public
Created

Benford Counter

  • Download Gist
benford_counter.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
class BenfordCounter
def initialize
@num_count = {}
 
# Set all values to zero
(1..9).each {|num| @num_count[num] = 0 }
 
@total_records = 0
@min_value = 9999999999
@max_value = 0
end
 
def count(string_value)
# Turn it into a nice string if it isn't already
string_value = string_value.to_s
string_value.gsub!(',', '')
string_value.strip!
 
# Create an integer for nice comparisons
int_value = string_value.to_i
 
# Make sure we have a number and it's positive
if string_value.length > 0 && int_value > 0
# Get the first number from the string
first_num = string_value[0].chr.to_i
 
if first_num > 0
@min_value = int_value if int_value < @min_value
@max_value = int_value if int_value > @max_value
 
@num_count[first_num] += 1
@total_records += 1
end
end
end
 
def results
@num_count.each do |first_num, num_records|
percentage = num_records.quo(@total_records) * 100
puts first_num.to_s + ": " + num_records.to_s + ": " + percentage.to_f.to_s + "%"
end
 
puts "Total records: #{@total_records.to_s}"
puts "Min value: #{@min_value.to_s}"
puts "Max value: #{@max_value.to_s}"
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.