Discussion
· Nov 17, 2021

Code Golf - Encoder

We need to send some coordinates to a spaceship through a laser beam.
To do that we have to encode it, and beam it out into space.
Your mission is to implement the encoder with a compression standard.
As usual shortest solution wins.

Task

You will receive a string of comma-separated integers and you will return a new string of comma-separated integers and sequence descriptors.

Input

"0,2,4,5,5,5,5,5,3,4,5"

Output

"0-4/2,5*5,3-5"

Note

  • Compression happens left to right
  • A sequence of 2 or more identical numbers is shortened as number*count
    • example: "5,5,5" is compressed to "5*3"
  • A sequence of 3 or more consecutive numbers is shortened as first-last. This is true for both ascending and descending order
    • example: "1,3,4,5" is compressed to "1,3-5"
  • A sequence of 3 or more numbers with the same interval is shortened as first-last/interval.
    • example: "0,2,4,6" is compressed to "0-6/2"
  • Use this code to check the result length
  • You also can use this test case here

Rules

  1. The signature of the contest entry MUST be:
Class dc.golf.Encoder {

ClassMethod Compress(a)
{
}

}
  1. It is forbidden to modify class/signature, including but not limited to:
  • Adding inheritance
  • Setting default argument values
  • Adding class elements (Parameters, Methods, Includes, etc).
  1. It is forbidden to refer to non-system code from your entry. For example, this is not a valid entry:
ClassMethod Compress(a)
{
  q ##class(myPackage.myClass).test(a)
}
  1. The use of $ZWPACK and $ZWBPACK is also discouraged.
Discussion (8)4
Log in or sign up to continue

Ok.

 
size = 190
 
size = 189

Hi Vitaliy,

Out of curiosity I had a go at this. I can't get under 188 using my own ideas and code:

c=",",x=$p(a,c,$i(i)) q:x="" f{y=$p(a,c,$i(j)+i),g=$g(g,y-x) q:j*g+x'=y  l=yg=$zabs(g),$p(o,c,$i(p))=s:2-'g<j o=o_$s(g:"-"_l_$s(g>1:"/"_g,1:""),1:"*"_j),i=i+j-1g,1

You could shave 2 characters off each of your versions by having a variable contain the comma:

x=",",a=$p(s,x,$i(i)),d=$p(s,x,i+1)-c=1:1{q:d*c+a'=$p(s,x,i+c)q=$zabs(d),v=$s(c>2&d:"-"_(c-1*d+a)_$s(q=1:"",1:"/"_q),c>1&'d:"*"_c,1:0) s:v'=0 $p(s,x,i,i+c-1)=a_q:a="" a

185 - with an unusual use of $PIECE instead of $SELECT to save 2 characters, which would also shorten yours to 184

c=",",x=$p(a,c,$i(i)) q:x="" f{y=$p(a,c,$i(j)+i),g=$g(g,y-x) q:j*g+x'=y  l="-"_yg=$zabs(g),$p(o,c,$i(p))=s:2-'g<o=o_$s(g:l_$p("/"_g,c,g>1),1:"*"_j),i=i+j-1 g,1

i=1:1:2e6{x=",",a=$p(s,x,i),d=$p(s,x,i+1)-c=1:1{q:d*c+a'=$p(s,x,i+c)q=$zabs(d),v=$s(c>2&d:"-"_(c-1*d+a)_$p("/"_q,x,q>1),c>1&'d:"*"_c,1:0) s:v'=0 $p(s,x,i,i+c-1)=a_vs