Skip to content

Instantly share code, notes, and snippets.

@wmwong
wmwong / quicksort.rb
Created September 30, 2013 02:00
Sorting quickly
module QuickSort
def sort(array, options = {})
start_index = options[:start_index] || 0
end_index = options[:end_index] || array.length - 1
unless start_index >= end_index
# Randomly choose a pivot and swap with the end index.
pivot_index = rand(end_index - start_index + 1) + start_index
temp = array[end_index]
array[end_index] = array[pivot_index]
array[pivot_index] = temp
@wmwong
wmwong / heap.rb
Created September 28, 2013 21:55
Fun with heaps
module Heap
def parent_index(i)
# +1 because the math works with indices starting from 1.
# -1 because we need to convert back to 0-index.
(i + 1) / 2 - 1
end
def left_child_index(i)
# +1 because the math works with indices starting from 1.
# -1 because we need to convert back to 0-index.
class Anagram
attr_reader :letters
def initialize(word)
@word = word
# letters is a count of each letter in the word.
@letters = {}
@word.each_char do |l|
@letters[l] ||= 0
@letters[l] += 1
require "digest/md5"
class SpellChecker
# num_bits is how many bits the hash function should produce.
def initialize(dictionary_name, num_bits)
@num_bits = num_bits
@bitmap = []
load_dictionary(dictionary_name)
end
module DataMunger
# This method uses the given regex to parse the data in the given filename
# to determine the minimum spread.
# The first match of the regex is the data to return.
# The second and third match is used to find the spread.
def min_spread(filename, regex)
result = nil
min_spread = nil
# Go through each line and parse the data.
# Iterative by number of iterations.
def chop(target, array)
found = false
start_index = 0
end_index = array.size - 1
check_index = 0
# Find the max iterations to perform.
# log2(0) is infinity so we have a special case for it.
# After log2(), we +1 because we still need to check the last value. floor()