How I write my algorithms for CP
This is my approach to how I solved a 4kyu problem on codewars( my profile). This is a neat little problem that deals with permutation.
Disclaimer: I use Java and I will not share any codes! Write your own code! And whilst writing algorithms, I like to write in such a way that it is readable but still mix a bit of incorrect syntax here and there.
Initial approach
This is my 2nd 4kyu solve on hacker rank. Prior to this, I solved the NxN matrix discriminant problem. I started that with an algorithm going back to my intro into programming days. However, with this, I decided to code directly. The code passed all the initial tests but failed two of the final test prior to submission. Upon closer inspection, the code was incapable of handling permutation with no alphabet repeats, so I went back to the drawing board. Writing code may be flashy but writing code with a sound algorithm is one of the most satisfying things in the world. It’s like watching Tim Duncan play basketball.
Algorithm
Recursive programming to me is the epitome of CP. So, this algorithm is based on recursion.
1. Define a function singlePermutaion(String s)public static List<String> singlePermutaion(Sting s){
if(s.length == 1)
return new List.add(s);
return new List.add(findPermutation(s));
}2. findPermutation is the recursive functionpublic static List<String> findPermutation(String s){
int len = s.length();
init list res;
if(len == 2)
insert if both string different else insert just one
res.add(s); and or
res.add(palindrome of s);
// if len >=3
else
for(int i = 0; i< len; i++){
String str = bring the ith character to the 0th index and add the remaining;
tempList = findPermutation(str.substring(1));
for (String a: tempList)
insert if string not present in list res
res.add(str(0) + a);
}
return res;
}
That’s it. Once you are able to come up with an algorithm coding is the easy part. The implemented code passed all test.