Skip to content

Instantly share code, notes, and snippets.

@jstanley0
Created February 22, 2014 21:39
Show Gist options
  • Save jstanley0/9162793 to your computer and use it in GitHub Desktop.
Save jstanley0/9162793 to your computer and use it in GitHub Desktop.
Naive but effective searcher for a short series of numbers comprised of alphanumeric characters that sum to a specific value, and intermediate values satisfy a bitwise constraint
require 'Set'
def search_helper(nums, partial_sum, list, target, length, constraint)
if list.length >= length - 1
last = target - partial_sum
if nums.include?(last)
list << last
return list
end
else
nums.each do |num|
n = (partial_sum + num) & 0xffff
if n & constraint == 0
res = search_helper(nums, n, list + [num], target, length, constraint)
return res unless res.nil?
end
end
end
return nil
end
# search for a series of alphanumeric numbers that add
# from start to target, where each intermediate sum & constraint == 0
def lagos_search(start, target, length = 3, constraint = 0)
# build a list of all possible 16-bit alphanumeric numbers
nums = Set.new
bytes = ['0'..'9', 'A'..'Z', 'a'..'z'].map(&:to_a).flatten.map(&:ord)
bytes.each_index do |i|
bytes.each_index do |j|
nums << (bytes[i] << 8 | bytes[j])
end
end
return search_helper(nums, start, [], target, length, constraint)
end
if ARGV.length < 2
puts "Usage: lagos-search starting_value target_value [length] [constraint]"
exit(1)
end
res = lagos_search(Integer(ARGV[0]), Integer(ARGV[1]), Integer(ARGV[2] || 3) , Integer(ARGV[3] || 0))
if res
puts res.map{|n| "%04x" % n}.join(',')
else
puts "No solution found"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment