Search code examples
j

Amend with multiple indices per substitution in J


In J, how do you idiomatically amend an array when you have:

substitution0    multipleIndices0
...
substitutionN    multipleIndicesN

(not to be confused with:

substitution0    multipartIndex0
...
substitutionN    multipartIndexN

)

For example, my attempt at the classic fizzbuzz problem looks like this:

   i=.3 :'<@I.(,*./)(=<.)3 5%~"(0 1)y'
   d=.1+i.20
   'fizz';'buzz';'fizzbuzz' (i d)};/d
|length error
|   'fizz';'buzz';'fizzbuzz'    (i d)};/d

I have created the verb m} where m is i d which is 3 boxes containing different-sized lists of 1-dimensional indices, whereas I think } expects m to be boxes containing single lists that each represent a single index with dimensions at least as few as the rank of the right argument.

How is this generally solved?


Solution

  • 'fizz';'buzz';'fizzbuzz' (i d)};/d
    

    This has a few problems:

    1. the x param of } is 'fizzbuzz', not a list of boxes, as the } happens before the ;s on the left. You mean
    ('fizz';'buzz';'fizzbuzz') (i d)};/d
    
    1. the boxed numbers in the m param of } are not interpreted as you expect:
       _ _ (1 1;2 2) } i.3 3
    0 1 2
    3 _ 5
    6 7 _
       _ _ (1 1;2 2) } ,i.3 3  NB. your length error
    |length error
    |   _ _    (1 1;2 2)},i.3 3
    
    
    1. If you raze the m param you get the right kind of indices, but still don't have enough members in the x list to go around:
       _ _ (;1 3;5 7) } i.9
    |length error
    |   _ _    (;1 3;5 7)}i.9
       _ _ _ _ (;1 3;5 7) } i.9
    0 _ 2 _ 4 _ 6 _ 8
    

    These work:

       NB. raze m and extend x (fixed)
       i=.3 :'<@I.(,*./)(=<.)3 5%~"(0 1)y'
       d=.1+i.20
       ((;# each i d)#'fizz';'buzz';'fizzbuzz') (;i d)};/d
    +-+-+----+-+----+----+-+-+--------+----+--+----+--+--+----+--+--+--------+--+----+
    |1|2|fizz|4|fizz|buzz|7|8|fizzbuzz|buzz|11|fizz|13|14|buzz|16|17|fizzbuzz|19|fizz|
    +-+-+----+-+----+----+-+-+--------+----+--+----+--+--+----+--+--+--------+--+----+
    
    
       NB. repeatedly mutate d
       i=.3 :'<@I.(,*./)(=<.)3 5%~"(0 1)y'
       d=.;/1+i.20
       ('fizz';'buzz';'fizzbuzz'),.(i ;d)
    +--------+--------------+
    |fizz    |2 5 8 11 14 17|
    +--------+--------------+
    |buzz    |4 9 14 19     |
    +--------+--------------+
    |fizzbuzz|14            |
    +--------+--------------+
       0$(3 : 'd =: ({.y) (1{::y) }d')"1 ('fizz';'buzz';'fizzbuzz'),.(i ;d)
       d
    +-+-+----+-+----+----+-+-+----+----+--+----+--+--+--------+--+--+----+--+----+
    |1|2|fizz|4|buzz|fizz|7|8|fizz|buzz|11|fizz|13|14|fizzbuzz|16|17|fizz|19|buzz|
    +-+-+----+-+----+----+-+-+----+----+--+----+--+--+--------+--+--+----+--+----+