Generate a new array from an array of numbers

I found this question on Glassdoor :

Create a new array from an array of numbers. Start from the beginning. First put the number of some number, and then this number. For example, from the array 1, 1, 2, 3, 3, 1 you should get 2, 1, 1, 2, 2, 3, 1, 1 Write a program to solve this problem.

I'm not sure if I get the idea why 1, 1, 2, 3, 3, 1 is converted to 2, 1, 1, 2, 2, 3, 1, 1? At first I thought it was the number of occurrences of a number, followed by the number itself. But from this example, it seems that something else is needed.

What kind of transformation is this?

+4
source share
3 answers

At first I thought it was the number of occurrences of a number, followed by the number itself.

Your first thought was correct.

Break the first array below:

1, 1, 2, 3, 3, 1 

And the second:

 2, 1, 1, 2, 2, 3, 1, 1 

Then it should make sense.

Implementation Example:

 #!/usr/bin/env python import sys array = map(int, sys.argv[1:]) print array count = 0 current = array[0] index = 1 output = [] for number in array: if current != number: output.append(count) output.append(current) current = number count = 0 count += 1 output.append(count) output.append(current) print output 

Demo:

 > ./arrays.py 1 1 2 3 3 1 [1, 1, 2, 3, 3, 1] [2, 1, 1, 2, 2, 3, 1, 1] 
+2
source

what do you think right. its number of times when a single element occurs, and then the element itself.


here's the pseudo code:

 array1 = given input array array2 = output array int previous = array1[0]; int currentCount = 0; for each entry x in array1 { if(x == previous) { currentCount++; } else { array2.add(currentCount); array2.add(x); //reset global variables for next elements previous = x; currentCount = 0; } } 
0
source

And the Haskell version ... yes, that's it.

 import Data.List countArray list = concat [[length l, fromIntegral (head l)] | l <- group list] 
0
source

All Articles