Skip to content

Instantly share code, notes, and snippets.

@mayfer
mayfer / pairs.rb
Created October 22, 2014 19:03
Find pairs of numbers that add up to the sum (three different methods)
# runtime O(N^2)
# memory O(1)
def find_pair(numbers, sum)
numbers.each_with_index do |n, i|
numbers.each_with_index do |m, j|
if n + m == sum
return [n, m]
end
end
@mayfer
mayfer / anagrams.rb
Created October 22, 2014 19:03
Find the word with most anagrams
# pat, tap, apt
def find_longest_anagram()
words = File.open('/usr/share/dict/words').read
anagrams = Hash.new { [] }
most_so_far = 0
most_signature = nil
@mayfer
mayfer / edit_distance.rb
Last active August 29, 2015 14:07
edit distance solutions
# An edit distance (e.d.) is defined as how many times you need to replace, add, or remove characters to match two strings.
# E.G. "train" and "brain" have e.d.=1
# "train" and "rain" have e.d.=1
# "train" and "trains" have e.d.=1
# Write a method that returns TRUE if edit distance is exactly 1, FALSE if not.
def edit_distance_is_one(word1, word2)
i1 = 0
i2 = 0
@mayfer
mayfer / orm.rb
Created October 15, 2014 17:23
Simple ORM livecoding
class ORM
def save
if defined? @id
sql_update
else
sql_insert
end
end
@mayfer
mayfer / ajax.rb
Created October 8, 2014 20:37
Ajax examples
require 'sinatra'
require 'nokogiri'
require 'open-uri'
require 'sinatra/json'
require 'json'
# sets the view directory correctly (to make it work with gists)
set :views, Proc.new { File.dirname(__FILE__) }
@mayfer
mayfer / activerecord.rb
Created September 17, 2014 17:43
ActiveRecord example
require 'active_record'
require 'pg'
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(
:adapter => "postgresql",
:host => 'ec2-54-204-41-178.compute-1.amazonaws.com',
:username => 'bmdjwluxchptuq',
:password => 'aEH-cKdr2zoXYUAjI8Xjma5eXK',
@mayfer
mayfer / orm.rb
Created September 17, 2014 17:40
ORM example
class ORM
def save
table_name = self.class
instance_variable_names = self.instance_variables.map do |i|
i.slice(1, i.length)
end
instance_variable_values = self.instance_variables.map do |i|
self.instance_variable_get("#{i}")
@mayfer
mayfer / ajax.rb
Created September 10, 2014 18:37
jQuery/AJAX/JSON/sinatra example
require 'sinatra'
require 'nokogiri'
require 'open-uri'
require 'sinatra/json'
# require 'json'
# sets the view directory correctly (to make it work with gists)
set :views, Proc.new { File.dirname(__FILE__) }
@mayfer
mayfer / math.rb
Created September 7, 2014 00:53
veronika's math game
#future update: count time, after 1 min, swith the user - 1 life
# Assignment created as a new Github repository
# require pry
# binbinding.pry
@players = [{
life: 3,
score: 0,
level: 1,
name: "Player 1"
@mayfer
mayfer / form_example.rb
Created August 22, 2014 17:16
A simple example demonstrating sending POST data from an HTML form
require 'sinatra'
get '/' do
<<-eos
<html>
<head>
<title>coffee orbit</title>
</head>
<body>