The good news: next permutation is not a clever trick. It is a very literal translation of what "next" means in lexicographic order. Once you see the suffix logic, you can derive the whole algorithm ...