Last active
February 28, 2024 15:21
-
-
Save missinglink/8514030275b7c4f97b7c87820b2945f9 to your computer and use it in GitHub Desktop.
compute the cartesian product of formula one team/player scores
This file contains hidden or 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
// copy->paste into the browser console and wait | |
// note: sorted with the highest points last | |
const csv = (text) => | |
text | |
.trim() | |
.split('\n') | |
.map((r) => { | |
const c = r.split(',').map((c) => c.trim()) | |
return { | |
id: c[0], | |
salary: parseFloat(c[1]), | |
points: parseFloat(c[2]), | |
} | |
}) | |
const TEAMS = csv(` | |
Red Bull,30,156 | |
Ferrari,24.4,138 | |
McLaren,27.2,142 | |
Aston,18.8,115 | |
Merc,21.6,138 | |
Alpine,16,124 | |
Vicarb,13.2,111 | |
Williams,10.4,100 | |
Stake,7.6,97 | |
Haas,4.8,100 | |
`) | |
const DRIVERS = csv(` | |
Perez,28.6,138 | |
Norris,27.2,149 | |
Max,30,166 | |
Russell,25.8,144 | |
Leclerc,24.4,139 | |
Sainz,23,137 | |
Hamilton,21.6,131 | |
Alonso,18.8,125 | |
Piastri,20.2,136 | |
gasly,17.4,128 | |
ocon,16,122 | |
Albon,14.6,114 | |
Stroll,13.2,114 | |
Tsunoda,11.8,107 | |
Daniel,10.4,118 | |
Zho,9,106 | |
Hulk,7.6,105 | |
Bottas,6.2,99 | |
Sargent,4.8,104 | |
Kmag,3.4,95 | |
`) | |
const MAX_SPEND = 100 | |
const MAX_RESULTS = 20 | |
let candidates = [] | |
const unique = new Set() | |
// select candidates | |
const cartesian = (team, drivers) => { | |
const salary = drivers.reduce((sum, d) => sum + d.salary, team.salary) | |
if (salary > MAX_SPEND) return | |
candidates.push({ | |
team: team.id, | |
drivers: drivers.map((d) => d.id), | |
points: drivers.reduce((sum, d) => sum + d.points, team.points), | |
salary, | |
}) | |
candidates = candidates | |
.sort((a, b) => a.points - b.points) | |
.slice(-MAX_RESULTS) | |
} | |
// unique cartesian product | |
TEAMS.forEach((t) => { | |
DRIVERS.forEach((d1) => { | |
DRIVERS.forEach((d2) => { | |
if (d1.id === d2.id) return | |
DRIVERS.forEach((d3) => { | |
if (new Set([d1.id, d2.id, d3.id]).size !== 3) return | |
DRIVERS.forEach((d4) => { | |
if (new Set([d1.id, d2.id, d3.id, d4.id]).size !== 4) return | |
DRIVERS.forEach((d5) => { | |
if (new Set([d1.id, d2.id, d3.id, d4.id, d5.id]).size !== 5) return | |
const k = [t.id, d1.id, d2.id, d3.id, d4.id, d5.id].sort().join('|') | |
if (!unique.has(k)) cartesian(t, [d1, d2, d3, d4, d5]) | |
unique.add(k) // dedupe | |
}) | |
}) | |
}) | |
}) | |
}) | |
}) | |
// sort and print results | |
candidates.forEach((c) => console.log(c)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment