Search code examples
arrayslistjtacit-programminglist-manipulation

J: Number of sign changes between items of list


Items of a are _1 or 1.

a =: 1 _1 _1 1 _1

There are 3 sign changes in a:

1, -1, -1, 1, -1
  Λ       Λ  Λ
 here   and here

How do I count them looplessly?


Solution

  • You pair them with 2 v\, check if they differ ~:/ and sum +/:

    +/ 2 ~:/\ a
    3
    
    2 ~:/\ 1 1 1 _1 _1 _1 1 _1 1
    0 0 1 0 0 1 1 1
    
    +/2 ~:/\ 1 1 1 _1 _1 _1 1 _1 1
    4
    

    edit

    Or you could line up the curtail }: and behead }. of a and compare them but that is notably less efficient.

    +/(}: ~: }.) a