# Run-Length Encoding [duplicate]

Write a program uses run-length encoding to shorten a list of non-negative integers it has to read in.

You can assume the non-negative integers can fit in 32bit signed integers.

Input Format

The length, n, of the list on the first line.

On the second line, a space-separated list of integers representing the list of integers.

Output Format

A space separated list of integers. The first 2 integers represent the first run, the next 2 integers the second run and so on. For each pair of integers representing a run, the first integer represents the length of the run and the second represents the value of the integer in the run.

Sample Input

1.

5
1 1 3 2 2


2.

3
1 1 1


Sample Output

1.

2 1 1 3 2 2


2.

3 1


Limits

0<n<10000

• Similar to golf.shinh.org/p.rb?Look+and+say and stackoverflow.com/questions/3908513/code-golf-morris-sequence – Nabb Feb 18 '11 at 10:08
• I think you should give a more tricky input, like 36/1 1 1 1 1 1 3 3 3 3 3 2 2 7 7 7 7 4 4 9 9 9 9 9 9 9 9 9 4 4 8 3 3 3 3 0, giving 6 1 5 3 2 2 4 7 2 4 9 9 2 4 1 8 4 3 1 0, to ensure correct output when there are several distinct sequences of same number. – PhiLho Jul 28 '11 at 19:55

# sh - 3329 28

read;echoxargs -n1|uniq -c


Usage:

$cat input|sh 1015.sh 2 1 1 3 2 2  • read skips the first line • xargs -n1 reads the reast and outputs each number on one line: 1 1 3 2 2  • uniq -c filters adjacent matching lines (with the c switch it also prints the number of adjancent lines) : 2 1 1 3 2 2  • echo sees those numbers as separate arguments and just prints them separated by a space: 2 1 1 3 2 2  • WTF? How is that possible? – FUZxxl Feb 18 '11 at 20:16 • added explanations :-) – Arnaud Le Blanc Feb 18 '11 at 20:26 • Very nice! (more chars) – J B Feb 18 '11 at 20:50 • You might be able to replace tail -n1| with a well-placed read; – J B Feb 18 '11 at 20:52 • And the tr can be replaced with an xargs. read;echoxargs -n1|uniq -c for 28 characters. – J B Feb 18 '11 at 21:03 ## Perl, 46 5668 $_=<>;s/(?{$a=1})(\d+)( \1(?{++$a}))*/$a$1/g


Run with the p command-line option (counted in code size):

$perl -pe '$_=<>;s/(?{$a=1})(\d+)( \1(?{++$a}))*/$a$1/g'
5
1 1 3 2 2
=> 2 1 1 3 2 2
3
1 1 1
=> 3 1


import List
main=interact$unwords.(>>= \x->[show$length x,x!!0]).group.tail.words


Number of elements in the list is ignored.

# Ruby - 57

$><<[*$<][-1].gsub(/(\d+)( \1)*/){"#{$&.split.size} "+$1}


Ungolfed:

length = STDIN.readline