Search code examples
.netarraysvb.net2048

sliding array values


I'm trying to recreate the game 2048 in vb and I'm struggling with figuring out how to get the values in an array to slide together.

I'm trying to do this in a single dimensional array before I task myself with the full thing

for example if I have an array of

[0,2,0,4]

I need to figure out how I can step through each number, check if there is a 0 behind it so that the array would become

[2,4,0,0]

but I'm struggling with figuring out how to check all the values behind a number in the array

I'm only trying the slide left function at the moment just so I can take things slowly, does anyone have any idea how I can achieve this?


Solution

  • You can do this with LINQ:

    Dim a = {0, 2, 0, 4}
    a = a.Where(Function(x) x <> 0).Concat(a.Where(Function(x) x = 0)).ToArray()
    
    Console.WriteLine(String.Join(",", a)) ' outputs 2,4,0,0
    

    The first Where gets all the non-zero elements. The Concat concatenates the result of that with (all the zero elements), thus maintaining the length of the data, and the .ToArray() converts the result back to an array.