Skip to content

Instantly share code, notes, and snippets.

@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 / 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 / find_index.rb
Created October 22, 2014 19:05
Find index of number (two different methods)
# N is number of elements
# N
# O(N)
def find_index(number, numbers)
numbers.each_with_index do |n, i|
if n == number
return i
@mayfer
mayfer / ajax.rb
Created November 5, 2014 19:35
AJAX examples with Sinatra
require 'sinatra'
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 / book_orm.rb
Last active August 29, 2015 14:09
simple ORM example for a Book class
# This example demonstrates how to generate SQL statements
# to fetch and save objects to a database.
# Warning: It does not do the actual database calls. just returns the statements.
class Book
attr_accessor :id, :title, :author_id, :subject_id
def initialize(id, title, author_id, subject_id)
@id = id
@mayfer
mayfer / index.erb
Created November 14, 2014 19:57
Basic HTTP get/post example setup with sinatra
<!doctype html>
<html>
<head>
<title>hmmm</title>
<style>
html, body { background: #377; font-family: monospace; color: #fff; }
</style>
</head>
<body>
@mayfer
mayfer / intro_js.md
Last active August 29, 2015 14:10
Introduction to JS

Global vs. local variables

  • Local variables are defined with the var keyword.
  • Variables defined without var are automatically global.

Function declaration and calling

  • Two ways to define functions:
    • function someFunc(arg1, arg2) {}
    • var someFunc = function(arg1, arg2) {}
  • All arguments are inherently optional. Calling someFunc() without arguments will NOT error out. The arguments will have undefined values.
@mayfer
mayfer / 0.js
Created December 8, 2014 20:05
node examples, step by step.
// run this with "node 0.js"
console.log("Hello World");
@mayfer
mayfer / find_number.rb
Created December 11, 2014 19:12
Algorithms and Data structures
# complexity O(log N)
def find_number(numbers, find_number)
middle = numbers.size / 2
first = 0
last = numbers.size - 1
loop do
@mayfer
mayfer / ws.html
Created December 16, 2014 19:02
Node, Websockets (socket.io), Prototypical inheritance
<!doctype>
<html>
<head>
<title>hi</title>
<style>
body, html {
background: #aaa;
font-family: monospace;