Skip to content

Instantly share code, notes, and snippets.

@TylerRockwell
Last active August 31, 2015 22:38
Show Gist options
  • Save TylerRockwell/39d8f5d68a7f2a2a51e0 to your computer and use it in GitHub Desktop.
Save TylerRockwell/39d8f5d68a7f2a2a51e0 to your computer and use it in GitHub Desktop.
Week 1 Exercise 1 - User Input Statistics
#WARNING! This code is functional but has some redundancy
#LEVEL: NIGHTMARE
def is_a_number(input)
true if Float(input) rescue false
end
def get_input()
puts "Please give me your input:"
gets.chomp
end
def count_e(megaString)
count = 0
megaString.split("").each do |letter|
count +=1 if letter=="e"
end
count
end
def find_median(numbers)
size = numbers.count
#Check if number of inputs is even or odd
if size % 2 == 0
#Average 2 middle numbers
(numbers[size/2]+numbers[size/2-1])/2.0
else
#Return middle number
numbers[numbers.size/2]
end
end
def find_std_deviation(numbers, average)
total = 0
#Calculate variance
numbers.each do |x|
total += (x - average) ** 2
end
#Calculate and return Standard Deviation
(1.0/(numbers.count-1) * total) ** 0.5
end
#Initialize variables
input = 0
numbers = []
#Get initial input
input = get_input
#Check if initial input is a number
if is_a_number(input)
#Add initial input to array
numbers.push(input.to_f)
#Adds input to total if a number or sends a message to the user if not
while(input != "")
input = get_input
if is_a_number(input)
numbers.push(input.to_f)
else
#Outputs a message to the user if they enter a non-number
input != "" ? (puts "You started with numbers! You can't just switch it up like that") : ()
break
end
end
#Output statistics
total = numbers.inject(:+)
average = total / numbers.length
median = find_median(numbers)
deviation = find_std_deviation(numbers, average)
puts "The total for all numbers entered is: #{total}."
puts "The average of the numbers entered is: #{average}."
puts "The standard deviation is #{deviation}."
puts "The median is #{median}"
#If the initial input is not a number
else
numInputs = 0
megaString =""
megaString += input
total = input.length
while(input != "")
input = get_input
if is_a_number(input)
puts "Get out of here with those numbers!"
break
else
megaString += input
total += input.length
numInputs += 1
end
end
#Calculates average string length and number of 'e's
average = Float(total) / numInputs
numberE = count_e(megaString)
puts "Here is all the text you entered: #{megaString}."
puts "The average word length is: #{average}."
puts "Your input contained #{numberE} e's."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment