Advertisement
musifter

AoC 2024, day 23 (smalltalk)

Dec 23rd, 2024 (edited)
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 2.17 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Symbol extend [ value: arg [^arg perform: self] ]
  4.  
  5. Object subclass: Graph [
  6.     | graph |
  7.     Graph class >> new: conxArray  [^super new init: conxArray]
  8.     init: conxArray [
  9.         graph := Dictionary new.
  10.         conxArray do: [:str |
  11.            | ends |
  12.             ends := (str substrings: '-') collect: #asSymbol.
  13.             (graph at: ends first  ifAbsentPut: [Set new]) add: ends second.
  14.             (graph at: ends second ifAbsentPut: [Set new]) add: ends first.
  15.         ].
  16.         ^self
  17.     ]
  18.  
  19.     " Part 1: "
  20.     complete3withStartT [
  21.         | res |
  22.         res := Set new.
  23.  
  24.         " Start at computers beginning with T "
  25.         (graph keys select: [:c | c startsWith: #t]) do: [:comp |
  26.             (graph at: comp) do: [:neigh |
  27.                 " Looking in neighbours of neighbours for starting computer "
  28.                 ((graph at: neigh) select: [:n | (graph at: n) includes: comp]) do: [:third |
  29.                     res add: ({comp. neigh. third} sorted join: ',').
  30.                 ].
  31.             ].
  32.         ].
  33.         ^res size
  34.     ]
  35.  
  36.     " Part 2: Finding maximum sized clique using Bron-Kerbosch algorithm "
  37.     recurseBK: r poss: p exc: x [
  38.         | cliques res poss exc |
  39.         res  := r.
  40.         poss := p.
  41.         exc  := x.
  42.  
  43.         (poss isEmpty & exc isEmpty) ifTrue: [^Array with: res].
  44.  
  45.         cliques := Set new.
  46.         poss do: [:vertex |
  47.            | vertSet |
  48.             vertSet := Set with: vertex.
  49.             cliques addAll: (self recurseBK: (res  + vertSet)
  50.                                        poss: (poss & (graph at: vertex))
  51.                                         exc: (exc  & (graph at: vertex))).
  52.  
  53.             poss := poss - vertSet.
  54.             exc  := exc + vertSet.
  55.         ].
  56.         ^cliques
  57.     ]
  58.  
  59.     getCliques [
  60.         ^self recurseBK: Set new poss: (Set from: graph keys) exc: Set new.
  61.     ]
  62. ]
  63.  
  64. "
  65. | Mainline
  66. "
  67. graph := Graph new: stdin lines.
  68.  
  69. ('Part 1: %1' % {graph complete3withStartT}) displayNl.
  70.  
  71. max_clique := graph getCliques fold: [:a :b | (a size > b size) ifTrue: [a] ifFalse: [b]].
  72. ('Part 2: %1' % {max_clique sorted join: ','}) displayNl.
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement