2016-05-13 60 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。但是,它尚未经过测试。