Discussion
· 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.

Task

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.

Input:

42

Output:

444422

Note:

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

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

Enjoy!

[edited to add other cases.]

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(
  s,
  = {$lb("",1,22,333,4444,55555,666666,7777777,88888888,999999999)},
  ""As %String
{
 i=1:1:$l(sr=r_$li(t,$e(s,i)+1)
 r
}

codemode = expression:

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

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)
  s
}

}