J: Coordinates with a specific value

Say we have an array

0 1 2 3 4 5 8 7 8 9 

There are two indexes that have a value of 8:

 (i.10) ([#~8={) 0 1 2 3 4 5 8 7 8 9 6 8 

Is there a shorter way to get this result? There may be some built-in verb.

But more importantly. What about higher dimensions? Let them say that there is a 5x4 matrix

 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 

I want to know what are coordinates with a value of 6.
I want to get the result like this (there are three coordinates):

 4 1 3 2 2 3 

This is a fairly simple task, and I think there must be some simple solution.

The same thing in three dimensions?

thanks

+5
source share
2 answers

Verb indices I. almost complete the task.

When you have a simple list, I. used simply:

 I. 8 = 0 1 2 3 4 5 8 7 8 9 6 8 

For higher order matrices, you can associate it with antibase #: to get the coordinates in the $ matrix base. For instance:

 ]a =: 4 5 $ 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 I. 6 = ,a 9 13 17 ($a) #: 9 13 17 1 4 2 3 3 2 

Similarly, for any number of dimensions: flatten ( , ), compare ( = ), get the indices ( I. ) and transform the coordinates ( ($a)&#: :

 ]coords =: ($a) #: I. 5 = , a =: ? 5 6 7 $ 10 0 0 2 0 2 1 0 2 3 ... (<"1 coords) { a 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 

By the way, you can write I. x = y as x ( I.@ :=) y for extra performance. special code for

where xfy

+3
source

Using Sparse array parameters ( $. ) Provides a very quick and gentle solution that also works for multiple dimensions.

  ]a=: 5 ]\ 1 + i. 8 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 6 = a 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 4 $. $. 6 = a 1 4 2 3 3 2 

silently:

  getCoords=: 4 $. $. getCoords 6 = a ,: a 0 1 4 0 2 3 0 3 2 1 1 4 1 2 3 1 3 2 
+4
source

All Articles