Skip to content

Instantly share code, notes, and snippets.

@rayning0
Last active December 24, 2015 01:19
Show Gist options
  • Save rayning0/6722922 to your computer and use it in GitHub Desktop.
Save rayning0/6722922 to your computer and use it in GitHub Desktop.
Song List (used Bubble Sort)
# Raymond Gan
# Given this List of Songs, Construct Arrays by Artist and Album
# Hint: Make use of the split() String Method
# http://www.ruby-doc.org/core-1.9.3/String.html#method-i-split
# Simple Example of Data Parsing
songs = [
"The Magnetic Fields - 69 Love Songs - Parades Go By",
"The Magnetic Fields - Get Lost - Smoke and Mirrors",
"Neutral Milk Hotel - In An Aeroplane Over the Sea - Holland 1945",
"The Magnetic Fields - Get Lost - You, Me, and the Moon",
"The Magnetic Fields - 69 Love Songs - The Book of Love",
"Neutral Milk Hotel - In An Aeroplane Over the Sea - The King of Carrot Flowers"
]
def aas(songs) # create nested array
songs2 = []
songs.each do |s|
cut = []
cut = s.split(' - ')
songs2 << [cut[0], cut[1], cut[2]]
end
songs2
end
a = aas(songs)
(a.size).times do
(0..a.size - 2).each do |row|
if a[row][0] >= a[row+1][0] # sort by artist (column 0)
a[row], a[row + 1] = a[row + 1], a[row] # swap
end
#p a
end
end
puts
(a.size).times do
(0..a.size - 2).each do |row|
if a[row][1] > a[row+1][1] && a[row][0] >= a[row+1][0] # sort by album (column 1)
a[row], a[row + 1] = a[row + 1], a[row]
end
#p a
end
end
puts
(a.size).times do
(0..a.size - 2).each do |row|
if a[row][2] > a[row+1][2] && a[row][1] >= a[row+1][1] && a[row][0] >= a[row+1][0] # sort by song (column 2)
a[row], a[row + 1] = a[row + 1], a[row]
end
#p a
end
end
a.each do |song|
puts "#{song[0]} - #{song[1]} - #{song[2]}"
end
# puts a.sort_by {|artist, album, song| [artist, album, song]} -- quick way to solve it. Use sort_by method!
# Output:
#Neutral Milk Hotel - In An Aeroplane Over the Sea - Holland 1945
#Neutral Milk Hotel - In An Aeroplane Over the Sea - The King of Carrot Flowers
#The Magnetic Fields - 69 Love Songs - Parades Go By
#The Magnetic Fields - 69 Love Songs - The Book of Love
#The Magnetic Fields - Get Lost - Smoke and Mirrors
#The Magnetic Fields - Get Lost - You, Me, and the Moon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment