On Tue, May 17, 2011 at 11:08 PM, Ian Clark <[email protected]> wrote:
> I have an array like this (which may be unsorted, and can grow very large):
>
> 1       100
> 1       100
> 1       20
> 1       400
> 2       30
> 2       200
> 2       300
> 33      100
> 33      100
> 33      100
>
> I want to collapse it to:
>
> 1       620
> 2       530
> 33      300

On Tue, May 17, 2011 at 11:14 PM, Marshall Lochbaum
<[email protected]> wrote:
> The standard solution would be to use key (/.):
> +//./ |: arr

That, however, does not give the answer Ian asked for.  It only gives
the sums.  How would you get a matrix of both the sum and the keys?

Here are some solutions, but there probably is something more elegant.

   arr =: _2]\ 1 100 1 100 1 20 1 400 2 30 2 200 2 300 33 100 33 100 33 100
   (~.@[,.+//.)/ |: arr
 1 620
 2 530
33 300
   ({."1({.@{.,[:+/{:"1)/.]) arr
 1 620
 2 530
33 300

--
Ambrus
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to