廢話
在[codewar][1]上做練習,每次都是盡量快速地做完,然后趕着去看排名里面clever分最高的solution,看完每次都要感嘆一下人家怎么可以寫得這么簡潔,甚至有一次我用了一段大約七八行的代碼,別人只用了一行就搞定了。下午做了幾個練習,依然是這樣的感受,拎出來一個記下來鞭策一下自己。
問題
原題長這樣:
Vampire Numbers
Our loose definition of Vampire Numbers can be described as follows:
6 * 21 = 126
# 6 and 21 would be valid 'fangs' for a vampire number as the
# digits 6, 1, and 2 are present in both the product and multiplicands
10 * 11 = 110
# 110 is not a vampire number since there are three 1's in the
# multiplicands, but only two 1's in the product
解決
這是我寫的代碼:
var vampire_test = function(a, b){
var mul=(a*b).toString().split('').sort();
var pro=(a.toString()+b.toString()).split('').sort();
if(mul.length!==pro.length){
return false;
}else{
for(var i=0;i<mul.length;i++){
if(mul[i]!=pro[i])
{
return false;
}
}
return true;
}
}
可以看出真的很大一段,雖然實現了功能......
然后,這是clever最高分的solution:
function vampire_test(a, b){
return sortStr(a + '' + b) == sortStr(a * b + '');
}
function sortStr(v){ return v.split('').sort().join('') }
總結
我對比了一下,發現我的答案里,第一步和別人是類似的:將字符串轉成數組然后排序,獲得兩個排過序的數組mul和pro。但是接着我最瑣碎的一步在於進行mul和pro間的比較,因為引用類型的比較不能直接用“”進行,所以我只好挨個遍歷值去比較。
但是別人的solution里,又將排過序的數組join成字符串了,直接用“”比較,簡單多了。
然后我回想了一下,發現自己經常想不起來用join這個函數,總是笨拙地在循環里用str+=“aaa”。
比如說另外一個練習:
Description:
Here we have a function that help us spam our hearty laughter. But is not working! I need you to find out why...
Expected results:
spam(1);//hue
spam(6);//huehuehuehuehuehue
spam(14);//huehuehuehuehuehuehuehuehuehuehuehuehuehue
這是我的做法:
function spam(number){
var str="";
for(var i=1;i<=number;i++){
str+="hue";
}
return str;
}
然后別人用join函數只用了一行代碼就解決了:
function spam(number){
return Array(++number).join("hue");
}
說明
join函數:
定義和用法
join() 方法用於把數組中的所有元素放入一個字符串。
元素是通過指定的分隔符進行分隔的。
語法
arrayObject.join(separator)
separator可選。指定要使用的分隔符。如果省略該參數,則使用逗號作為分隔符。
[1]: http://www.codewars.com/