Skip to content

Instantly share code, notes, and snippets.

@karmatr0n
Last active November 30, 2022 15:34
Show Gist options
  • Save karmatr0n/cf1a624624b4a80b8a14ddb27766d0a3 to your computer and use it in GitHub Desktop.
Save karmatr0n/cf1a624624b4a80b8a14ddb27766d0a3 to your computer and use it in GitHub Desktop.
might_i_recommend_ruby.rb
require 'uri'
require 'net/http'
require 'csv'
class Downloader
attr_accessor :uri, :content
def initialize(uri)
@uri = URI(uri)
@content = nil
end
def download
response = Net::HTTP.get_response(uri)
@content = response.body if response.is_a?(Net::HTTPSuccess)
end
end
class CompactDisk
LIMIT = 120
attr_accessor :rows, :entries
def initialize(content, headers = true)
@rows = CSV.parse(content, headers: headers)
@entries = {}
end
def songs_per_url
@rows.each_with_object({}) do |row, hash|
key = row['url']
hash[key] = [] unless hash.key?(row['url'])
hash[key].push([row['filename'], row['size in kilobytes']])
end
end
def playlist
results = {}
songs_per_url.each do |key, songs|
size = songs.map {|song| song[1].to_i }.sum / 1024
if size > LIMIT
0.upto(size/LIMIT) do |i|
k = [key, i].join('_')
results[k] = []
songs.each do |song|
break if results[k].map {|song| song[1].to_i }.sum / 1024 > LIMIT
results[k].push(song)
end
songs -= results[k]
next
end
else
results[key] = songs
end
end
results
end
end
url = 'https://gist.githubusercontent.com/Schwad/9938bc64a88727a3ab2eaaf9ee63c99a/raw/6519e28c85820caac2684cfbec5fe4af33f179a4/rows_of_sweet_jams.csv'
downloader = Downloader.new(url)
downloader.download
compact_disk = CompactDisk.new(downloader.content)
pp compact_disk.playlist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment