Created
February 12, 2014 15:16
-
-
Save mnd999/8957352 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package spotifybox | |
import java.net.HttpURLConnection | |
import java.net.URI | |
import java.net.URL | |
import scala.io.Source | |
import scala.xml.XML | |
import java.net.URLEncoder | |
object SpotifyBox extends App { | |
val songs = getSongs("love").sortBy((x) => -x.length) | |
println(songs) | |
val answer = boxPack2(songs, 1500) | |
def sumTracks(tracks: Seq[Track]): Float = { | |
tracks.foldLeft(0f)((acc, track) => acc + track.length) | |
} | |
var runningTotal = 0f; | |
answer.foreach(track => { | |
runningTotal += track.length | |
println(s"${track.artist} ${track.title} ${timeFormat(track.length)} ${timeFormat(runningTotal)}") | |
}) | |
def timeFormat(timef : Float) : String = { | |
def timePad(s: Int): String = { | |
if (s < 10) { | |
"0" + s | |
} else { | |
s.toString | |
} | |
} | |
val time = timef.toInt | |
s"${time / 60}:${timePad(time % 60)}" | |
} | |
def getSongs(query: String): Seq[Track] = { | |
val url = new URL("http://ws.spotify.com/search/1/track?q=" + URLEncoder.encode(query, "utf-8")); | |
val xml = XML.load(url.openConnection().getInputStream()) | |
(xml \ "track").map(track => ( | |
Track((track \ "name").text, (track \ "artist" \ "name").text, (track \ "length").text.toFloat))) | |
} | |
def boxPack2(list: Seq[Track], len: Float): Seq[Track] = { | |
def boxPack2(list: Seq[Track], len: Float, box: Seq[Track]): Seq[Track] = { | |
list match { | |
case Nil => box | |
case h :: t if h.length < len => boxPack2(t, len-h.length, h +: box) | |
case h :: t => boxPack2(t, len, box) | |
} | |
} | |
var bestFit = boxPack2(list, len, Seq()) | |
var ewHax = list.tail | |
while (sumTracks(ewHax) > len) { | |
val fit = boxPack2(ewHax, len, Seq()) | |
ewHax = ewHax.tail | |
if (sumTracks(fit) > sumTracks(bestFit)) { | |
bestFit = fit | |
} | |
} | |
bestFit | |
} | |
} | |
case class Track(title: String, artist: String, length: Float) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment