Saturday, August 08, 2015

2048 game's slide

Get the first two +ve numbers as i1, i2 and keep a target index. If values at i1 and i2 are same, then 2x and loop again from i2-1. Else copy i1 and loop again from i2.
//example

    i2 i1
 -  2  2  -
          target

slide direction -->

i: 0123
a: ..22 = ...4
a: 2.2. = ...4
a: 221. = ..41
a: 2222 = ..44
a: 2.4. = ..24
//time O(n), space O(1)
slide(a):
    i1 = i2 = target = a.length()-1
    while true:
        while i1 >= 0 && a[i1] == 0:
            i1--
        if i1 < 0:
            break
        i2 = i1 -1
        while i2 >= 0 && a[i2] == 0:
            i2--
        t = a[i1]
        if i2 >= 0 && a[i1] == a[i2]: //i1 is >= 0 
            a[i1] = a[i2] = 0
            a[target--] = t << 1
            i1 = i2 -1
        else:
            a[i1] = 0
            a[target--] = t
            i1 = i2

No comments:

Post a Comment