2016-05-13 57 views
1
// require '04_wonky_coins' 
// require 'rspec' 
// 
// # Catsylvanian money is a strange thing: they have a coin for every 
// # denomination (including zero!). A wonky change machine in 
// # Catsylvania takes any coin of value N and returns 3 new coins, 
// # valued at N/2, N/3 and N/4 (rounding down). 
// # 
// # Write a method `wonky_coins(n)` that returns the number of coins you 
// # are left with if you take all non-zero coins and keep feeding them 
// # back into the machine until you are left with only zero-value coins. 
// # 
// # Difficulty: 3/5 
// 
// describe "#wonky_coins" do 
// it "handles a coin of value 1" do 
//  wonky_coins(1).should == 3 
// end 
// 
// it "handles a coin of value 5" do 
//  wonky_coins(5).should == 11 
//  # 11 
//  # => [2, 1, 1] 
//  # => [[1, 0, 0], [0, 0, 0], [0, 0, 0]] 
//  # => [[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]] 
// end 
// 
// it "handles a coin of value 6" do 
//  wonky_coins(6).should == 15 
// end 
// 
// it "handles being given the zero coin" do 
//  wonky_coins(0).should == 1 
// end 
// end 
function check_coins(hand){ 
    for(var i=0; i<hand.length; i++){ 
    var coin = hand[i] 
    if(coin !==0){ 
     return i; 
    } else { 
     return null; 
    } 
    } 
    return false; 
} 


function wonkyCoins(n){ 
    var hand = []; 

    hand.push(Math.floor(n/2)); 
    hand.push(Math.floor(n/3)); 
    hand.push(Math.floor(n/4)); 




while(check_coins(hand){ 

    var indx = check_coins(hand); 


    var value = hand[indx]; 

    var index1 = hand.indexOf(hand[indx]); 

    if (index1 > -1) { 
    hand.splice(index1, 1); 
    } 


    hand.push(Math.floor(value/2)); 
    hand.push(Math.floor(value/3)); 
    hand.push(Math.floor(value/4)); 

} 

return hand.length; 

} 

該程序正在工作,但由於某些原因while循環沒有循環。我懷疑這種情況有什麼問題。我不確定如果javaScript接受這樣的條件。但是,在ruby中它工作。 有人可以請爲我解釋爲什麼不工作?while循環沒有執行或不循環?

+1

在while條件中是否有缺少的右括號? – joshuanapoli

回答

2

你錯過了一個括號來關閉你的while循環條件參數。您的代碼應該是:

while(check_coins(hand)){ 

    ... 

} 

如果這樣不起作用,則可能是條件本身。請嘗試:

while(check_coins(hand) !== null){ 

... 

} 
+0

非常感謝,是的,這是第二種選擇。 –

0

while聲明應該是固定的這樣的:

while (check_coins(hand)) { 

它也出現了check_coins功能只檢查第一硬幣,應加以改變,以檢查他們。它還根據條件返回整數,布爾值或空值中的任何一個 - 它應該只返回一個整數(第一個非零硬幣的索引)或null(非零硬幣)。

固定的代碼應該是這樣的:

function check_coins(hand){ 
    for (var i=0; i < hand.length; i++) { 
     if (hand[i] > 0) { 
      return i; 
     } 
    } 
    return null; 
} 

function wonkyCoins(n) { 
    var hand = []; 

    hand.push(Math.floor(n/2)); 
    hand.push(Math.floor(n/3)); 
    hand.push(Math.floor(n/4)); 

    while ((indx = check_coins(hand)) != null) { 
     var value = hand[indx]; 
     var index1 = hand.indexOf(hand[indx]); 

     if (index1 > -1) { 
      hand.splice(index1, 1); 
     } 

     hand.push(Math.floor(value/2)); 
     hand.push(Math.floor(value/3)); 
     hand.push(Math.floor(value/4)); 
    } 

    return hand.length; 
} 

的代碼已經被清理,以使其更具可讀性和慣用的JavaScript。但是,它尚未經過測試。