Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was trying to solve a puzzle, using javascript. currently, this code doesn't run, at all. I tried to tweak the numbers in the for loops, but the page doesn't want to load. I have tried to remove the script part of the HTML, and it loaded, so I know at least that the code below is the problem.
JavaScript
var lockers = [];

function studentAI(id, locker) {
    if (locker % id && locker >= id) {
        if (lockers[id] = false) {
            lockers[id] = true;

        } else {
            lockers[id] = false;
        }

    }

}

for (var student = 1; student <= 10; student++) {
    
    for (var locker = 1; locker <= 10; locker++) {
        if (student = 1) {
            lockers[locker] = true;
        } else {
            studentAI(student, locker);
        }
    }

}
for (let index = 0; index < lockers.length; index++) {
    console.log(lockers[index]);
}

Thanks!

What I have tried:

I tried to tweak the numbers in the for loops, but the page doesn't want to load. I have tried to remove the script part of the HTML, and it loaded, so I know at least that the code below is the problem.
Posted
Updated 14-Mar-22 0:23am

ADDED: What follows is wrong, and not the solution!


if (locker % id && locker >= id) {

I can't even guess what is intended here, but it isn't acceptable JavaScript code.

&& is a diadic operator, it expects two boolean operands, things that are either true or false; locker % id is a number, not a boolean.
 
Share this answer
 
v3
Comments
Richard Deeming 14-Mar-22 6:18am    
In most languages, that would be correct. But Javascript is "special" - the && operator will return true if both operands are "truthy" values.

Truthy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN[^]

So locker % id && locker >= id is equivalent to (locker % id != 0) && locker >= id.
Luc Pattyn 14-Mar-22 6:40am    
You're right of course; I forgot about the JavaScript idiosyncrasies.
Your script is hanging because you have introduced an infinite loop:
Quote:
JavaScript
if (student = 1) {
This statement sets the student variable to 1, and then tests whether the assigned value is truthy[^].

Your outer loop will never terminate, because on every iteration you are resetting the loop variable.

Javascript uses == (or ===) to test for equality:
JavaScript
if (student === 1) {
 
Share this answer
 
Comments
Luc Pattyn 14-Mar-22 6:40am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900