J verb or phrase to group runs of identical elements

This is best illustrated by an example:

Input:

1 2 2 1 1 1 2 3 3

Conclusion:

    1; 2 2; 1 1 1; 2; 3 3

β”Œβ”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”
β”‚1β”‚2 2 β”‚1 1 1β”‚2β”‚3 3β”‚
β””β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”΄β”€β”€β”€β”˜

So I'm looking for something like Key /., but Key will group everything together, all two together, and so on. I want to group only adjacent runs together.

One final thought: the key can be used successfully if I can first create one xfor it that looks like this:

0 1 1 2 2 2 3 4 4   NB. x suitable for use in Key
1 2 2 1 1 1 2 3 3   NB. original data

I can’t think of a tacit solution to generate such an x, though (my ideas include a mutating temporary variable to hold the current β€œlabel”, that is, numbers from 0 to 4 in xas defined above)

+4
source share
1 answer

An alternative to Key /.in this case is binary Cut ;. :

Build xas:

   (1 ,~ 2 ~:/\ ]) 1 2 2 1 1 1 2 3 3
1 0 1 0 0 1 1 0 1

They mark the end of the groups. Then use dyadic ones <;.2to place these groups:

   ((1 ,~ 2 ~:/\ ]) <;.2 ]) 1 2 2 1 1 1 2 3 3
β”Œβ”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”
β”‚1β”‚2 2β”‚1 1 1β”‚2β”‚3 3β”‚
β””β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”΄β”€β”€β”€β”˜

This may be abbreviated:

   (<;.2~ 1 ,~ 2&(~:/\)) 1 2 2 1 1 1 2 3 3
β”Œβ”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”
β”‚1β”‚2 2β”‚1 1 1β”‚2β”‚3 3β”‚
β””β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”΄β”€β”€β”€β”˜
+4
source

Source: https://habr.com/ru/post/1682332/


All Articles