Skip to content

Instantly share code, notes, and snippets.

@edelgado
Last active June 8, 2016 19:44
Show Gist options
  • Save edelgado/5dbfa4604dd1cc93f63d152e7a7db799 to your computer and use it in GitHub Desktop.
Save edelgado/5dbfa4604dd1cc93f63d152e7a7db799 to your computer and use it in GitHub Desktop.
Mini Code Challenges

Write a function to determine if a word is an anagram of another.

class String
  def anagram?(str)
    (self.chars - str.chars) == []
  end
end

"anna meme".anagram? "name name" # => true

Without the handy - operation between arrays:

class String
  def anagram?(str)
    return false if str.length != self.length
    other = str.chars
    self.each_char do |char|
      if position = other.index(char)
        other.delete_at position
      else
        return false
      end
    end
    other.empty?
  end
end
"anna meme".anagram? "name name" # => true
"nana mama".anagram? "nana nama" # => false
"anna meme".anagram? "bmmb ndnd" # => false
"anna".anagram? "ana"            # => false
"something".anagram? "somethings"# => false
"xy".anagram? "xz"# => false

Given an array of numbers 1 to n, stored in an array of length n-1, where all numbers are unique, write a function that to determine which number is missing.

def missing?(array)
  (1..(array.length + 1)).to_a - array
end

missing? [5,1,4,3] # => 2

Write a function that returns true if a word is a palindrome, or false if it’s not.

class String
  def palindrome?
    self.reverse == self
  end
end

"wow".palindrome? # => true

Given this map operation on an array:

out = [1, 2, 3].map do |n|
  n + 1
end

Q: What is the value of out? A: [2, 3, 4]

Now, pretend Array#map does not exist. Implement one for me:

class Array
  def meh_my_map
    i = 0
    values = []
    while i < self.length do
      values << yield(self[i])
      i += 1
    end
    values
  end
end
class Array
    def better_my_map
        self.each_with_object([]) do |elem, memo|
            memo << yield(elem)
        end
    end
end
puts [1, 2, 3].map { |n| n + 1}.to_s           # => [2,3,4]
puts [1, 2, 3].meh_my_map { |n| n + 1}.to_s    # => [2,3,4]
puts [1, 2, 3].better_my_map { |n| n + 1}.to_s # => [2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment