Apply Permutation
Problem Statement
Write a program that takes a permutation array and a input array and reorder the input array as per the given permutation.
Problem Solving
- I can see that this seems to be a linear time problem.
- We need to apply permutation inc cycle.
- Start at 0 replace current position at 0 with previous input, swap previous input at current position. continue till end.
- However there are multiple missing things in this solution.
- As there can be multiple cycle in the same array. Therefore we need mechanism to break from cycle and then run on the next cycle.
- To break the cycle we need to keep an bool index whether the position is processed or not.
- and to go to next cycle we can always scan the processed array for non processed items and then start the process there.
- This seems okay.
- Find code here.
Learning
- This question might seem simple but to implement it correctly is difficult.
- Since I coded through the problem solving my code also looked tangled and complex.
- After multiple debugging sessions and fixing problems. The code looked in a very bad shape.
- However it passed all test cases.
- Then I looked at the answer to find it to my surprise, that the code written is so much more elegant than what I had written.
- However there is space optimization in the book's answer but ignoring that also the code was much more simple.
- Later I refactored my code into that shape. Felt both good and bad.
- Writing good code is really really difficult. I understand it now. Everyone can code but to make proper sentences in the language is the art. To write pieces that are elegant and clear and concise.
- Now that I have refactored it. It look good.
- Also one key insight is that whenever you feel like using an iterator that runs through all the elements in linear fashion use a for loop. and when needed to skip use continue or empty loop cycle. No need to write make complex iterator advances.
- Small question lots of learning.
No comments:
Post a Comment