170k views
1 vote
Assume that someone dictates you a sequence of numbers and you need to write it down. For brevity, he dictates it as follows: first says the number of consecutive identical numbers and then says the number itself. E.g. The sequence 1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2 will be dictated as "Two ones, three threes, four twos, three fourteens, three elevens, one two", so you will write down the sequence 2 1 3 3 4 2 3 14 3 11 1 2. The challenge is to write the program which compresses the given sequence using this approach.

1 Answer

2 votes

Answer:

Answer is in java language

Step-by-step explanation:

Java Code

public class Compress{

public static void main(String []args){

int[] array=new int[]{1 ,1 ,3 ,3, 3, 2, 2, 2, 2, 14, 14, 14, 11, 11, 11, 2};

int currentNumber=array[0];

int count=1;

for(int i=1;i <array.length;i++){

if(currentNumber != array[i]){

System.out.print(count+" " +currentNumber+" ");

currentNumber=array[i];

count=1;

} else{

count++;

}

}

System.out.print(count+" " +currentNumber+" ");

}

}

Code Explanation

First create two variables which will hold the current number and its count and then iterate over every element in array. If current index value is different from currentNumber variable then display the previous calculated number value and its count and then change the value to current index of array.

At the end display the last calculated value.

Example

Answer will look like below

2 1 3 3 4 2 3 14 3 11 1 2

User Venkatesh Panabaka
by
4.8k points