Skip to content

Instantly share code, notes, and snippets.

@gsheppard
Created February 24, 2014 00:46
Show Gist options
  • Save gsheppard/9179716 to your computer and use it in GitHub Desktop.
Save gsheppard/9179716 to your computer and use it in GitHub Desktop.
# report average, lowest, and highest scores
require 'pry'
def bubble_sort scores
bubbled = scores
outer = 0
while outer < bubbled.length - 1
inner = 0
while inner < bubbled.length - 1
if bubbled[inner] > bubbled[inner+1]
bubbled[inner], bubbled[inner+1] = bubbled[inner+1], bubbled[inner]
end
inner += 1
end
outer += 1
end
bubbled
end
def get_average scores
total = 0
scores.each {|num| total += num }
total / scores.length
end
# ------- Method Barrier
test_scores = [75, 100, 85, 65, 84, 87, 95]
sorted = bubble_sort(test_scores.dup)
print " Test scores: "
puts test_scores.join(' ')
print "Sorted scores: "
puts sorted.join(' ')
print " Lowest score: "
puts sorted[0]
print "Highest score: "
puts sorted[-1]
print "Average score: "
puts get_average(sorted)
@hchood
Copy link

hchood commented Feb 24, 2014

Nice work!

One formatting note: Setting your tab size in Sublime to 2 should avoid the big indents. (A tab size of 2 is standard for Ruby code.)

A few suggestions / notes:

  1. I'd try to use variable names that clearly indicate what the variable is. Instead of outer and inner, I'd use outer_counter and inner_counter. (Good naming is one of the hardest things in coding, I've found -- definitely a learned skill.)
  2. You might want to tinker with your average method to return a more precise average. (The actual average is 84.43-something.) To do that, you need to convert at least one of the numbers to a float. If you divide two integers, you unfortunately will get an integer, not a float:
2.0.0-p353 :001 > 3/2
 => 1
2.0.0-p353 :002 > 3.0/2
 => 1.5
  1. If you wanted to refactor, you could try creating max and min methods without sorting. You could also create a method to output class statistics.

Good job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment