I have the following code which includes a varying number (nk) of if-else conditions.
var n = 128; // n is 128 or greater.
var nk = 4; // nk is varying, can be 4,6,8,12,16 etc. smaller than n.
for (let i = 1; i <= n; i++) {
if ((i < 1 * n / nk) { ... }
else if (i < 2 * n / nk) { ... }
else if (i < 3 * n / nk) { ... }
else if (i < 4 * n / nk) { ... }
}
Is it possible to turn the if-else statements into a for loop (or anything else) so that it can work with varying nk? Right now, to account for varying nk values, I have to write multiple for loops with if-else statements.
I tried the following, which obviously does not work:
for (let i = 1; i < nk; i++) {
if (x < i * n / nk)) { /* code here is a function of i */ }
}
3
Answers
After further trial and error, I reached the following solution, which works as I needed. The key point was to use closed interval check inside
if
; and use ofbreak
for better performance:Apologies for not properly expressing my question, this question may either be closed or kept if the answer might be useful to anyone else in the future.
Yes, it is possible to convert the varying-length if-else statement into a for loop. However, you need to modify the loop condition and the if condition to accommodate the varying nk value
Calculate the value of i as indicated in @tevemadar s comment, then perform your function of i