Home > front end >  How to send the output of the FOR loop as the input to itself in Scala?
How to send the output of the FOR loop as the input to itself in Scala?

Time:12-16

Add elements to the array buffer such that the element to be added is the product of the previous two elements of the input array buffer. The elements in the output array buffer should not exceed 10000.

Input ArrayBuffer:- ArrayBuffer(2, 3) Expected Output ArrayBuffer:- ArrayBuffer(2, 3, 6, 18, 108, 1944) Actual Output ArrayBuffer:- ArrayBuffer(2, 3, 6, 18)

def main(args: ArrayBuffer[Int]): Unit = {
    for(k <- 1 to args.length if(args(k) < 10000)){
      args  = args(k)*args(k-1)
    }
    println(args)
  }

Here I took args from main function as input to the for block. Then it calculates and appends the result to args only upto the previous length of the input say (2, 3) that is 2. But the length should increase as the elements keep appending to the arraybuffer. Say after the 1st iteration args will be (2, 3, 6, 18). Now this should be fed as input to the FOR block and it should continue till last value reaches closest min value to 10000.

If I find solution for this, I will update here. Until then, please help me solving this

  • Related