Week 2 #100DaysOfCode

Code Challenge!

Esther
2 min readJan 20, 2020

This week was much more difficult to maintain the requisite hour of code than last week and I wonder if it’s because I’m getting tutorial burnout. So one day I spend an hour on Code Wars to get back into the solving code challenges. I haven’t been practicing these types of coding problems in quite some time so I was really rusty, but I hope to make it part of my weekly coding ritual from now on.

The Problem

I decided to give myself 20 minutes to solve the problem and if I couldn’t figure it out, I would look up the solutions that other’s submitted. Here was the problem I worked on:

Convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

Examples

"din"      =>  "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("

After twenty minutes, here’s the solution I came up with (Ruby):

def duplicate_encode(word)   
count = {};
lower_case = word.downcase()
array = lower_case.split("")
array.each {|char| count[char] ? count[char]+=1 : count[char]=1}
symbol = array.map{|char| count[char] > 1 ? ")" : "("}
symbol.join("")
end

Yup, that’s a lot of lines, a lot of code, but it works! I was happy enough that the tests were passing, but realized that my code challenge skills were really rough. So after I submitted it, I looked at solutions that were highly rated. I know there are so many ways to solve one problem, but it’s not until I see someone else’s solution that that perspective really sinks in.

Here’s the highest rated solution:

def duplicate_encode(word) #Hello   
word #HEllO
.downcase #hello
.chars #[h, e, l, l, o]
.map {|char| word.downcase.chars.count(char) > 1 ? ")" : "("}
.join
end

I learned a new ruby method and chaining! I immediately went back to my code and attempted to refactor my code. Since I already solved the problem once, I was able to understand what the refactor was doing even if I never used the .chars method or did extensive chaining.

There are many resources to practice code challenges and it’s not always this enjoyable (especially for those challenges I can’t solve in the 20 minutes), but I always learn something new and walk away a better problem solver. Here’s to another week of learning!

--

--