I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.
Today I did: https://www.codewars.com/kata/calculate-string-rotation/javascript
Time: 20 minutes
What I’ve learnt: Back to string manipulation at codewars! So I got a lot of tests passing pretty quickly, but to knock out the ones that should be returning -1
took me a few attempts at adding things to my conditional.
Here was my solution:
1 2 3 4 5 |
function shiftedDiff(first,second){ var firstLetterPosition = second.indexOf(first[0]) if (firstLetterPosition === -1 || (first[1] !== second[firstLetterPosition +1] && firstLetterPosition !== first.length-1 ) || (first[first.length - 1] !== second[firstLetterPosition -1] && first !== second && first[1] !== second[0])) return -1 return firstLetterPosition } |
What I learned from other people’s code:
I should have spent 5 more minutes thinking about what the failing condition was, instead of continuously adding conditionals to get my codewars passing. Seriously all I needed is if first.length != second.length
… duh!
The way they did this was seriously interesting (thanks Daniel for explaining by the way!). They added up the two strings (of the second), for example in this test where “coffee” was shifted over 2:
shiftedDiff(“coffee”, “eecoff”) => 2
So second + second would be “eecoffeecoff” and checked at what index does the first (“coffee”) show up, and return that number. Amazing thinking!!
I did this similarly but just by looking for the first letter, had I looked for the whole word if it didn’t exist it would know right there.
Looking forward to tomorrow! Hopefully will do this kata before midnight 😉