4

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?

Dan Oak
  • 704
  • 1
  • 7
  • 26

2 Answers2

5

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
Eelvex
  • 8,975
  • 26
  • 42
  • Could you explain why `+/@(}: ~: }.)` is less efficient than `+/@(2&(~:/\))`, please? – Dan Oak Nov 05 '14 at 16:02
  • 1
    Mostly because `2 f/\y` is supported by [special code](http://www.jsoftware.com/help/release/infix2a.htm). One other thing is that beheading is expensive (both in time and space). It takes more to just behead a large `a` than to count the number of sign changes with the first way. You can make a large random `a` (`a =: 1 _1 {~ ? 1e6 $ 2`) and test it using `timespacex`. – Eelvex Nov 05 '14 at 16:25
  • Thanks. Indeed, it is faster and cheaper. The fact that to code efficiently in J you need to remember all the SC is always putting me out, because it's like you say to J to do instruction `A` but J does `improved A` that is not what you expect. – Dan Oak Nov 06 '14 at 13:37
1

if the numbers can be other than 1 and _1,

  2 ~:&*/\ _2 4 3 _1 _3 1
1 0 1 0 1
pascalJ
  • 61
  • 1
  • 3