Snippets

marinus Contiguous block count

Created by marinus

File snippet.dyalog Added

  • Ignore whitespace
  • Hide word diff
+⍝ count contiguous blocks
+contig←{
+    G←⍵                             ⍝ input array
+
+    ⍝ do floodfill with 0s on G starting at ⍵
+    flood←{
+        adj←⍵∘+¨(+,-)↓∘.=⍨⍳3       ⍝ adjacent coordinates...
+        adj←(adj∊,⍳⍴G)/adj         ⍝ ...which are within the figure...
+        adj←(1=G[adj])/adj         ⍝ ...and are marked
+        G[⊂⍵]←0                    ⍝ set current position to zero
+        0=⍴adj:⍬                   ⍝ if no adjacent ones, stop
+        ∇¨adj                      ⍝ recurse
+    }
+
+    ⍝ find coordinates of ones
+    ones←(,G)/,⍳⍴G
+
+    0=⍴ones:0  ⍝ no ones = no figures
+
+    ⍝ remove figure starting at first one
+    _←flood⊃ones
+
+    ⍝ the result is 1 + the amount of figures in the modified array
+    1+∇G
+}
+
+⍝ read a block from the interactive input
+read←{
+    ln←{⍞}
+    dm←{
+        0=⍴in←⍺⍺⍬:⍬
+        (⊂in),∇⍬
+    }
+
+    '1'=↑↑↑ln dm dm⍬
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.