Day 22: Monkey Market

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

5 points

Rust

Nice breather today (still traumatized from the robots). At some point I thought you had to do some magic for predicting special properties of the pseudorandom function, but no, just collect all values, have a big table for all sequences and in the end take the maximum value in that table. Part 1 takes 6.7ms, part 2 19.2ms.

Solution
fn step(n: u32) -> u32 {
    let a = (n ^ (n << 6)) % (1 << 24);
    let b = a ^ (a >> 5);
    (b ^ (b << 11)) % (1 << 24)
}

fn part1(input: String) {
    let sum = input
        .lines()
        .map(|l| {
            let n = l.parse().unwrap();
            (0..2000).fold(n, |acc, _| step(acc)) as u64
        })
        // More than 2¹⁰ 24-bit numbers requires 35 bits
        .sum::<u64>();
    println!("{sum}");
}

const N_SEQUENCES: usize = 19usize.pow(4);

fn sequence_key(sequence: &[i8]) -> usize {
    sequence
        .iter()
        .enumerate()
        .map(|(i, x)| (x + 9) as usize * 19usize.pow(i as u32))
        .sum()
}

fn part2(input: String) {
    // Table for collecting the amount of bananas for every possible sequence
    let mut table = vec![0; N_SEQUENCES];
    // Mark the sequences we encountered in a round to ensure that only the first occurence is used
    let mut seen = vec![false; N_SEQUENCES];
    for l in input.lines() {
        let n = l.parse().unwrap();
        let (diffs, prices): (Vec<i8>, Vec<u8>) = (0..2000)
            .scan(n, |acc, _| {
                let next = step(*acc);
                let diff = (next % 10) as i8 - (*acc % 10) as i8;
                *acc = next;
                Some((diff, (next % 10) as u8))
            })
            .unzip();
        for (window, price) in diffs.windows(4).zip(prices.iter().skip(3)) {
            let key = sequence_key(window);
            if !seen[key] {
                seen[key] = true;
                table[key] += *price as u32;
            }
        }
        // Reset seen sequences for next round
        seen.fill(false);
    }
    let bananas = table.iter().max().unwrap();
    println!("{bananas}");
}

util::aoc_main!();

Also on github

permalink
report
reply
3 points

How have I never noticed that scan() exists? Very handy.

I liked the zipping of the offset prices, neater than my helper method.

permalink
report
parent
reply
5 points
*

Uiua

It’s been a while since I posted one of these, but I thought this would be straightforward in Uiua. Turns out that bitwise operations are a bit (haha) of a pain, so the Rng operation is very slow at 4sec for live data.

I took this as an opportunity to play with the ⧈(stencil) operator which probably slowed things down too.

Data ← 1_2_3_2024
Xor  ← Β°β‹―β—Ώ2⬚0+βˆ©β‹― # Bitwise xor of two numbers.
Rng  ← βŠ™β—Œβ—Ώ,XorΓ—2048.β—Ώ,Xor⌊÷32.β—Ώ,XorΓ—64.βŠ™16777216
Runs ← ⍉(β‡Œ[β₯(Rng.)])2000 Data # Should be constant?
Firsts ← (
  βŠŸβŠ‚0β§ˆβ‚‚/-.β—Ώ10 β†˜Β―1         # Build run, gen pair diffs
  ⊒⧈(βŠŸβŠ™βŠ£/(+Γ—40+20)°⊟) 2_4 # Convert 4-diff into key, collect.
  βŠ•βŠ’βŠ›βŠ™β‰βŠ™β—ŒΒ°βŠŸ.⍉             # Only keep first of each key. # ⍜(mapΒ°βŠŸβ‰β‡Œ|∘) failed. 
)
&p /+β‰‘βŠ£.Runs
&p /β†₯βŠ•(/+)+1βŠ›Β°βŠŸβ‰/β—‡βŠ‚wait≑spawn(β–‘Firsts) # Group by key, sum prices, return highest.
permalink
report
reply
3 points

Haskell

I have no Idea how to optimize this and am looking forward to the other solutions that probably run in sub-single-second times. I like my solution because it was simple to write which I hadn’t managed in the previous days, runs in 17 seconds with no less than 100MB of RAM.

import Control.Arrow
import Data.Bits (xor)
import Data.Ord (comparing)

import qualified Data.List as List
import qualified Data.Map as Map

parse :: String -> [Int]
parse = map read . filter (/= "") . lines

mix = xor 
prune = flip mod 16777216
priceof = flip mod 10

nextSecret step0 = do
        let step1 = prune . mix step0 $ step0 * 64
        let step2 = prune . mix step1 $ step1 `div` 32
        let step3 = prune . mix step2 $ step2 * 2048
        step3

part1 = sum . map (head . drop 2000 . iterate nextSecret)
part2 = map (iterate nextSecret
                >>> take 2001
                >>> map priceof
                >>> (id &&& tail)
                >>> uncurry (zipWith (curry (uncurry (flip (-)) &&& snd)))
                >>> map (take 4) . List.tails
                >>> filter ((==4) . length)
                >>> map (List.map fst &&& snd . List.last)
                >>> List.foldl (\ m (s, p) -> Map.insertWith (flip const) s p m) Map.empty
                )
        >>> Map.unionsWith (+)
        >>> Map.assocs
        >>> List.maximumBy (comparing snd)

main = getContents
        >>= print
        . (part1 &&& part2)
        . parse
permalink
report
reply
3 points

Haha, same! Mine runs in a bit under 4s compiled, but uses a similar 100M-ish peak. Looks like we used the same method.

Maybe iterate all the secrets in parallel, and keep a running note of the best sequences so far? I’m not sure how you’d decide when to throw away old candidates, though. Sequences might match one buyer early and another really late.

permalink
report
parent
reply
3 points

Rust

Not too hard today, apart from yesterday’s visit to a cocktail bar leaving me a little hazy in the mind.

code
use std::{fs, str::FromStr};

use color_eyre::eyre::{Report, Result};
use gxhash::{HashMap, HashMapExt};

const SECRETS_PER_DAY: usize = 2000;
const SEQ_LEN: usize = 4;

type Sequence = [i8; SEQ_LEN];

fn produce(n: usize) -> usize {
    let n = (n ^ (n * 64)) % 16777216;
    let n = (n ^ (n / 32)) % 16777216;
    (n ^ (n * 2048)) % 16777216
}

#[derive(Debug)]
struct Buyer {
    prices: [u8; SECRETS_PER_DAY + 1],
    changes: [i8; SECRETS_PER_DAY],
}

impl Buyer {
    fn price_at_seq(&self, seq: &Sequence) -> Option<u8> {
        self.changes
            .windows(SEQ_LEN)
            .position(|win| win == *seq)
            .and_then(|i| self.price_for_window(i))
    }

    fn price_for_window(&self, i: usize) -> Option<u8> {
        self.prices.get(i + SEQ_LEN).copied()
    }
}

struct BananaMarket {
    buyers: Vec<Buyer>,
}

impl FromStr for BananaMarket {
    type Err = Report;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let buyer_seeds = s
            .lines()
            .map(|s| s.parse::<usize>())
            .collect::<Result<Vec<_>, _>>()?;

        let buyers = buyer_seeds
            .into_iter()
            .map(|seed| {
                let mut prices = [0; SECRETS_PER_DAY + 1];
                let mut changes = [0; SECRETS_PER_DAY];

                let mut secret = seed;
                let mut price = (seed % 10) as u8;
                prices[0] = price;
                for i in 0..SECRETS_PER_DAY {
                    let last_price = price;
                    secret = produce(secret);
                    price = (secret % 10) as u8;
                    prices[i + 1] = price;
                    changes[i] = price as i8 - last_price as i8;
                }
                Buyer { prices, changes }
            })
            .collect();
        Ok(Self { buyers })
    }
}

impl BananaMarket {
    fn sell_with_seq(&self, seq: &Sequence) -> usize {
        self.buyers
            .iter()
            .map(|b| b.price_at_seq(seq).unwrap_or(0) as usize)
            .sum()
    }

    fn maximise_bananas(&self) -> usize {
        let mut cache: HashMap<Sequence, usize> = HashMap::new();

        for seq in self
            .buyers
            .iter()
            .flat_map(|buyer| buyer.changes.windows(SEQ_LEN))
        {
            let seq = seq.try_into().unwrap();
            cache.entry(seq).or_insert_with(|| self.sell_with_seq(&seq));
        }

        cache.into_values().max().unwrap_or(0)
    }
}

fn part1(filepath: &str) -> Result<usize> {
    let input = fs::read_to_string(filepath)?
        .lines()
        .map(|s| s.parse::<usize>())
        .collect::<Result<Vec<_>, _>>()?;
    let res = input
        .into_iter()
        .map(|n| (0..SECRETS_PER_DAY).fold(n, |acc, _| produce(acc)))
        .sum();
    Ok(res)
}

fn part2(filepath: &str) -> Result<usize> {
    let input = fs::read_to_string(filepath)?;
    let market = BananaMarket::from_str(&input)?;
    Ok(market.maximise_bananas())
}

fn main() -> Result<()> {
    color_eyre::install()?;

    println!("Part 1: {}", part1("d22/input.txt")?);
    println!("Part 2: {}", part2("d22/input.txt")?);
    Ok(())
}
permalink
report
reply
2 points

Go

Re-familiarizing myself with Go. The solution to Part 2 is fairly simply, the whole packing of the sequence into a single integer to save on memory was an optimization I did afterwards based on looking at other solutions. I thought it was cool.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

type SequenceMap struct {
	Data map[int32]int
}

func PackSeq(numbers [4]int8) int32 {
	var packed int32
	for i, num := range numbers {
		packed |= int32(num+9) << (i * 5)
	}
	return packed
}

func UnpackSeq(packed int32) [4]int8 {
	var numbers [4]int8
	for i := range numbers {
		numbers[i] = int8((packed>>(i*5))&0x1F) - 9
	}
	return numbers
}

func NewSequenceMap() SequenceMap {
	return SequenceMap{make(map[int32]int)}
}

func (m *SequenceMap) Increment(seq [4]int8, val int) {
	pSeq := PackSeq(seq)
	acc, ok := m.Data[pSeq]
	if ok {
		m.Data[pSeq] = acc + val
	} else {
		m.Data[pSeq] = val
	}
}

func (m *SequenceMap) Has(seq [4]int8) bool {
	pSeq := PackSeq(seq)
	_, ok := m.Data[pSeq]
	return ok
}

type Generator struct {
	Secret         int64
	LastPrice      int8
	ChangeSequence []int8
}

func NewGenerator(Secret int64) Generator {
	var ChangeSequence []int8
	return Generator{Secret, int8(Secret % 10), ChangeSequence}
}

func (g *Generator) Mix(value int64) *Generator {
	g.Secret = g.Secret ^ value
	return g
}

func (g *Generator) Prune() *Generator {
	g.Secret = g.Secret % 16777216
	return g
}

func (g *Generator) Next() {
	g.Mix(g.Secret * 64).Prune().Mix(g.Secret / 32).Prune().Mix(g.Secret * 2048).Prune()
	Price := int8(g.Secret % 10)
	g.ChangeSequence = append(g.ChangeSequence, Price-g.LastPrice)
	g.LastPrice = Price
	if len(g.ChangeSequence) > 4 {
		g.ChangeSequence = g.ChangeSequence[1:]
	}
}

func ParseInput() []int64 {
	if fileInfo, _ := os.Stdin.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {
		fmt.Println("This program expects input from stdin.")
		os.Exit(1)
	}
	scanner := bufio.NewScanner(os.Stdin)

	var numbers []int64
	for scanner.Scan() {
		line := scanner.Text()
		num, err := strconv.ParseInt(line, 10, 64)
		if err != nil {
			fmt.Printf("ERROR PARSING VALUE: %s\n", line)
			os.Exit(1)
		}
		numbers = append(numbers, num)
	}

	return numbers
}

func main() {
	numbers := ParseInput()

	m := NewSequenceMap()
	sum := int64(0)

	for i := 0; i < len(numbers); i += 1 {
		g := NewGenerator(numbers[i])
		tM := NewSequenceMap()
		for j := 0; j < 2000; j += 1 {
			g.Next()
			if len(g.ChangeSequence) == 4 {
				if !tM.Has([4]int8(g.ChangeSequence)) {
					tM.Increment([4]int8(g.ChangeSequence), 1)
					if g.LastPrice > 0 {
						m.Increment([4]int8(g.ChangeSequence), int(g.LastPrice))
					}
				}
			}
		}
		sum += g.Secret
	}

	fmt.Printf("Part One: %d\n", sum)

	var bestSeq [4]int8
	bestPrice := 0
	for pSeq, price := range m.Data {
		if price > bestPrice {
			bestPrice = price
			bestSeq = UnpackSeq(pSeq)
		}
	}

	fmt.Printf("Part Two: %d\n", bestPrice)
	fmt.Printf("Best Sequence: %d\n", bestSeq)
}
permalink
report
reply

Advent Of Code

!advent_of_code@programming.dev

Create post

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

  • Follow the programming.dev instance rules
  • Keep all content related to advent of code in some way
  • If what youre posting relates to a day, put in brackets the year and then day number in front of the post title (e.g. [2024 Day 10])
  • When an event is running, keep solutions in the solution megathread to avoid the community getting spammed with posts

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

Community stats

  • 500

    Monthly active users

  • 104

    Posts

  • 1.1K

    Comments