Public
Edited
Jan 3, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// rockPaperScissors :: [Game] => [Strategy] => [[Number]]
// Executes all strategies on all games and returns their scores.
rockPaperScissors = (games) => (strategies) => map(plays(games))(strategies)
Insert cell
Insert cell
((strategy)=>pipe(split("\n"),map(pipe(split(" "),normalize,strategy,score,sum)),sum))(strategies[0])(rawGames[0])
Insert cell
Insert cell
// execute :: gameString => Score
// Execute a specific strategy on a specific game and returns its total score.
execute =
(strategy) =>
// (input) =>
pipe( // input: `A Y\n B X\n C Z\n`
split("\n"), // → [Line]: ["A Y", "B X", "C Z"]
map( // execute strategy on normalized rounds, sum results
pipe(
split(" "), // → [Token]: [["A", "Y"], ["B", "X"], ["C", "Z"]]
normalize, // → [Round]: [[0, 1], [1, 0], [2, 2]]
strategy, // → [Outcome]: [[2, 1], [0, 0], [2, 2]]
score, // → [[Score]]: [[6, 2], [0, 1], [3, 3]]
sum, // → [Score]: [8, 1, 6]
)
),
sum // → 15
)
// (input)
Insert cell
Insert cell
execute(strategies[0])(rawGames[0])
Insert cell
Insert cell
plays = (games) => (strategy) => (map(execute(strategy))(games))
Insert cell
plays(rawGames)(strategies[1])
Insert cell
rawGames = [
`A Y\nB X\nC Z`,
await FileAttachment("input.txt").text()
]
Insert cell
Insert cell
Insert cell
//
strategies = [

// :: Round → Outcome
([opponent, you]) => // part 1: each Round has [Shape, Shape]
[
// outcome points index: 0: Lose, 1: Draw, 2: Win
(1 + 2 * opponent + you) % 3,

// you points index: 0: Rock, 1: Paper, 2: Scissors
you,
],

// :: Round → Outcome
([opponent, outcome]) => [ // part 2: each Round has [Shape, Outcome]

// 0: Lose, 1: Draw, 2: Win
outcome,

// shape you must play to achieve given outcome
(opponent + outcome + 2) % 3, // 0: Rock, 1: Paper, 2: Scissors
]
]
Insert cell
Insert cell
// normalize :: Token → Round
// convert a letter tuple to its number tuple
// ["A", "Y"] → [0, 1]
normalize = ([p, q]) => ([A(p), X(q)])
Insert cell
normalize(["A", "Y"])
Insert cell
Insert cell
// score :: Outcome → Score
// takes an Outcome
// returns its Score
score = ([outcome, you]) => [
[0,3,6][outcome], // Lose, Draw, Win
[1,2,3][you] // Rock, Paper, Scissors
]
Insert cell
score([2, 1])
Insert cell
Insert cell
// takes character
// returns distance from "A"
A = n("A")
Insert cell
#### ƒ `X :: Letter → Number`
Insert cell
// takes character
// returns distance from "X"
X = n("X")
Insert cell
Insert cell
// takes a base character
// returns function that takes a character and returns its distance from base
n = (base) => (c) => c.charCodeAt(0) - base.charCodeAt(0)
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more