Created
April 20, 2009 15:22
-
-
Save scrogson/98580 to your computer and use it in GitHub Desktop.
(PHP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function benford($str) { | |
$nums = explode(' ', $str); | |
$nums = array_map('firstChar', $nums); | |
$total = sizeof($nums); | |
$histogram = array(); | |
foreach ($nums as $num) { | |
if (isset($histogram[$num])) { | |
$histogram[$num]++; | |
} else { | |
$histogram[$num] = 1; | |
} | |
} | |
$data = array(); | |
foreach ($histogram as $numeral => $sightings) { | |
$data[$numeral] = array('sightings' => $sightings, 'frequency' => round($sightings / $total * 100)); | |
} | |
return $data; | |
} | |
function firstChar($str) { | |
return $str{0}; | |
} | |
$str = '123 456 789 123 123 456 456 789 789 987 987 654 654 321 321 123 123 123 456 456 123 123 123 234 231 231 231 233 233 234 564 564 564 897 897 978 987 897 897 897 654 987 789 789 789'; | |
$data = benford($str); | |
ksort($data); | |
foreach ($data as $key => $value) { | |
echo "The number $key was seen {$value['sightings']} times, which is a frequency of {$value['frequency']}%\n"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment