Random Code Prompts and Traumatic Brain Injury
Tags: ruby, tbi, programming, code
Published: 2021-10-11 02:48:30

## TLDR; 
I used ruby and pointless programming challenges from all over the internet to work on recovering from a Traumatic Brain Injury. 

## What Happened? 
On the _9/15/2021_ I was in a major car accident that my daughter and I will struggle with for the rest of our lives, but I don't want to go into many details about that accident.  While this post has tangential information I'm going to try to focus on keeping it in the technical realm.  That being said I do need to talk about a few injuries.  My injuries are quite severe and I'm currently recovering in a nursing home probably for the next couple months. Over simplifying, I have 2 broken legs, a broken shoulder, and a mild traumatic brain injury.    

The good thing is I will get over my brain injury, but I have to rehab it just like I would any other limb or muscle. I am over simplifying a lot here, but brain injuries are no joke they can cause you to have a variety of symptoms that could take weeks, months, or years to fix.  For me mental slowness in my cognitive reaction times, dizzy spells, short term memory loss, and frustration at my slowed cognitive reaction times are the symptoms I'm working to rehabilitate.

## What Am I doing?  
I am not a complacent person, I do not take the easy way out of things and I often like to think ahead.  As a software engineer I need to get my problem solving skills back up to snuff.  I began doing what I find comfortable and distractive enough from other pains, solving stupid code problems. Writing solutions to stupid code problems makes me happy, puts my brain to use, and gives me an escape from the physical and emotional traumas that I'm not ready to face yet.  

## Code Problems
_These problems are small simplistic things on the internet that most likely have no real world implications.  Most of them I will treat that way and not refactor, the solution you see is many times to first solution I'm writing._

### Day 1 (Fake Binary String Problem) 

This problem was taken from a prompt sent out by [codewars](https://www.codewars.com/).  The goal was to take any numerical string and turn it into a fake binary string by converting numbers to 1's and 0's.  If the number is a 5 or less it is a 0, otherwise it is a 1. 

Let me say that this is no where near any real binary strings and I think we could go further with it to fake it better and make a converter and parser, but I stuck to the original params.  

```ruby
def fake_binary(str) 
  arry = str.split('')
  new_arry = []
  arry.each do |int| 
    if int.to_i <= 5
      new_arry.push 0
    else 
      new_arry.push 1
    end 
  end 
  new_arry.join
end 

bin = fake_binary '113843948' 
puts bin # '000100101' 
puts "Solution Correct" if bin == "000100101" 
```
**Post Mortem:** This was a good day 1 project for me, at the time my cognition was much lower and I was still able to put together a quick solution that worked.  At the end of this I had maybe an hour or half hour into it including the time it took to setup a dev environment on the computer I was using.  By the end I was getting dizzy, blurred vision, and my right shoulder (broken) was hurting, but I had a viable solution that worked without any major changes and I had some fun.

### Day 2 (Longest Word) 
This problem was taken from a prompt on [eadabit](https://edabit.com/challenge/mywAnTMFyvNvD78qT).  

The goal is to write a function that finds the longest word in a sentence. If two or more words are found, return the first longest word. I found this task too easy, and know that if it was a realistic task would be to return all the longest words. 

```ruby
sentences = [
    "When we are children we seldom think of the future; This innocence leaves us free to enjoy ourselves as few adults can.",
    "Finding a needle in a haystack isn't hard when every straw is computerized.",
    "I decline the title of Iron Cook and accept the lesser title of Zinc Saucier, which I just made up."
]

def longest_word_singular(sentence)
    words = sentence.scan(/[\w']+/)
    words.max_by(&:length)
end 

def longest_word_multiple(sentence)
    words = sentence.scan(/[\w']+/).sort_by!(&:length).reverse!
    max = words.map(&:length).max
    words.select { |word| word if word.length == max}.join(', ')
end 

puts longest_word_multiple(sentences[0]) # innocence, ourselves
puts longest_word_multiple(sentences[1]) # computerized
puts longest_word_multiple(sentences[2]) # decline, Saucier

puts longest_word_singular(sentences[0]) # innocence
puts longest_word_singular(sentences[1]) # computerized
puts longest_word_singular(sentences[2]) # decline
```

**Post Mortem:** I felt a little stronger mentally when dealing with this problem.  I even felt strong enough to look at the at a top level and add to the criteria to push myself a little bit. I don't see any obvious refactors with either function and they seem like viable solutions.  

### Day 3 (COVID Hand Washing Prompt)
I'm not sure where I pulled this one from, but the prompt is as follows.  The goal write a program that calculates time spent washing hands during the global pandemic.  It takes 21 seconds to wash your hands and help prevent the spread of COVID-19.  In one function calculate the number of times a person washes their hands in a day and number of days they follow this routine.  Use this function to calculate duration in minutes and seconds.

```ruby
WASH_TIME = 21

def hand_washing_time(days, washes_per_day)
  seconds = days * (washes_per_day * WASH_TIME)
  minutes_seconds(seconds)
end 

# humanizes the time to something good looking
# i like this result, but when I thought about it I 
# was not keeping with the scope
def humanize_time(seconds)
  Time.at(seconds).utc.strftime("%H:%M:%S")
end 

# this is not something I would really want to do
# however this is the scope of the challenge.
def minutes_seconds(seconds)
  mins = seconds / 60
  remainder = seconds % 60
  "#{mins} Mins #{remainder} Seconds spent washing your hands."
end 

puts hand_washing_time(4, 8) # 11 Mins 12 Seconds spent washing your hands.
``` 
**Post Mortem:** This problem was pretty easy, but I have to be honest with myself I kept veering off the path to complete the goals as defined.  I had trouble keeping my mind focused on the task instead of being off coding in tangential sub-tasks.  

### Day 4 (Matching case but changing string)
This prompt I do not remember where it came from, but the goal was to take a given string and match the input style while changing the output to a different string.  So if the string coming in is lowercase the string coming out would be lower case.  The same would be true for upper or alternating case styles.  

```ruby
def change_string(str, new_str = "holler") 
  new_str.upcase! if uppercase?(str)
  new_str.downcase! if lowercase?(str)
  new_str = alternating_case(new_str, 0) if alternating_even?(str)
  new_str = alternating_case(new_str, 1) if alternating_odd?(str)
  new_str
end 

def uppercase?(str)
  str == str.upcase
end 
 
def lowercase?(str)
  str == str.downcase
end 

def alternating_even?(str)
  str == alternating_case(str, 0)
end 

def alternating_odd?(str)
  str == alternating_case(str, 1)
end 

def alternating_case(str, offset = 1)
  if offset == 1 
    str.gsub(/[A-Za-z]/).with_index{|letter, i| i.odd? ? letter.upcase : letter.downcase}
  else 
    str.gsub(/[A-Za-z]/).with_index{|letter, i| i.even? ? letter.upcase : letter.downcase}
  end 
end 

sample = "somestring"
sample2 = "SoMe ReAlLy CoOl StRiNg ThAt DoEs SoMeThInG"
sample3 = "FUNKY MAGIC MAN"

puts change_string(sample) # holler
puts change_string(sample2) # hOlLeR
puts change_string(sample3) # holler
``` 
**Post Mortem:** A little bit stronger of a problem and more fun of a task, but still pretty easy and pretty pointless.  However the goal is to slowly get my brain working and wrapping around programming tasks so that I can rehabilitate myself.  I will say each day has been a little more progressive and this day was much faster than the days before.  My typing is better, my memory and focus is a little better.  So I would say not only is this a viable solution it shows that I'm getting a little more normal.   

### DAY 5 and 6 (Developer Productivity Tasks)
I didn't give up on these days, but I was having some pain and there was some definite concentration loss.  I am using a laptop of mine that was setup for different uses, but now that I'm the main user I figure it is okay to setup a development environment.  That being said we had some work todo. 

1. Install Homebrew
2. Use Brewfile to install dependencies
3. Check dependencies are working properly
4. Install and setup rbenv
  * This includes installing the version of ruby and some gems such as rubocop, rails, and other ones that I use often. 
5. Get text editor up to snuff
  * Installing plugins
  * Modifying Settings
  * Automatic corrections
  * Snippets
  * Code Smells Detection
  * Rubocop

### Day 6: (Palindromic Primes)
This problem came from hacker rank I believe, but I'm not 100% on that because I had it written down on day 5.  The problem was to define a function that used `.lazy` method and returned only numbers that were both prime numbers and palindromes. I took this time to make something that felt more like usable ruby.  Even though the problem ended up being super pointless from a code standpoint and would probably never be seen in a "production code base". 

```ruby
class PalindromicPrimes
  def initialize(size)
    @size = size
  end

  def palindrome_primes(size)
    1.upto(Float::INFINITY).lazy
     .map { |num| num if prime?(num) && palindrome?(num) }
     .select { |x| x.is_a? Integer}.first(size)
  end

  def prime?(num)
    (2..(num - 1)).each do |multiple|
      return false if (num % multiple).zero?
    end
    true
  end

  def palindrome?(str)
    str.to_s == str.to_s.reverse
  end
end

p = PalindromicPrimes.new(5)
puts p.palindrome_primes(7).inspect # [1, 2, 3, 5, 7, 11, 101]
puts p.palindrome_primes(18).inspect # [1, 2, 3, 5, 7, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787]
```
**Post Mortem:** Primes are a bitch to figure out, possibly because the years I've been away from math.  To be honest I googled to figure out how to deal with the primes, but I tried to figure it out only from the Math point of view.  That being said one of the resources I looked at was a JavaScript solution for doing the same thing. I was really disappointed in the fact that I couldn't `map` without getting `nils` in the array and struggled to find another solution. That is why I had to add the `select` so that we weren't getting all the `nils` in the final `array`.  Overall a much tougher project, but I feel more confident that I did day 1 and I felt like my brain activity was much better.  

## Closing Thoughts
I don't know if I'm the first person to try to battle  the effects of a Traumatic Brain Injury with programming skills, but I think there is some validity to doing it for those who had the skills prior to having the accident or injury.  I feel like it has given me some confidence in my skills and is working my brain for my eventual return to work. 

I'm going to keep working on some problems, maybe even try to do some work on some open source repositories.  I may even try to do some more writing  to really work my brain and snap myself out of this fog.  

I think time will be the best way to heal myself, but at least this makes time go by much faster.  Thanks for reading.