Skip to content

Instantly share code, notes, and snippets.

@nat-n
Created October 20, 2012 12:50
Show Gist options
  • Save nat-n/3923189 to your computer and use it in GitHub Desktop.
Save nat-n/3923189 to your computer and use it in GitHub Desktop.
Command line executable which searches for the first occurence of a given string in PI, in the form of an ascii base10 string.
#!/usr/bin/env ruby
# encoding: utf-8
#
# Created by Nat Noordanus on 2012-10-20.
#
# requires a text file of digits of pi http://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt
def find_in_pi string, pi_file_path
# convert string to base 10 ascii
bin_string = string.each_char.map{|c| c.ord.to_s(2) }.join
b10_string = Integer("0b#{bin_string}").to_s
puts "Searching for #{b10_string} in pi..."
# stream pi and scan for target
pi_file = File.open(pi_file_path,'r')
match_length = 0
i = -2 # start counting from zero at the firs decimal characters
pi_file.each_char do |c|
i += 1
if c == b10_string[match_length] and (match_length+=1) == b10_string.length
puts "String found at Pi*10^-#{i}."
return
end
match_length = 0
end
puts "String not found within #{i} digits."
end
find_in_pi ARGV.join(" "), "./pi-billion.txt"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment