dnestoff
9/13/2016 - 4:03 PM

Algorithms: Basic

Basic algorithms include:

  • Anagrams

class Word < ActiveRecord::Base

  def anagrams
    all_words = Word.all
    word_to_check = self.word_text.chars.sort
    all_words.select do |word|
      if word.word_text != self.word_text
        word.word_text.chars.sort == word_to_check
      end
    end
  end

end
require_relative 'balanced_parens'

describe "Balanced Parens" do

  let(:parens_map1) do 
    { "(" => ")", "[" => "]", "{" => "}" } 
  end
  let(:parens_map2) do 
    { "(" => ")", "{" => "}" } 
  end

  it "can factor in different sets of parens" do
    string = "{aabe}(airl:irlgi)[andrege (algi)]"
    results_array = [ balanced_parens(string, parens_map1), balanced_parens(string, parens_map2)]
    expect(results_array).to eq([true, true])
  end

  it 'is balanced' do
    string = "{([(alpha king)]* 4)}"
    expect(balanced_parens(string, parens_map1)).to eq true
  end

  it 'is balanced with a string over 20 characters' do
    string = "[ ( do { end } ) {} and (everything) before [(*)+(9)]]"
    expect(balanced_parens(string, parens_map1)).to eq true
  end

  it 'is not balanced' do
    string = "{{([(alpha king)]* 4)}"
    expect(balanced_parens(string, parens_map1)).to eq false
  end

  it 'is not balanced if a parens is not properly closed' do
    string = "[(])"
    expect(balanced_parens(string, parens_map1)).to eq false
  end


end

def balanced_parens(string, parens_map)
  opening_parens = []
  i = 0
  while i < string.length
    if parens_map.keys.include? string[i]
      opening_parens << string[i]
    elsif parens_map.values.include? string[i]  
      popped_paren = opening_parens.pop
      return false if string[i] != parens_map[popped_paren]
    end
    i += 1
  end
  opening_parens.empty?
end