Adám's idea of using ⌹ to find the average is really cool. See their explanation in the comments. R
is the result of X⌹Y
, and it's chosen to minimize the square of the difference between X
and the matrix product of R
and Y
. In this case, since Y
is a vector of all 1s, the average of X
minimizes that squared difference.
Explanation:
{
1≥|⊃⍵-(+/÷≢)⍵: 0 ⍝ Base case: If it's the last iteration, return 0
⍵⌹=⍨⍵ ⍝ Average of ⍵ (the array) (not sure why that works)
=⍨⍵ ⍝ Compare ⍵ to itself to create an array of 1s the same size as ⍵
⍵⌹ ⍝ ⍵ divided by that (matrix division)
⍵- ⍝ Subtract that from all elements of ⍵
⊃ ⍝ Take only the first of those differences
| ⍝ Absolute value
1≥ ⍝ Is it less than or equal to 1?
⋄1+∇h,3÷⍨3+/⍵,h←⊃⍵
h←⊃⍵ ⍝ Assign the first element of ⍵ to h
⍵, ⍝ Append to ⍵ (because of wrapping)
3+/ ⍝ Take groups of 3 adjacent elements and sum each
3÷⍨ ⍝ Divide each sum by 3 (to get average)
h, ⍝ Prepend h, which stays constant
∇ ⍝ Call on this new iteration
1+ ⍝ Add 1 to that
}