Skip to content

Instantly share code, notes, and snippets.

@jeffnv
jeffnv / merge_sort.rb
Created September 20, 2013 05:28
merge sort
def merge_sort_rec(array)
return array if array.length == 1
array_left = array[0..(array.length/2 - 1)]
array_right = array[(array.length/2)..-1]
sorted_array_left = merge_sort_rec(array_left)
sorted_array_right = merge_sort_rec(array_right)
trim_illegal_moves!(new_spaces)
trim_already_visited!(new_spaces)
new_spaces.each do |location_pair|
leaf_node.add_node(TreeNode.new(location_pair))
end
new_spaces.each do |location_pair|
add_new_moves_to_tree(location_pair)
end
def find_path(target_pos)
path = [target_pos]
target_node = @move_tree.bfs(target_pos)
return [target_node.value] if target_node.parent.nil?
find_path(target_node.parent.value) + path
end
some_array.each_with_index do |item, index|
other_array[index] = ##somethign something
end
some_string.split('').each do |char|
do_something_special(char)
end
some_array.each_index do |index|
other_array[index] = ##somethign something
end
some_string.chars do |char|
do_something_special(char)
end
def in_check?(color)
all_opponent_pieces = @board.flatten.compact.select { |piece| piece.color != color }
all_opponent_pieces.each do |opponent_piece|
opponent_piece.valid_moves(self).each do |opponent_valid_move|
return true if piece_at(opponent_valid_move).is_a?(King)
end
end
false
end
def do_for_every_square(&prc)
@board.each_with_index do |row, row_index|
row.each_with_index do |square, col_index|
prc.call(row_index, col_index, square)
end
end
end
SELECT a.company, a.num, a.stop, b.stop
FROM route a JOIN route b ON
(a.company=b.company AND a.num=b.num)
WHERE a.stop=53
def avg_karma
results = QuestionsDatabase.instance.execute(<<-SQL, @id, @id)
SELECT (COUNT(questions.id) *1.0/ (SELECT COUNT(*) FROM questions WHERE user_id = ?))
FROM questions JOIN question_likes ON (question_likes.question_id = questions.id)
WHERE questions.user_id = ?
SQL
results[0].values[0]
end
def results
responses = Question.joins(<<-SQL)
LEFT OUTER JOIN answer_choices
ON answer_choices.question_id = questions.id
LEFT OUTER JOIN responses
ON answer_choices.id = responses.answer_choice_id
SQL
responses = responses.where("questions.id = ?", self.id)
p responses
responses.group('answer_choices.answer_body').count('responses.id')