Home > Software design >  Algorithm:Three numbers multiply through three loop?
Algorithm:Three numbers multiply through three loop?

Time:06-20

I need to compute data based on three integers

For example: A:001 B:002 C: 003.I'm going to get 1 times 2 times 3, six pieces of data

The result like: Arr = [1-1-1, 1-1-2, 1-1-3, 1-2-1, 1-2-2, 1-2-3]; This is my code

  for (let index = 1; index < 2; index  ) {
    for (let indexB = 1; indexB < 3; indexB  ) {
      for (let indexC = 1; indexC < 4; indexC  ) {
        console.log(`${index}-${indexB}-${indexC}`);
      }
    }
  }

Yes, it uses 3 for loops.Is there a more efficient algorithm?

CodePudding user response:

No.

Given the 3 inputs, the number of items in the result will be those 3 inputs multiplied together. There's no way around that - any possible algorithm will have to iterate A * B * C times (if that's what we label the numbers as).

Three nested for loops, where one iterates A times, another iterates B times, and another iterates C times produces that result. There's no sensible way of changing the algorithm by reducing the number of nested loops; the nested loops already iterate exactly the number of times required, and no more. That's about as efficient as you can get, computational complexity wise.

  • Related