虽然循环不执行或不循环

While loop not executing or not looping?

本文关键字:循环 执行      更新时间:2023-09-26
// 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是否接受这种条件。然而,在红宝石中它奏效了。有人可以为我解释为什么不工作吗?

您错过了一个括号来关闭 while 循环条件参数。你的代码应该真的是:

while(check_coins(hand)){
  ... 
 }

如果这不起作用,那可能是条件本身。尝试:

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

while语句应该像这样修复:

while (check_coins(hand)) {

似乎check_coins功能只是检查第一个硬币,应该更改为检查所有硬币。 它还返回整数、布尔值或 null 值中的任何一个,具体取决于条件 - 它应该只返回一个整数(第一个非零硬币的索引(或 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。 然而,它还没有经过测试。