Created
August 6, 2020 16:02
-
-
Save rodrigogiraoserrao/99bbab8cd5728858608fd20502d59aba to your computer and use it in GitHub Desktop.
RGS's solution for Problem 8, Phase 2 of 2020 APL competition (see https://mathspp.com/blog/2020-apl-competition for my thoughts on it)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
⍝ PROBLEM 8.1 | |
Balance ← { | |
(⎕IO ⎕ML ⎕WX) ← 0 1 3 | |
⍝ Given an integer vector ⍵, find a 2-partition with equal sums. | |
⍝ Monadic function expecting an integer vector. | |
⍝ This algorithm is O(2*≢⍵); we compute possible partitions of ⍵ and check | |
⍝ if their sums satisfy the requirement. | |
⍝ Return a 2-element vector of integer vectors. | |
S ← 1⊥⍵ ⍝ Check simple necessary properties: | |
2|S: ⍬ ⍝ odd sum can't be evenly split | |
(∧/0≤⍵)∧S<2×⌈/⍵: ⍬ ⍝ all integers are ≥0 and largest element is too big | |
s ← S÷2 | |
⍝ compute all relevant possible partitions of ⍵; we can arbitrarily fix the partition in which the 1st elem. of ⍵ appears | |
mask ← 1 ⍪ 2∘⊥⍣¯1 ⍳2*¯1+≢⍵ | |
ss ← 1⊥ mask× (⍪⍵)/⍨ 1⊃⍴ mask | |
ps ← ⍉mask /⍨ s = ss | |
0=⊃⍴ps: ⍬ ⍝ return ⍬ if there is no solution. | |
p ← ⊃↓ps | |
(⊂p/⍵),(⊂⍵/⍨~p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment