Puzzles/APL Idioms1

From J Wiki
Jump to navigation Jump to search

The APL Idioms column in Vector 21.4 poses 10 puzzles. Some of them are also interesting J puzzles.

A few of the solutions use features available only in J 6.01.


How many elements does a given variable have?

Restriction: assume that the , verb is not available.

ce0=: */@$
ce1=: +/^:_ @ (=~)

ce2=: ($:@:]`1:@.-: {.) * #
ce3=: (7: $. $.)@:=~

Is a value within a given range?

Restriction: assume that the relational verbs < <: = ~: >: > are not available.

ir0=: _1: >. (+&:*)/ @: (-/)

Sort a numeric array of integers in ascending order of the number of digits

Restriction: assume ": or !: are not available.

sn=: /: 10 <.@:^. |

Return the element(s) of a numeric array indexed by its first dimension

Restriction: assume that $ and # are not available.

ld0=: {:
ld1=: _1&{

ld2=: {.@:(_1&{.)
ld3=: {.@:|.

ld5=: {.;.0
ld6=: {.@:({.;.1~ 1: _1} 0"_1)

Return the sum of element(s) of a numeric array on its first dimension

Restriction: assume that + is not available.

ls=: 1 #.&.|: ]


ls2=: */&.:^   NB. -- [[User:Oleg Kobchenko|Oleg Kobchenko]] [[DateTime(2005-12-09T08:33:17Z)]]

Convert the string representation of integers to numbers

Restriction: assume that ". is not available.

cn=: 10 #. '0123456789' i. ]

Return a numeric array as zeros, increasing the last dimension by 1

Restriction: assume that * {. - , are not available, nor is $ with a right argument of 0.

zm0=: 1: ^.~  (i.@:(}: , >:@:{:)))@:$
zm1=: 1: ^.~  i.@:(+ (<: = i.)@:#)@:$
zm2=: [: -. 0 -:~\"1 ]

Return the first ones from a Boolean vector

Restriction: assume that -. and |. are not available.

fo0 =: *. ~:/\^:_1
fo1 =: 2 </\ 0 , ]
fo2 =: 1 = 2 #.\ 0 , ]
fo3 =:  (1:`{.@I.`( *. 0:))@]}~ NB. only valid if there is a first 1

Return the last ones from a Boolean vector

Restriction: assume that -. and |. are not available.

lo0 =: *. ~:/\.^:_1
lo1 =: 1 0 &E.
lo2 =: 1 = ([ * +)/\.
lo3 =:  (1:`{:@I.`( *. 0:))@]}~  NB. only valid if there is a last 1

Return the elements of a numeric array found at given coordinates

Restriction: assume that looping is not permitted.

re0=: ({~ <: L: 0 @:( <"1 ^: (L. = 0:)))~    NB.  <: is because APL page says []IO <- 1
re1=: ($@[ #. <:@]) { ,@[   NB. index origin 1
re2=: ($@[ #. ]) { ,@[      NB. index origin 0