ShareMyScreen/AdventOfCode/2023/04/Scratchpads/rdm

From J Wiki
Jump to navigation Jump to search

day 4

1sample=: {{)n
2Card 1: 41 48 83 86 17 | 83 86  6 31 17  9 48 53
3Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
4Card 3:  1 21 53 59 44 | 69 82 63 72 16 21 14  1
5Card 4: 41 92 73 84 69 | 59 84 76 51 58  5 54 83
6Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
7Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
8}}
9day4=: ([fwrite&'2023-day4.txt') fread '~/Downloads/input.txt'

Here, we were working with "scratchcards" and for each line, we needed to know the quantity of numbers to the left of the | character which appeared in the list to its right.

10tallies=: {{ +/@e."1&>/ <@:>"1|:<@(0&".);._1@('|',]);._2 y}}

In other words:

   tallies sample
4 2 2 1 0 0

It's perhaps worth noting that I'm using 0&". to parse each "half" of each line. In other words:

   0 ". 'Card 1: 41 48 83 86 17 '
0 0 41 48 83 86 17
   0 ". ' 83 86  6 31 17  9 48 53'
83 86 6 31 17 9 48 53

The extra zeros in the first "half" don't matter for my purposes, because zeros never appear in the other "half" of the line.

For part 1, I needed to discard 0s from the tallies, and sum a corresponding power of 2. There's a variety of good ways of doing this, but I opted for a slightly awkward brute force approach:

11part1=: +/@{{ 1 -:@-.~ 2 ^ tallies y }}

I probably should have used +/<.2^<:tallies y

For part 2, it was a bit more complicated - for each card we generated 1 extra copy of each of the n following cards where n was the tally from that card. In other words:

12part2=: {{
13   cop=. win=win=. tallies y
14   for_w. win do.
15     ndx=. w_index+1+i.w
16     cop=. cop ndx}~ (ndx{cop)+w_index{cop
17   end.
18   +/cop
19}}

Here, cop is the number of copies of each scratchcard - initially all 1s, and the tally for each scratchcard added 1 copy of each of that many of the following cards. Easier to read the code, maybe, than the english description.

But, it was pointed out to me that there's a much more concise approach:

12part2=: +/@{{ <.,%.y ((]#0:),1,[#_1:)"0 i.#y }}@tallies

It's probably best to sit down with an implementation of J and look at intermediate results here.

   t ((]#0:),1,[#_1:)"0 i.#t=: tallies sample
1 _1 _1 _1 _1 0
0  1 _1 _1  0 0
0  0  1 _1 _1 0
0  0  0  1 _1 0
0  0  0  0  1 0
0  0  0  0  0 1
   %.t ((]#0:),1,[#_1:)"0 i.#t=: tallies sample
1 1 2 4 7 0
0 1 1 2 3 0
0 0 1 1 2 0
0 0 0 1 1 0
0 0 0 0 1 0
0 0 0 0 0 1

But I'm still trying to think of a good way of describing the problem itself in english, ...

Note that what's happening here is vaguely related to the fibonacci sequence.

   %.(=i.9)-1|.!.0(=i.9)+1|.!.0(=i.9)
1 1 2 3 5 8 13 21 34
0 1 1 2 3 5  8 13 21
0 0 1 1 2 3  5  8 13
0 0 0 1 1 2  3  5  8
0 0 0 0 1 1  2  3  5
0 0 0 0 0 1  1  2  3
0 0 0 0 0 0  1  1  2
0 0 0 0 0 0  0  1  1
0 0 0 0 0 0  0  0  1

day 3 day 5