Skip to content

Instantly share code, notes, and snippets.

@relyks
Created November 30, 2022 07:03
Show Gist options
  • Save relyks/b486e3411cdd5194e5c04b33d13e47df to your computer and use it in GitHub Desktop.
Save relyks/b486e3411cdd5194e5c04b33d13e47df to your computer and use it in GitHub Desktop.
My Solution for Shopify’s Day 1 Challenge at RubyConf 2022
require 'csv'
require 'json'
def produce_song_list_from_song_entries(song_entries)
song_entries
.map { |_, _, song, size| [File.basename(song), size.to_i] }
.sort_by { |song, size| size }
.reverse
end
Album = Struct.new(:size, :songs)
def albums_from_song_list(song_list)
albums = []
if !song_list.empty?
albums << Album.new(0, [])
end
song_list.each do |song|
song_name, song_size = song
found_spot_in_album = false
albums.each do |album|
if album.size + song_size <= 122_880
found_spot_in_album = true
album.songs << song
album.size += song_size
break
end
end
unless found_spot_in_album
albums << Album.new(song_size, [song])
end
end
return albums.map(&:songs)
end
# songs = CSV.parse(File.read("rows_of_sweet_jams.csv"), headers: true).to_a[1..-1]
songs_enumerator = Enumerator.new do |e|
CSV.foreach("rows_of_sweet_jams.csv") { |r| e.yield r.to_a }
end
sites_to_song_entries =
songs_enumerator
.lazy
.group_by { |entry| entry.first }
.map { |site, song_entries|
[
site,
produce_song_list_from_song_entries(song_entries)
.then { |song_list| albums_from_song_list(song_list) }
]
}
.to_h
.to_json
puts sites_to_song_entries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment