Home > OS >  Write a program that generate part of this sequence 122333444455555
Write a program that generate part of this sequence 122333444455555

Time:11-01

Write a program that prints a part of the following sequence 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (the number of repetitions is equal to the respective number). Input is a positive integer n – the number of the elements of the sequence that the program should print. Output the sequence of numbers, written in a single line, separated by spaces. The idea here is to use while loop instead of for loop.

For example, if n is 7, the program should output 1 2 2 3 3 3 4 (seven numbers).

SAMPLE INPUT: 8

SAMPLE OUTPUT: 1 2 2 3 3 3 4 4

I tried to write this code:

fun main() {
    val input = readLine()!!.toInt()
    var counter = 0
    var i = 0
    var j = 0
    while(i <= input) {
        while(j <= i) {
            counter  
            print("$i ")
            j  
        }
        i  
    }
}

But instead of getting 1 2 2 3 3 3 4 4
I get this output 0 1 2 3 4 5 6 7

CodePudding user response:

fun main() {
    
    val input = readLine()!!.toInt()
   var counter = 1
   var i = 1
   var j = i
    while(counter <= input) {
     j = i
     while(j > 0 && counter <= input) {
        print("$i ")
        j--
        counter  
    }
    i  
}
    
}

Another solution with O(n) time complexity with extra space.

fun main() {
        val input = readLine()!!.toInt()
        var counter = 1
        var printed = 0 
        var map = mutableMapOf<Int,Int>()
            while (printed < input) {
                print("$counter ")
                printed  
                if(map[counter] ?: 0 < counter - 1) {
                    map[counter] = if(map[counter] == null) 1 else (map[counter] ?: 0)   1
                    continue
                } else {
                    counter  
                }
            }
    }
  • Related