Skip to content

Instantly share code, notes, and snippets.

@cdimartino
Created November 29, 2022 22:39
Show Gist options
  • Save cdimartino/aa20025aecb80bf7ad87b2f2792862ce to your computer and use it in GitHub Desktop.
Save cdimartino/aa20025aecb80bf7ad87b2f2792862ce to your computer and use it in GitHub Desktop.
# From https://gist.github.com/Schwad/44f01093e4fe7d8a083a0bc2ac246918
#
# Given Data:
# https://gist.githubusercontent.com/Schwad/9938bc64a88727a3ab2eaaf9ee63c99a/raw/6519e28c85820caac2684cfbec5fe4af33f179a4/rows_of_sweet_jams.csv
#
# Output:
# - Has the blog URLs as key values
# - Each blog URL key points to nested arrays.
# - The arrays each have a list of filenames and kilobyte values of songs found on that website.
# - An array's total megabytes cannot exceed 120. (This is the limit when burning an 80 minute audio CD!)
require "csv"
require "debug"
require "pp"
class MightIRecommend
attr_reader :list
def initialize(csv)
@list = CSV.parse(csv, headers: true)
end
def to_s
to_songs.group_by { |song| song.url }.map do |url, songs|
[
url,
Albumator.new(songs, album_type: MixTape).to_albums
]
end.to_h
end
private
def to_songs
list.map do |row|
Song.new(
url: row["url"],
email: row["email"],
filename: row["filename"],
size: row["size in kilobytes"]
)
end
end
end
class Albumator
attr_reader :album_type, :songs
def initialize(songs = [], album_type:)
@songs = songs
@album_type = album_type
end
def to_albums
[].tap do |albums|
albums << album_type.new
songs.each do |song|
added = albums.last << song
unless added
albums << album_type.new
albums.last << song
end
end
end
end
end
class MixTape
MAX_BYTES = 120_000_000
attr_reader :album
def initialize
@album = []
end
#
# Adds the song to the album (if space is available). Returns false if unable to add to the album.
#
def <<(song)
return false if song.size >= remaining_space
@album << song
end
def inspect
album.inspect
end
def size
album.map { |song| song.size }.sum
end
private
def remaining_space
MAX_BYTES - size
end
end
#<CSV::Row "url":"http://murazik.io/mandi.konopelski" "email":"[email protected]" "filename":"twilight_laser/laborum.mp3" "size in kilobytes":"8107">
class Song
attr_reader :email, :filename, :size, :url
def initialize(url:, email:, filename:, size:)
@url = url
@email = email
@filename = filename
@size = size.to_i * 1000 # convert KB to Bytes
end
def inspect
[filename, size]
end
end
URL = %{https://gist.githubusercontent.com/Schwad/9938bc64a88727a3ab2eaaf9ee63c99a/raw/6519e28c85820caac2684cfbec5fe4af33f179a4/rows_of_sweet_jams.csv}
pp MightIRecommend.new(`curl --silent #{URL}`).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment