Skip to content

Instantly share code, notes, and snippets.

View jubishop's full-sized avatar
🎼
Making a podcast app.

Justin Bishop jubishop

🎼
Making a podcast app.
View GitHub Profile
def min_distance(from_word, to_word)
return 0 if from_word == to_word
count = 0
words = [from_word]
loop {
new_words = Array.new
words.uniq.each { |word|
index = 0
rindex = -1
index += 1 until (word[index] != to_word[index])
def match(board, char, row, col)
return false if row < 0 or row >= board.length
return false if col < 0 or col >= board.first.length
return board[row][col] == char
end
def _exist(board, word, row, col)
return true if word.empty?
[[row-1, col], [row+1, col], [row, col-1], [row, col+1]].each { |cur_row, cur_col|
if (match(board, word[0], cur_row, cur_col))
# Usage:
# (min..max) { |x| x <=> target } => Integer or nil
class Range
def binary_search
left, right = min, max
while (left <= right)
middle = left + ((right - left) / 2)
result = yield middle
if (result == 0)
class String
include Enumerable
def each
each_char { |char| yield char }
end
end
def compress_string(string)
string.chunk{|x|x}.map { |char, ary| ary.length > 1 ? "#{char}#{ary.length}" : char }.join('')
class String
include Enumerable
def each
each_char { |char| yield char }
end
end
def split_parts(string)
parts = Array.new
def num_search(string, ans)
if (string.empty?)
ans[:count] += 1
return
end
return if string[0] == "0"
num_search(string[1..-1], ans)
if (string.length > 1 and (string[0].to_i < 2 or (string[0].to_i == 2 and string[1].to_i < 7)))
num_search(string[2..-1], ans)
end
# @param {Integer} n
# @return {TreeNode[]}
def generate_trees(n, vals = (1..n).to_a)
return [] if vals.empty?
return [TreeNode.new(vals.first)] if (vals.length == 1)
nodes = Array.new
all_rights = generate_trees(n, vals[1...vals.length])
all_rights.each { |right|
node = TreeNode.new(vals.first)
def _is_interleave(s1, s2, s3)
return s2 == s3 if (s1.empty?)
return s1 == s3 if (s2.empty?)
return false if ($dp1[s1] == s3)
if (s1[0] == s3[0])
return true if _is_interleave(s1[1..-1], s2, s3[1..-1])
end
if (s2[0] == s3[0])
return true if _is_interleave(s1, s2[1..-1], s3[1..-1])
end
require_relative 'jubilib/binary_tree'
def validate_and_return_minmax(node)
left_valid, left_min, left_max = node.left.nil? ?
[true, node.val, node.val] :
validate_and_return_minmax(node.left)
return [false, 0, 0] unless left_valid
right_valid, right_min, right_max = node.right.nil? ?
[true, node.val, node.val] :
validate_and_return_minmax(node.right)
require_relative 'jubilib/binary_tree'
def is_valid_bst(node, min = -Float::INFINITY, max = Float::INFINITY)
return true if node.nil?
return false unless node.val > min and node.val < max
return (is_valid_bst(node.left, min, [max, node.val].min) and
is_valid_bst(node.right, [min, node.val].max, max))
end