package recommendation import "github.com/jackc/pgx/v5/pgtype" // artistGap is how many other songs SpreadArtists puts between two songs by // one artist when the picks allow it. Radio's best matches are usually the // seed artist's own songs, and played in score order they would open the // radio back to back; three songs between them keeps the artist present // without the radio sounding like an album. const artistGap = 3 // SpreadArtists reorders picks so that, where another choice exists, an // artist doesn't play again within artistGap songs. It changes only the // order, never which songs are picked. // // Each slot takes the best-scoring remaining pick whose artist is outside the // gap, so the strongest picks stay near the front. When every remaining pick // is by a recently played artist, the slot takes the one whose artist was // played longest ago, so a pool of two artists alternates rather than // clumping. A pick with no known artist is never held back. // // lastPlayed lists the artists heard just before these picks, oldest first: // a radio's seed song plays first, so its artist counts as just played. func SpreadArtists(picks []Candidate, lastPlayed ...pgtype.UUID) []Candidate { if len(picks) < 2 { return picks } remaining := append([]Candidate(nil), picks...) out := make([]Candidate, 0, len(picks)) // lastAt is the position each artist last played at, counting the // lastPlayed songs as positions before 0. lastAt := make(map[[16]byte]int, len(picks)) for i, a := range lastPlayed { if a.Valid { lastAt[a.Bytes] = i - len(lastPlayed) } } for len(remaining) > 0 { pos := len(out) choice := -1 oldest, oldestAt := -1, 0 for i, c := range remaining { a := c.Track.ArtistID at, played := lastAt[a.Bytes] if !a.Valid || !played || pos-at > artistGap { choice = i break } if oldest < 0 || at < oldestAt { oldest, oldestAt = i, at } } if choice < 0 { choice = oldest } c := remaining[choice] remaining = append(remaining[:choice], remaining[choice+1:]...) if c.Track.ArtistID.Valid { lastAt[c.Track.ArtistID.Bytes] = pos } out = append(out, c) } return out }