skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 of break for better performance:

    n = 128;
    var nk = 4;
    
    for (let i = 1; i <= n; i++) {
        let nkk = n / nk;
    
        for (let k = 0; k < nk; k++) {
            if (i > k * nkk && i <= (k + 1) * nkk) {
                // ...
                break;
            }
        }
    }
    

    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.


  2. 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

    var x, n; // defined before
    var nk = 4;
    
    for (let i = 0; i < nk; i++) {
        if (i === nk - 1 || x < (i + 1) * n / nk) {
            // Code here is a function of i
            break;
        }
    }
    Login or Signup to reply.
  3. Calculate the value of i as indicated in @tevemadar s comment, then perform your function of i

    const i = Math.floor(x/(n*nk));
    myFunctionOfI(i);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search