简体   繁体   中英

Not sure why but my code is breaking the command prompt (possible infinite loop)

So I've been having a go at the advent of code challenges. Currently I'm on day 2 and there seems to be an issue with the following code when I run it through node.js on the command prompt:

 const fs = require("fs"); var valid = fs.readFileSync("input2.txt", "utf8") var validArr = valid.split("\n") function validate() { var validPasswords = 0 for (var i = 0; i < validArr.length;i++) { var low = validArr[i].match(/\d+/g)[0]; var high = validArr[i].match(/\d+/g)[1]; var password = validArr[i].match(/[a-zA-Z]+/g)[1]; var letter = validArr[i].match(/[a-zA-Z]+/g)[0]; if (test(password, low, high, letter)) { validPasswords++ } } console.log(validPasswords); } test = function(password, low, high, letter) { var count = 0 for (i=0; password.length; i++) { if (password.charAt(i) === letter) { count++ } } if (low <= count && count <= high) { return true } else { return false } } validate();

The problem arises when I move the if (low <= count && count <= high) statement out of the for loop in the function "test". Anyone know why this is the case?

Your for loop's condition is incorrectly set:

for (i=0; password.length; i++) {

You are saying that as long as password.length is true, keep looping. So, as long as password.length is not zero, it converts to true and you loop forever.

What you should be doing is saying that as long as the loop counter ( i ) is less than the password.length keep looping:

for (i=0; i < password.length; i++) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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