Created
April 27, 2016 21:24
-
-
Save garrettgsb/eb8eb5dec6c99c2a87207328e69b32d3 to your computer and use it in GitHub Desktop.
Counting Characters
This file contains 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
require 'pry' | |
## Counts characters, omitting spaces | |
def char_count(target) | |
target = target.gsub(" ","") | |
tally = Hash.new(0) | |
target.each_char {|x| tally[x] += 1} | |
tally | |
end | |
puts char_count('Chi putao bu tu putao pi') | |
def char_positions(target) | |
# Assuming the index INCLUDING WHITE SPACE is important | |
tally = Hash.new{|h,k| h[k] = []} # What's going on here: http://stackoverflow.com/questions/2698460/strange-behavior-when-using-hash-default-value-e-g-hash-new | |
target.each_char.each_with_index {|x,i| tally[x] << i} | |
return tally | |
end | |
puts char_positions("Chi putao bu tu putao pi") | |
puts char_positions(".aaaaaaaabbbbbbbbccccccccdddddddd") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment