JPhrases/Grading

From J Wiki
Jump to: navigation, search

6C. Grading

Grading is the assignment of an ordinal number to each item of an array, with all numbers distinct, and with the earliest of equal values being assigned a lower ordinal number. Grading can be used to produce the permutation that will put an array in order. Since sorting is a primitive operation in J, grading is more commonly used to put a companion array into an order derived from another array. For example, a table of addresses may be put into an order derived from a table of last names.

m0=: /: Grade y up
m1=: \: Grade y down
d2=: /:@i. Grade y up according to key x
d3=: \:@i. Grade y down according to key x
   y=:'leap','note',:'file'
   (] ; m0 ; (m0 { ]) ; m1 ; (m1 { ])) y
+----+-----+----+-----+----+
|leap|2 0 1|file|1 0 2|note|
|note|     |leap|     |leap|
|file|     |note|     |file|
+----+-----+----+-----+----+

   x=: ' abcdefghijklmnopqrstuvwxyz' [ y=: 'senator'
   x (d2 ; (d2{]) ; d3 ; (d3{])) y
+-------------+-------+-------------+-------+
|3 1 2 5 6 0 4|aenorst|4 0 6 5 2 1 3|tsronea|
+-------------+-------+-------------+-------+