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:
- Input is only made of digits [0-9]
- Zero returns an empty string
- Use this code to check the result length
- You also can use this test case here
Comments
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 ]
{
f
}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 JHere'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 JAnd, 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 JEnjoy!
[edited to add other cases.]
Nice!
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)
}s=9999999999999999999
![]()
![]()
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 resultThe 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 = 171So why do you show those devils?
codemode = code:
ClassMethod AddWater(
s,
t = {$lb("",1,22,333,4444,55555,666666,7777777,88888888,999999999)},
r = "") As %String
{
f i=1:1:$l(s) s r=r_$li(t,$e(s,i)+1)
q r
}codemode = expression:
ClassMethod AddWater(
s,
r = {"" s r="" f i=1:1:$l(s) s t=$e(s,i) s: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(s) As %String
{
f i=$l(s):-1:1 s t=$e(s,i),$e(s,i)=$$DC(t,t)
q s
}
}Neat trick for the expression for r! (Which I hope to never see again outside of the context of contests like this. :))