I have a task where I need to generate all possible combination of numbers from 0-0-0 to 100-100-100 (x,y,z)
var x = 0
var y = 0
var z = 0
while(true){
x++
while(true){
y++
while(true){
z++
msg.payload = [x,y,z]
node.send(msg)
}}}
The problem I have is that the x and y values never change (only once when input)... I think this is not an efficient way of doing this, any suggestion?
If you know the number of iterations it's simpler to use for loop:
for (let x = 0; x <= 100; ++x) {
for (let y = 0; y <= 100; ++y) {
for (let z = 0; z <= 100; ++z) {
msg.payload = [x,y,z]
node.send(msg)
}
}
}
for (let x = 0; x <= 3; ++x) {
for (let y = 0; y <= 3; ++y) {
for (let z = 0; z <= 3; ++z) {
// msg.payload = [x,y,z]
// node.send(msg)
console.log({ payload: [x, y, z] });
}
}
}
Of course, you could use your while loop instead but you have to remember to break after 100 iterations:
let x = 0;
while(true) {
let y = 0;
while(true) {
let z = 0;
while(true) {
msg.payload = [x,y,z]
node.send(msg);
if (z === 100) break;
z++;
}
if (y === 100) break;
y++;
}
if (x === 100) break;
x++;
}
let x = 0;
while(true) {
let y = 0;
while(true) {
let z = 0;
while(true) {
// msg.payload = [x,y,z]
// node.send(msg);
console.log({ payload: [x, y, z] });
if (z === 3) break;
z++;
}
if (y === 3) break;
y++;
}
if (x === 3) break;
x++;
}
Or you use the inverted break condition for the while condition:
let x = 0;
while(x <= 100) {
let y = 0;
while(y <= 100) {
let z = 0;
while(z <= 100) {
msg.payload = [x,y,z]
node.send(msg);
z++;
}
y++;
}
x++;
}
let x = 0;
while(x <= 3) {
let y = 0;
while(y <= 3) {
let z = 0;
while(z <= 3) {
// msg.payload = [x,y,z]
// node.send(msg);
console.log({ payload: [x, y, z] });
z++;
}
y++;
}
x++;
}