Skip to content

Instantly share code, notes, and snippets.

@scrogson
Created April 27, 2009 08:08
Show Gist options
  • Save scrogson/102385 to your computer and use it in GitHub Desktop.
Save scrogson/102385 to your computer and use it in GitHub Desktop.
Letter histogram
def letter_stats(string)
string.gsub!(/[^A-z]/, '').upcase!
letters = {}
string.split('').each do |letter|
if letters[letter].nil?
letters[letter] = { sightings: 1,
frequency: (1.to_f / string.size.to_f * 100).ceil }
else
letters[letter][:sightings] += 1
letters[letter][:frequency] = (letters[letter][:sightings].to_f / string.size.to_f * 100).ceil
end
end
letters.sort
end
string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG THIS IS AN EXAMPLE OF HOW TO TEST YOUR HISTOGRAM PROGRAM. YOU CAN USE THIS EXAMPLE."
data = letter_stats(string)
data.each do |k, v|
puts "#{k} - #{v[:sightings]}, (#{v[:frequency]}%)"
end
# >> A - 7, (7%)
# >> B - 1, (1%)
# >> C - 2, (2%)
# >> D - 1, (1%)
# >> E - 9, (9%)
# >> F - 2, (2%)
# >> G - 3, (3%)
# >> H - 6, (6%)
# >> I - 5, (5%)
# >> J - 1, (1%)
# >> K - 1, (1%)
# >> L - 3, (3%)
# >> M - 5, (5%)
# >> N - 3, (3%)
# >> O - 11, (11%)
# >> P - 4, (4%)
# >> Q - 1, (1%)
# >> R - 6, (6%)
# >> S - 7, (7%)
# >> T - 8, (8%)
# >> U - 5, (5%)
# >> V - 1, (1%)
# >> W - 2, (2%)
# >> X - 3, (3%)
# >> Y - 3, (3%)
# >> Z - 1, (1%)
<?php
function countLetters($str)
{
$str = preg_replace('/[^A-z]/', '', $str);
$str = strtoupper($str);
$total = strlen($str);
$letters = array();
for ($i=0; $i < strlen($str); $i++)
{
$letters[$i] = $str{$i};
}
$histogram = array();
foreach ($letters as $letter)
{
if (isset($histogram[$letter]))
$histogram[$letter]++;
else
$histogram[$letter] = 1;
}
$data = array();
foreach ($histogram as $letter => $sightings)
{
$data[$letter] = array('sightings' => $sightings, 'frequency' => round($sightings / $total * 100));
}
ksort($data);
return $data;
}
$str = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG THIS IS AN EXAMPLE OF HOW TO TEST YOUR HISTOGRAM PROGRAM. YOU CAN USE THIS EXAMPLE.';
$data = countLetters($str);
foreach ($data as $key => $value)
{
echo "The letter $key was found {$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