Search code examples
j

Open boxes with a custom padding value in J


Unboxing or opening boxes with different sizes causes padding with 0 for numerals and a space with literals:

v=.1 4 8 ; 2 6 4 ; 6 8 4 5; 7 8 9; 6 3 7 4 9

>v
1 4 8 0 0
2 6 4 0 0
6 8 4 5 0
7 8 9 0 0
6 3 7 4 9

The fit (!.) conjunction is usually the thing to use for these things, but

>!. _1 v

Is not supported and throws a domain error.

I've got this, but with very large arrays it's not very fast:

(>./ # every y) {.!. _1 every y

Is there an efficient way to define the padding value for opening boxes?


Solution

  • Setting

    f =: 3 :'(>./ # every y) {.!. _1 every y'
    g =: _1&paddedOpen
    

    and (in the same spirit as your f):

    h =: 3 : '((>./# &> y)&($!._1))@> y'
    

    I get the following performances for time and space:

    (100&(6!:2) ,: 7!:2) &.> 'f L';'g L';'h L'
    ┌─────────┬─────────┬─────────┐
    │ 0.045602│0.0832403│0.0388146│
    │4.72538e6│1.76356e7│4.72538e6│
    └─────────┴─────────┴─────────┘
    

    where L is a large array:

    L =. (<@(+i.)/)"1 ? 50000 2 $ 10
    

    You can slightly improve f by making it terse; for example:

    f =: ] {.!._1&>~ >./@:(#&>)
    

    I don't think that there is much room for more improvements.