How can I make my text behave in accordance with gravity?

Caché

Hi, Community!

And so I continue with publishing of the tasks for the Final round of InterSystems Contest on InterSystems Caché and DeepSee as a part of IT Planet Student Championship in Sochi. This year we had about 2 000 participants in InterSystems Contest.

One of the tasks for the finals was to crack the black box and another to output 9876543210!

Here's the next task: gravity!

Let's consider this text:

Championship
IT
Planet
2017

Have you noticed that it does not behave in accordance with gravity? If it was, it would have looked like this:

Ch
ITam
Planpi
2017etonship

Your goal is to write a shortest solution that transforms the text in accordance with laws of physics, namely gravity.

Sample call:

Set Text(1) = "Championship"
Set Text(2) = "IT"
Set Text(3) = "Planet"
Set Text(4) = "2017"

Do ##class(ITPlanet.Task3).Main(.Text)
Zw Text

Text(1)="Ch"
Text(2)="ITam"
Text(3)="Planpi"
Text(4)="2017etonship"

Here's a method signature (it can't be modified):

ClassMethod Main(ByRef Text)
  • + 1
  • 0
  • 188
  • 1
  • 2

Answers

ClassMethod Main(ByRef Text)
{
f i=1:1:$o(Text(""),-1)-1 s t=$l(Text(i+1))+1 s:$l(Text(i))+1>t $e(Text(i+1),*+1)=$e(Text(i),t,*),$e(Text(i),t,*)="",i=1
}

It's the wrong solution, because it works not for all cases such as this:

Set Text(1) = "Planet"
Set Text(2) = "Championship"
Set Text(3) = "2017"
Set Text(4) = "IT"

Here is more optimized code Sean:

ClassMethod Main(ByRef Text)
{
 f j=2:1:$o(Text(""),-1) f k=j:-1:2 s l=$l(Text(k))+1,$e(Text(k),l)=$e(Text(k-1),l,*),$e(Text(k-1),l,*)=""
}
ClassMethod Main(ByRef Text)
{
  s i=$o(Text(""),-1) j=1:1:k=i:-1:2 l=$l(Text(k))+1,$e(Text(k),l)=$e(Text(k-1),l,*),$e(Text(k-1),l,*)=""
}