14
\$\begingroup\$

In the game 2048, you have a grid, and you can move the elements in four directions. They all move in that direction as far as they can. For this challenge, you will be given a padded, square 2D string (either with newlines, or a list of strings), like so:

ab cd e 
 f ghij 
      kl
mno p   
 q r st 
u      v
 w x  y 
z       

or

['ab cd e ', ' f ghij ', '      kl', 'mno p   ', ' q r st ', 'u      v', ' w x  y ', 'z       ']

The four operations are left, right, up, and down. The result of each on the above input:

Left:

abcde   
fghij   
kl      
mnop    
qrst    
uv      
wxy     
z       

or

['abcde   ', 'fghij   ', 'kl      ', 'mnop    ', 'qrst    ', 'uv      ', 'wxy     ', 'z       ']

Right:

   abcde
   fghij
      kl
    mnop
    qrst
      uv
     wxy
       z

or

['   abcde', '   fghij', '      kl', '    mnop', '    qrst', '      uv', '     wxy', '       z']

Up:

abocdiel
mf ghsjv
un rp k 
zq x  t 
 w    y 


        

or

['abocdiel', 'mf ghsjv', 'un rp k ', 'zq x  t ', ' w    y ', '        ', '        ', '        ']

Down:

        


 b    e 
af c  j 
mn gd k 
uq rhitl
zwoxpsyv

or

['        ', '        ', '        ', ' b    e ', 'af c  j ', 'mn gd k ', 'uq rhitl', 'zwoxpsyv']

Your goal is to rotate which operation is performed each iteration, performing them on the input n times. So if your order is URDL, and the input says to start with D (2, 0-indexed), and you need 5 operations, you perform D-L-U-R-D, then print.

Input:

  • A string in a format like above
    • Trailing spaces are not required (but they are probably helpful)
    • It will be at least 2x2
    • Will only contain printable ASCII and spaces (and newlines per your input format)
    • You should theoretically support any length, but memory constraints are okay
  • A non-negative integer, n, for the number of operations that will be performed
  • An integer 0-3 or 1-4, or a letter UDLR, describing the operation to start with.
    • So your program must be able to start or end with any operation
    • You may define them in any order for starting purposes, but it must be a consistent order, so U cannot sometimes follow R and also sometimes follow L.
  • Operations must be performed non-trivially
    • You could do operations in the order LDRU (left, down, right, up) repeatedly, but not DLRU or UDLR (because UD is the same as D, and LR is the same just as doing R.)

Output:

  • The string after performing the four operations n times
  • The output format must be the same as your input format
  • Trailing spaces are not required (but they are probably helpful)

Example:

This example uses the order URDL.

Input:

10  (number of times operations are applied)
0   (starts with Up)
ab cd e 
 f ghij 
      kl
mno p   
 q r st 
u      v
 w x  y 
z       

Outputs for n = 0-5: (just print the end result)

ab cd e 
 f ghij 
      kl
mno p   
 q r st 
u      v
 w x  y 
z       
---------------
abocdiel
mf ghsjv
un rp k 
zq x  t 
 w    y 



---------------
abocdiel
 mfghsjv
   unrpk
    zqxt
      wy



---------------



      el
    dijv
   chspk
 bognrxt
amfuzqwy
---------------



el      
dijv    
chspk   
bognrxt 
amfuzqwy
---------------
eljvkxty
disprqw 
chgnz   
bofu    
am      


        

My pretty, ungolfed implementation

\$\endgroup\$
5
  • \$\begingroup\$ Related, but different, because that one can have letters "fall off the map". \$\endgroup\$
    – mbomb007
    Mar 28, 2017 at 15:53
  • \$\begingroup\$ Related \$\endgroup\$
    – Laikoni
    Mar 28, 2017 at 16:01
  • 1
    \$\begingroup\$ Should be only print the final result, or the intermediate steps too? Also, isn't the result just cyclic after all four operations have been performed once? (Not sure, just guessing) \$\endgroup\$
    – Luis Mendo
    Mar 28, 2017 at 16:12
  • \$\begingroup\$ Just the end result. And I confirmed that it is not cyclic. \$\endgroup\$
    – mbomb007
    Mar 28, 2017 at 16:14
  • \$\begingroup\$ Not cyclic after only four operations, that is. The period will be much longer. \$\endgroup\$
    – mbomb007
    Mar 28, 2017 at 16:38

4 Answers 4

2
\$\begingroup\$

Jelly, 23 bytes

UZ
Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y

Try it online!

I'm a bit unsatisfied, but MATL needed some competition. :P

Uses the order URDL. Inputs:

  • the input array as an array of padded lines
  • the number of repetitions
  • the move to start from (1 = U, 2 = R, 3 = D, 4 = L)

Explanation

UZ       Helper link. Argument: A (the 2D array)
U        Reverse each line and...
 Z       ...transpose. Rotates 90° CCW.

Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y    Main link. Arguments: A, n (2D array, repetitions)
Ç                       Rotate 90° CCW...
 ¡                      ...m times. (m = which move to start on)

     Þ                  Sort...
      €                 ...each line of the array...
  =⁶                    ...based on the characters' equality to " ".
       Ç                Rotate 90° CCW.
        $               Combine the sort and rotate to one action.
         ⁴¡             Do that n times. (n = repetition count)

           Z            Transpose and...
            U           ...reverse each line. Rotates 90° CW.
             $          Combine the transpose and reverse to one action.
                  ¡     Do that...
              ⁵+⁴¤      ...m + n times.

                   Y    Join the array by newlines.
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 168 bytes

(n,d,s,t=s.replace([RegExp(`( )([^]{${l=s.search`
`}})(\\w)`),/(.)(\b)( )/,RegExp(`(\\w)([^]{${l}})( )`),/( )(\b)(.)/][d%4],`$3$2$1`))=>n?t!=s?f(n,d,t):f(n-1,d+1,s):s

Ungolfed:

function gravity(count, direction, string) {
    let width = string.indexOf('\n');
    let up = new RegExp('( )([^]{' + width + '})(\\w)');
    let down = new RegExp('(\\w)([^]{' + width + '})( )');
    while (count--) {
        let regexp = [up, /(.)(\b)( )/, down, /( )(\b)(.)/][direction++ % 4];
        while (regexp.test(string)) string = string.replace(regexp, '$3$2$1');
    }
    return string;
}

d is the initial index into the directions which are URDL.

\$\endgroup\$
1
\$\begingroup\$

Python 2, 226 224 204 193 bytes

-1 byte thanks to Trelzevir

x,s,n=input()
j=''.join
g=lambda x,i:[eval("j(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x]
for i in([0,3,1,2]*n)[s:s+n]:x=[map(j,zip(*g(map(j,zip(*x)),i))),g(x,i)][i>1];print'\n'.join(x)

Try it online!

Function that remove all spaces of each element in the list and complete with spaces on left or right.

g=lambda x,i:[eval("''.join(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x]

This to transpose (rotate 90º) when the input is 0 or 1(U or D) and apply g

x=[map(''.join,zip(*g(map(''.join,zip(*x)),i))),g(x,i)][i>1]
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Extra space in for i in (...). \$\endgroup\$
    – Trelzevir
    Mar 28, 2017 at 16:18
  • \$\begingroup\$ This is basically a golfed version of my implementation (I never bothered to golf it much). \$\endgroup\$
    – mbomb007
    Mar 28, 2017 at 16:31
1
\$\begingroup\$

MATL, 24 23 bytes

:+"@X!XJ_JXzJ32>S(c@_X!

Order is URDL, 1-based. So 1 is Ù,2isR` etc.

Inputs are: number of times, initial direction, char matrix (using ; as row separator).

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I'll add an explanation later in the day \$\endgroup\$
    – Luis Mendo
    Mar 28, 2017 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.