Skip to content

Instantly share code, notes, and snippets.

@0racle
Last active February 4, 2023 02:12
Show Gist options
  • Save 0racle/58dae7f21339554ec58365e21081d05e to your computer and use it in GitHub Desktop.
Save 0racle/58dae7f21339554ec58365e21081d05e to your computer and use it in GitHub Desktop.
Rehaping Reshape in J
0 1 2 3 0 1 2 3 0 1
==
1 0 3 2 1 0 3 2 1 0
==
MNOP
IJKL
EFGH
ABCD
==
PONM
LKJI
HGFE
DCBA
==
20 21 22 23
16 17 18 19
12 13 14 15
8 9 10 11
4 5 6 7
0 1 2 3
44 45 46 47
40 41 42 43
36 37 38 39
32 33 34 35
28 29 30 31
24 25 26 27
==
┌──────┬───────┐
│Brian │Adam │
├──────┼───────┤
│Morten│Michael│
└──────┴───────┘
==
5
⎕IO ← 0
'disp' ⎕CY 'dfns'
echo←{⎕←disp⍵}
v ← ⍸0>,
r ← |⍤⊣⍴⊢
f ← {⊖[⍺]⍵}
reshape ← {⊃⍺f⌿⍤(v⍤⊣,⊂⍤r)⍵}
echo 10 reshape ⍳4
echo '=='
echo ¯10 reshape ⍳4
echo '=='
echo ¯4 4 reshape ⎕A
echo '=='
echo ¯4 ¯4 reshape ⎕A
echo '=='
echo 2 ¯2 ¯3 4 reshape ⍳48
echo '=='
echo 2 ¯2 reshape 'Adam' 'Brian' 'Michael' 'Morten'
echo '=='
echo ⍬ reshape 5 3 1
V =: >:@I.@(0 > |.)
R =: ] $~ |@[
F =: {{ |."x y }}&.>/
NB. {{ > F (<"0 V x), < x R y }}
Reshape =: >@F@(<"0@V@[ , <@R)
echo 10 Reshape i. 4
echo '=='
echo _10 Reshape i. 4
echo '=='
echo _4 4 Reshape azuc =. u: 65 + i. 26
echo '=='
echo _4 _4 Reshape azuc
echo '=='
echo 2 _2 _3 4 Reshape i. 48
echo '=='
echo 2 _2 Reshape 'Adam' ; 'Brian' ; 'Michael' ; 'Morten'
echo '=='
echo (0$0) Reshape 5 3 1

On the J channel in The APL Farm Discord, Raul Miller and Bob Therriault helped make this less APL, more J through a few iteration.

NB. {{ (0 > x) {{ (i. (_1^x) * $ y) { , y }} x R y }}
Reshape =: (0 > [) (i.@((_1 ^ [) * $@]) { ,@]) R

NB. {{ (| x) $ (i. x) {&, y $~ |x }}
Reshape =: |@[ $ (i.@[ {&, ($~ |)~)

NB. {{ (i. x) { , (| x) $ y }}
Reshape =: i.@[ { ,@(|@[ $ ])
Reshape =: i.@[ { (,@$~ |)~

You can see the discussion start here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment