Code Katas in Swift (#2 Gravity Cubes)

Liyicky
2 min readAug 2, 2022

--

Gravity Cubes

This Kata is a fun and easy one. See the boxes above? Imagine them falling to the left or right when you tilt them. Just like the image above, if you tilt the boxes to the left they should all fall in that direction.

Represent the columns as an array: [3,2,1,2]

3 boxes stacked on top of each other in the first column, then 2 and so on. Write an algorithm that moves the boxes neatly to the left or right.

Solution

Genius

I started by thinking of the problem as physical cubes. But after seeing it all on paper I saw that is was just a problem of sorting an array from least to greatest and vice versa.

That’s when I heard Barack Obama’s beautiful voice in my head.

Not this time Obama!

This time however, Bubble Sort was exactly what was needed to solve this problem. The simplest solution would be to use swift’s built in sorted() method.

return [3,2,1,2].sorted(by: direction == "L" ? (>) : (<))

Since I’ve never written a bubble sort algo I decided to try on my own. I had a hard time figuring it out on paper. I had an easier time figuring it out in my head during a quick walk. Try that out if you get stuck.

Final solution

You can try it out yourself here if you’d like.

I’m broke and jobless teaching myself to be an iOS dev from scratch. If you’re in a similar situation subscribe or follow me on twitter. We can learn together and get this goal. Thank you for reading.

--

--

Liyicky

Hey, I’m Jason Cheladyn. Going back to the coding world after 6 years of teaching English in Japan. https://www.twitter.com/liyicky https://www.liyicky.com