Illustration for “The First time Rust really impressed me” (1 of 2)

c style

Illustration for “The First time Rust really impressed me” (2 of 2)

Rust style

You know how this chain goes. I want to understand how to write multi-agent controllers for games like troll_farm. Python is too slow, so I chose Rust. I don't know Rust, so I'm learning it by solving leetcode. For the first time, I bumped into something which made me go: WOW.

I'm not impressed by Rust's memory management. Instead of paying attention to pairs of new/delete or malloc/free calls, you have to learn tons of "borrowing" rules and fight the compiler every step of the way. It turned linked-list problems into a hellish nightmare. I hope that it was a useful nightmare, but who knows.

And finally I found IT. Leetcode 31. "Next permutation". I have known the problem and the algorithm since I bought A. Shen's book in 1998. Nice juggling with indices. Or with pointers, if you want. You have to carefully:

  • find the rightmost number smaller than its right neighbor. It's a pivot element. No => end of algorithm
  • swap the pivot with the rightmost greater than it
  • reverse the suffix to the right of pivot element

It is exactly what is written on the top picture. But check the bottom one. It's beautiful. You split your sequence into windows of length two, select one which satisfies the predicate. Then - rightmost greater then pivot. Then - swap and reverse. Your algorithm is written in almost like plain English. I don't know yet whether it gives any advantage in programming in general. Nevertheless, in this case, it is beautiful.