简体   繁体   English

变量在while循环中不改变

[英]variable not changing in while loop

I am trying challenges in order to practice, learn, and better understand coding. 我正在尝试挑战,以便练习,学习和更好地理解编码。 I came across a hard and decided to try it, just to see. 我遇到了困难,决定尝试一下,只是为了看看。 It has no time limit luckily. 幸运的是没有时间限制。 The challenge was (you can skip if you wish) 挑战是(您可以根据需要跳过)

"Using the JavaScript language, have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), and subtract the smaller number from the bigger number. Then repeat the previous step. Performing this routine will always cause you to reach a fixed number: 6174. Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174). Your program should return the number of times this routine must be performed until 6174 is reached. For example: if num is 3524 your program should return 3 because of the following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174." “使用JavaScript语言,使函数KaprekarsConstant(num)接受传递的num参数,该参数将是一个4位数字,至少包含两个不同的数字。您的程序应对该数字执行以下例程:将数字降序排列按升序(将零添加到4位数字中),然后从较大的数字中减去较小的数字,然后重复上一步。执行此例程将始终使您达到固定的数字:6174。然后在6174上执行例程将始终为您提供6174(7641-1467 = 6174)。您的程序应返回该例程必须执行的次数直到达到6174.例如:如果num为3524,则您的程序应返回3,因为以下步骤之一:(1)5432-2345 = 3087,(2)8730-0378 = 8352,(3)8532-2358 =6174。”

(coderbyte) (编码字节)

After working for a long while, I had found something that I imagined would work. 工作了很长一段时间后,我发现了一些我想像的东西。 I could not test the loop yet though, because if I did I could not rerun the code, because the loop was incomplete and would never finish processing. 不过,我还无法测试循环,因为如果这样做,我将无法重新运行代码,因为循环不完整并且永远无法完成处理。 After it was all finished, I tested it. 全部完成后,我对其进行了测试。 And I got 0, no matter what I tried. 不管我尝试什么,我都得到0。 If I entered letters I got an error, what should happen, but no matter what numbers I put, even the 4 digit one from the example. 如果输入字母,我会出错,但是应该怎么写,无论输入什么数字,即使示例中的4位数字也是如此。

Here is my code: 这是我的代码:

 function KaprekarsConstant(num) { var forD = []; var sNum = num.toString(); var result = 0; var chngdN = []; var trkr = 0; for (var i = 0; i < sNum.length; i ++) { forD.push(+sNum.charAt(i)); } for (var j = 0; j < sNum.length; j ++) { chngdN.push(+sNum.charAt(j)); } while(while(forD-chngdN === trkr){ forD = trkr.toString(); chngdN = trkr.toString(); forD = forD.split(""); chngdN = chngdN.split(""); forD = forD.sort(); chngdN = chngdN.sort(); forD = forD.reverse(); forD = forD.join(""); chngdN = chngdN.join(""); forD = parseFloat(forD); chngdN = parseFloat(chngdN); trkr = forD - chngdN; forD = trkr.toString(); chngdN = trkr.toString(); result = result +1; } // code goes here return result; } // keep this function call here KaprekarsConstant(readline()); 

I am just starting, so I really do not know what is wrong here. 我才刚刚开始,所以我真的不知道这里出了什么问题。 I would love it if someone could tell me what was wrong. 如果有人可以告诉我出了什么问题,我会喜欢的。 (I know that it sounds like I'm trying to seem like I don't understand any of it, but I really just don't have a firm grasp on everything I've learned yet. I learned it all in a short time). (我知道这听起来似乎是我似乎不了解其中任何一个,但是我真的只是对所学到的一切都没有足够的了解。我很快就学会了这一切。 )。 Thank you in advance. 先感谢您。

The following will solve the problem, first version was not actually an implementation of the requirements but this one is. 下面将解决问题,第一个版本实际上不是要求的实现,而这个是。

I used the following for this: 我为此使用了以下内容:

  1. Recursion (function calling itself until desired result) 递归(函数自行调用,直到获得所需的结果)

  2. Array.from and Number.prototype.toString to make sure the number string is 4 characters long. Array.fromNumber.prototype.toString以确保数字字符串的长度为4个字符。

  3. Ternary operator with direction that is an argument for sortNum to sort ascending or descending. 方向的三元运算符 ,是sortNum进行升序或降序排序的参数。

  const makeAtLeast4 = num => //number to string make sure you have a string that's 4 characters (add 0 if not) num.toString() + Array.from(//create an array from someghing new Array(//that something is a new array //the lenght of this array is 4 minus the length of the string 4-num.toString().length), ()=>"0"//for each item of the array insert the string "0" ).join("");//join this array (num 111 will be sring "1110") //create ascending or descending sorted number // if direction is 1 it's ascending const sortNum = (numString,direction) => parseInt( (direction === 1) //if direction is 1 do ? else do : ? numString.toString().split("").sort().join("") : numString.toString().split("").sort().reverse().join("") ,10//decimal number ); //take number, sort digits descending and ascending // substract ascending from descending const descending_minus_ascending = num => { const stringNum = makeAtLeast4(num); return sortNum(stringNum) - sortNum(stringNum,1) } const kaprekarsConstant = (num,times=0) => { //get result for this number const result = descending_minus_ascending(num); //if result is the same as the number, return times tried if(result === num){ return times } console.log(`Try:${times+1}, result:${result}`); //try again with the result and increase times tried by one // recursively call this function return kaprekarsConstant(result,times+1); } console.log(kaprekarsConstant(11)) 

[UPDATE] [更新]

Here is the code as a while loop, I would advice you to avoid any kind of loops until you've used recursion and array functions, these maybe take a bit longer to learn but let you write easier to understand code in the long run: 这是作为while循环的代码,我建议您在使用递归和数组函数之前避免任何形式的循环,它们可能需要更长的时间来学习,但从长远来看,可以让您编写更容易理解的代码:

const kaprekarsConstant = (num) => {
  //get result for this number
  //  !! notice that result is not a constant but a var
  //  we will have keep re assigning it, this can be confusing
  //  in complex code and should be avoided if possible
  //  with recursion we don't need to do this
  var result = descending_minus_ascending(num);
  var times=0;
  //keep re assigning result until it's same as num
  while(result !== num){
    console.log(`Try:${times+1}, result:${result}`);
    result = descending_minus_ascending(num);
  }
  return times;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM