Skip to content

Instantly share code, notes, and snippets.

View jhamon's full-sized avatar

Jennifer Hamon jhamon

View GitHub Profile
require 'sqlite3'
require 'singleton'
class QuestionsDatabase < SQLite3::Database
include Singleton
def initialize
super "aafollowers.db" # Our test db
self.results_as_hash = true
self.type_translation = true
key_array = [1,2,3] # => [1, 2, 3]
value_array = [4,5,6] # => [4, 5, 6]
silly_hash = { key_array => value_array } # => {[1, 2, 3]=>[4, 5, 6]}
key_array.pop # => 3
# After mutating the key the hash is broken
silly_hash # => {[1, 2]=>[4, 5, 6]}
silly_hash[key_array] # => nil
silly_hash[[1,2]] # => nil
@jhamon
jhamon / king.rb
Last active December 23, 2015 21:19
# coding: utf-8
require 'colorize'
class King < Piece
include SteppingPieces
def move_dirs
[[0, -1], [0, 1], [1, 0], [-1, 0], [-1, -1], [-1, 1], [1, -1], [1, 1]]
end
class King < Piece
include SteppingPieces
def move_dirs
[[0, -1], [0, 1], [1, 0], [-1, 0], [-1, -1], [-1, 1], [1, -1], [1, 1]]
end
def mark
return "♚".colorize(@color)
end
@jhamon
jhamon / stepping.rb
Last active December 23, 2015 21:19
module SteppingPieces
# Movement for stepping pieces, e.g. King, Knight
def moves(board)
# returns array of valid move positions for self (a Piece instance)
# Add movement vectors to current position
moves = self.move_dirs.map { |vec| new_position(@pos, vec)}
# We only allow moves that fall on the board.
@jhamon
jhamon / piece.rb
Last active December 23, 2015 21:19
class Piece
attr_reader :color
attr_accessor :pos
def initialize(color, pos)
@color = color # :white or :black
@pos = pos # position = [x, y]
end
def dup
class TreeNode
# ...
def dfs(target_value = nil, &blk)
# Depth-first search. Returns TreeNode instance
# with target value, or nil if not in tree.
# Optionally accepts a block and returns the
# first node encounted for which the block
# evaluates to true. This allows us to dfs
# search using arbitrary criteria.
class TreeNode
# ...
def dfs(target_value = nil, &blk)
# Depth-first search. Returns TreeNode instance
# with target value, or nil if not in tree.
# Optionally accepts a block and returns the
# first node encounted for which the block
# evaluates to true. This is useful when
# searching for nodes using attributes other
@jhamon
jhamon / broken_dfs.rb
Created September 21, 2013 07:14
This doesn't work because the block can't be passed recursively.
class TreeNode
# ... omitted.
def dfs(target_value = nil, &blk)
# A (broken) first attempt at depth-first search
# with arbitrary search criteria defined by the
# block received.
return self if !blk.nil && blk.call(@value)
return self if @value == target_value
@jhamon
jhamon / treenode.rb
Last active December 23, 2015 14:19
A simple implementation of nodes in a tree. Each tree can have arbitrarily many child nodes.
class TreeNode
attr_accessor :parent, :children
attr_reader :value
def initialize(value)
@value = value
@parent = nil
@children = []
end