Last active
June 14, 2017 00:52
-
-
Save ryanveroniwooff/7fbf02995f61b29ca873d13488a7e7a9 to your computer and use it in GitHub Desktop.
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
# readFile sets up a new file right away by calling writeFile | |
# then stores the file as readfile and returns the formatFile method on the readfile | |
def readFile | |
writeFile | |
file = File.open(File.expand_path File.dirname(__FILE__) + "/output.txt") | |
readfile = file.read | |
file.close | |
readfile.formatFile | |
end | |
# writeFile creates a file containing 1 million random numbers | |
def writeFile | |
array = [] | |
1000000.times{ array << rand(10) } | |
fname = "output.txt" | |
file = File.open(fname, "w") # a = append, w = wipe | |
file.puts array | |
file.close | |
end | |
# formatFile formats the file into a sorted array of integers | |
class String | |
def formatFile | |
self.gsub(/[^0-9]\s/, ' ').split(' ').map {|e| e.to_i}.sort | |
end | |
end | |
# occurence returns the most frequently occuring number from the file | |
# and outputs a string such as: | |
#=> The number 5 accounted for 10.3% of the 1,000,000 items. | |
class Array | |
def occurence(n) | |
occurence = ((self.count(n) / (self.size).to_f) * 100).round(2) | |
size = self.size.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse | |
puts "The number #{n} accounted for #{occurence}\% of the #{size} items." | |
end | |
end | |
readFile.occurence(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment