Logo
Masterquiz

Logic games in APL: Trees

Rules

  1. The aim is to fill the grid with 1 tree per row, column and area.
  2. There can't be adjacent trees.
  3. If side length is greater or equal to 9 you have to put 2 trees per rows/column and area.

Source code

  mat ← 9 9⍴0
  mat[1;] ← 1 1 1 1 2 3 3 3 3
  mat[2;] ← 1 1 1 1 2 2 3 3 3
  mat[3;] ← 1 1 1 2 2 2 4 3 5
  mat[4;] ← 1 1 1 6 2 4 4 4 5
  mat[5;] ← 7 7 6 6 6 6 4 5 5
  mat[6;] ← 7 7 7 6 6 8 5 5 5
  mat[7;] ← 7 7 7 7 8 8 8 5 5
  mat[8;] ← 9 7 7 8 8 8 8 8 5
  mat[9;] ← 9 9 9 9 8 8 8 8 5

  cmat ← {⊖⊃⍪/{k,¨⍪\1+⍵}⍣⍺⊢(⊂⍉⍪⍬),d⍴⊂0 0⍴k←⌽⍳1+d←⍵-⍺}

  check ← {
    ⍺⍺=1: ∧/⍺⍺≥(+/,+⌿)⍵>0
    (∧/⍺⍺≥(+/,+⌿)⍵>0)>(0 1)(1 1)(1 0)∊⍨|-/⍺
  }

  f ← {
    x ← ⍵
    n ← ⍺
    y ← ({⊃⍤⍋⊢∘≢⌸⍵}⌷∪)0~⍨,⍺⍺×0=x
    area ← y=⍺⍺
    n>≢vec ← ⍸(0≤⍵)∧area: ⍬
    vec ← ↓vec[n cmat≢vec]
    res ← {1@⍵⊢x}¨vec
    res ← res/⍨vec(n check)¨res
    adj ← {×⍵-¯1 ¯1↓1 1↓⊃∨/⊃,/4 ¯4↑¨⊂,¯1 0 1∘.⊖¯1 0 1⌽¨⊂0(,∘⌽∘⍉⍣4)1=⍵}¨res
    cr  ← {(⊢-⊢<(n≤+/)∘.∨n≤+⌿)1=⍵}¨res
    (⊢-(⊂area)∧0∘=)adj⌊cr
  }

  solver ← {
    n ← 4 9⍸≢ m ← ⍵
    1={⊃,/n (m f)¨⍵/⍨0∊¨⍵}⍣(⌈/,⍵)⊢⊂{0}¨⍵
  }

  createTree ← {
    mat ← {(1+⌈/,⍵)@(⊂(?∘⍴⊃⊢)∘⍸¨(~+/,⍥⊂+⌿)×⍵)⊢⍵}⍣⍵⊢⍵ ⍵⍴0
    {⍵+(0=⍵)ׯ1 ¯1↓1 1↓⊃⊃⌈/2 4 5 6 8⌷¨⊂,¯1 0 1∘.⊖¯1 0 1⌽¨⊂0(,∘⌽∘⍉⍣4)⍵}⍣≡mat
  }

  creator ← {
    4:: ∇⍵
    n←1+8<≢m←createTree ⍵
    (1=≢ ∧ (∧/1∘∊¨)) solver m: m
    ∇⍵
  }