Eduard Lebedyuk · Oct 8, 2021

Code Golf: Just add water...

Have you ever seen those vaccum compressed towels, that look like a pill and after you add water became a towel?

That's our challenge for today. As usual shortest solution wins.


You will receive an integer number and you will return a new number where each digit is repeated a number of times equals to its value.






0 352
Discussion (11)3
Log in or sign up to continue

Edit: down from 73 to 67 to 58 (but still looking for better...)

Missing an important test case:
Do $$$AssertEquals(##class(CodeGolf.MagicTowel).AddWater("00020"), "22")

Gaming the system and using the code provided to check the result length, 3:

ClassMethod AddWater(p As %String, t = {$e(p)}, r = {$case(p,"":"",:..AddWater($e(p,2,*)))}, f = {$Select(t:$tr($j(t,t)," ",t)_r,1:r)}) As %String [ CodeMode = expression ]

Yeah, zeroes make $tr($j()) trick less applicable to the current challenge.

43, if you have to read in the variable. -4 if it's assumed to already be there. +4 if you need to see a carriage return between the input and the output:

R Z F I=1:1:$L(Z) S J=$E(Z,I) F K=1:1:J W J

Here's the '-4' code if you assume the Z variable has the initial integers:

F I=1:1:$L(Z) S J=$E(Z,I) F K=1:1:J W J

And, here's the +4 code to add the carriage return between input & output:

R Z W ! F I=1:1:$L(Z) S J=$E(Z,I) F K=1:1:J W J


[edited to add other cases.]

Check this one...

ClassMethod AddWater(s)
   f i=$l(s):-1:1 s t=$e(s,i),$e(s,i)="1E"_t-1/9*t
   q $tr(s,0)

Oh, I see right now, we can save one byte...

ClassMethod AddWater(s)
   f i=$l(s):-1:1 s t=$e(s,i),$e(s,i)=10**t-1/9*t
   q $tr(s,0)

According to the task, "...You will receive an integer number and you will return a new number..."

set s=9999999999999999999
write s --> 10000000000000000000
write AddWater(s) --> 1  // which is the expected result

The above method works also for cases, where s contains a string of digits

set a="9999999999999999999"
write a  --> 9999999999999999999
set res=AddWater(s)
write res ---> 999...<165 more nines>...999
write $length(s) --> 19
write $length(res) --> 171  // 19 * 9 = 171

So why do you show those devils?

codemode = code:

ClassMethod AddWater(
  = {$lb("",1,22,333,4444,55555,666666,7777777,88888888,999999999)},
  ""As %String

codemode = expression:

ClassMethod AddWater(
  = {"" r="" i=1:1:$l(st=$e(s,is:t r=r_$tr($j(t,t)," ",t)}) As %String CodeMode = expression ]

Required mapping ISCDC.inc from CACHESYS:

Include ISCDC

Class dc.test Abstract ]

ClassMethod AddWater(sAs %String
  i=$l(s):-1:1 t=$e(s,i),$e(s,i)=$$DC(t,t)


Neat trick for the expression for r! (Which I hope to never see again outside of the context of contests like this. :))