# Count the changes in an array

Your task today is to write a program or function that takes an array of integers, and counts the number of times, reading it left to right, that the value changes. This is easier to show with an example: [1 1 1 2 2 5 5 5 5 17 3] => [1 1 1 **2** 2 **5** 5 5 5 **17** **3**] => 4

Test case:

Input           |   Output
[]              |   0
[0]             |   0
[0 1]           |   1
[0 0]           |   0
[1 2 3 17]      |   3
[1 1 1 2 2 3]   |   2
[-3 3 3 -3 0]   |   3


This is , fewest bytes wins!

• Is my answer valid if the result is always correctly calculated, but if it's 0, False is printed instead? Commented Oct 27, 2017 at 15:54
• @FlipTack That depends on the language. In general, if I can say 2+False and it errors, that's not fine, but if I get 2, that's fine. Commented Oct 27, 2017 at 18:21
• @FlipTack By default, this is the consensus. Commented Oct 28, 2017 at 13:33
• Is empty output for 0 acceptable? Commented Nov 2, 2017 at 21:06
• @Titus yes it is. Commented Nov 2, 2017 at 22:21

# MATL, 2 bytes

dz


### Explanation

     % Implicit input
d    % Consecutive differences
z    % Number of nonzeros
% Implicit display


# Python 3, 38 bytes

f=lambda x=0,*y:y>()and(x!=y[0])+f(*y)


Try it online!

• Huh, did know know you could use a default arg like that, nice find.
– xnor
Commented Oct 26, 2017 at 20:45
• Easier test case format Commented Oct 27, 2017 at 9:44
• @Dennis How does the function exit the recursive loop when the array is empty? I don't see how this doesn't end in a maximum recursion depth exceeded. Commented Oct 27, 2017 at 17:40
• @Ioannes Once there's only one element (x) left, y>() will evaluate to False, so the code following and doesn't get executed. Commented Oct 27, 2017 at 17:47

f(a:b:r)=sum[1|a/=b]+f(b:r)
f _=0


Try it online!

Bonus: Somewhat curious point-free arithmetic version (44 bytes)

sum.(tail>>=zipWith((((0^).(0^).abs).).(-)))


Try it online!

Given an input [1,1,4,3,3,3], we first take the difference of adjacent entries ([0,3,-1,0,0]), then the absolute value: [0,3,1,0,0]. Taking zero to the power of each element the first time yields [1,0,0,1,1], and a second time inverts the list: [0,1,1,0,0] ((1-) would also work here instead of (0^)). Finally we take the sum of the list to get 2.

# Python 2, 42 bytes

lambda a:sum(x!=y for x,y in zip(a,a[1:]))


Try it online!

# K (oK), 8 bytes

Solution:

+/1_~~':


Try it online!

Examples:

+/1_~~':1 1 1 2 2 5 5 5 5 17 3
4
+/1_~~':()
0
+/1_~~':-3 3 3 -3 0
3


Explanation:

Interpreted right-to-left:

+/1_~~': / the solution
~': / equal each-previous
~    / not (ie differ)
1_     / 1 drop, remove first as this is different to null
+/       / sum up trues


# Brain-Flak, 50 bytes

([][()]){{}({}[({})]){{}<>({}())(<>)}{}([][()])}<>


Try it online!

Outputs nothing for 0, which in brain-flak is equivalent. If this is not acceptable, than append this for +4 bytes: ({})

Explanation:

#Push stack-height-1
([][()])

#While true:
{

#Pop the stack-height-1 off
{}

#If 'a' is the element on top of the stack, and 'b' is the element underneath it, then
#Pop 'a' off, and push (a - b)
({}[({})])

#If (a-b) is not 0...
{
#Pop (a-b) off
{}

#Switch stacks
<>

#Increment the value on the other stack
({}())

#Push a 0 back to the main stack
(<>)

#Endif
}

#Pop either (a-b) or the 0 we pushed
{}

#Push stack-height-1
([][()])

#Endwhile
}

#Toggle to the alternate stack and display the counter
<>

• Different approach, same length Commented Oct 26, 2017 at 19:54
• @Riley Nicely done! :) Commented Oct 26, 2017 at 19:55
• Slight improvement for 48 bytes Commented Oct 27, 2017 at 2:57
• @WheatWizard I tried that also, but it loops forever on empty input. -0+1 = 1 Commented Oct 27, 2017 at 16:25

# Brain-Flak, 50 bytes

(([][()]){[{}]<({}[({})])>{(<{}>)()}{}([][()])}<>)


Try it online!

# Get ready to push the answer
(

# Push stack height - 1
([][()])

# Loop until 0 (until the stack has a height of 1)
{

# Pop the old stack height and subtract it
#(cancels the loop counter from the final answer)
[{}]

# Pop the top of the stack and subtract the next element from that
# Don't include this in the final answer
<({}[({})])>

# If not 0
{

# Pop the difference between the last two numbers
# Don't include this in the final answer
(<{}>)

()

# End if
}{}

# Push stack height - 1
([][()])

# End while
}

# Switch to the off stack so we don't print anything extra
<>

# Push the total sum. This is the number of times the if was true
)

• Congrats for 10k rep! Commented Oct 26, 2017 at 19:59
• @Pavel Thanks! It took me forever to get the last few hundred. I've been too busy with other stuff :( Commented Oct 26, 2017 at 20:00
• I had this Commented Oct 26, 2017 at 20:02
• @H.PWiz I had that at one point, but I like how the pop cancels the stack height push. Commented Oct 26, 2017 at 20:04

-8 bytes thanks to H.PWiz.

Out-golfed by a recursive version. Haskell is pretty much the best at recursion and I missed it. >_<

f l=sum[1|x<-zipWith(/=)l$tail l,x]  Try it online! It'd be awesome if anybody figured out how to employ this tip. ## Alternate solution, 36 bytes f l=sum[1|True<-zipWith(/=)l$tail l]


Try it online!

• Also 35 Commented Oct 26, 2017 at 19:41
• That tip misses the crucial fact that you'd need to uncurry the function f to get it to work. This sum.map fromEnum.(zipWith(/=)=<<tail) is probably the closest you get, but it won't work with [] and is 37 bytes.. Commented Oct 27, 2017 at 16:53

# Java (OpenJDK 8), 65 bytes

Not as short as I'd like, but that's just Java for you.

Test by passing the array as a comma delimited list.

a->{int s=0,i=1;for(;i<a.length;s+=a[i-1]!=a[i++]?1:0);return s;}


Try it online!

• If the empty array wasn't a test case (and I don't find it really relevant, actually), one could have used: a->{int s=0,p=a[0];for(int n:a)s+=p==(p=n)?0:1;return s;} (57 bytes). Commented Oct 27, 2017 at 9:43
• @OlivierGrégoire I know! I wrote that out and thought I'd managed to cut down the bytes but it failed on that first case. Commented Oct 27, 2017 at 10:01
• 56 bytes: a->{int s=0;for(int i:a)s+=a[0]!=(a[0]=i)?1:0;return s;} Commented Oct 27, 2017 at 13:08

# Jelly, 3 bytes

ITL


Try it online!

## How it works

ITL  - Full program.

I    - Increments (deltas).
T   - Get the indices of truthy values (gets the indexes of non-0 elements).
L  - Length.


# Husk, 3 bytes

Ltg


Try it online!

### Explanation

Ltg    Input: [1,1,1,2,2,3]
g    Group equal elements together: [[1,1,1],[2,2],[3]]
t     Drop the first group (if any): [[2,2],[3]]
L      Return the length of the list: 2


# Ohm v2, 3 bytes

ΔyΣ


Try it online!

Explanation

Δ     absolute differences between consecutive elements
y    sign: 1 if positive, -1 if negative, 0 if zero
Σ   sum

• Clever usage of the sign builtin! Commented Oct 27, 2017 at 2:41
• @NickClifford Thanks! Commented Oct 27, 2017 at 7:27

# Wolfram Language (Mathematica), 23 242629 bytes

Length@Split@#~Max~1-1&


Try it online!

• -1 byte thanks to Martin Ender!
• -2 bytes thanks to JungHwan Min! nice use of Split[].
• -3 bytes thanks to totallyhuman!

a little explanation:

Split will divide an array into a list of lists (of same elements), that is, turning {1, 2, 2, 3, 1, 1} into {{1}, {2, 2}, {3}, {1, 1}} . So, Length@Split@# is the quantity of consecutive segements. Max[*****-1, 0] is used to deal with {} input.

• 26 bytes. Commented Oct 26, 2017 at 19:56
• 24 bytes: Max[Length@Split@#-1,0]& Commented Oct 26, 2017 at 20:03
• 23: Length@Split@#~Max~1-1& Commented Oct 27, 2017 at 7:22

# Retina, 2421 16 bytes

Thanks to @MartinEnder for -3 bytes and noticing a bug
-1 byte thanks to @tsh
-4 bytes thanks to @Leo

m^(\S+)¶(?!\1$)  Try it online! # Perl 6, 18 bytes {sum$_ Z!= .skip}


Test it

## Expanded:

{ # bare block lambda with implicit parameter ｢$_｣ sum # count the number of True values$_      # the input
Z!=       # zip using &infix:«!=»
.skip   # the input, but starting from the second value
• @NealFultz it's probably still worth posting as an answer! Always good to see another approach. And you should use sum(rle()$v|1) instead of length anyway. :) Commented Oct 29, 2017 at 16:48 # Cubix, 24 bytes UpO@0I>I!^-u>q.uvv$!^;)p


Try it online

Note that Cubix uses 0 to indicate that there are no more inputs, so 0 cannot be in the list.

### Explanation

Unfolded:

    U p
O @
0 I > I ! ^ - u
> q . u v v $! ^ ; ) p  We start at the 0, pushing the counter (initialized with 0) and the first input (I) onto the stack. We then enter the loop. At each iteration of the loop, we get the next input with I. If it's 0, we've run out of inputs, so we rotate the counter to the top (p), Output, and exit (@). Otherwise, we take the difference of the top two elements. If it's nonzero, we rotate the counter to the top, increment it, and rotate it back to the bottom with p)q. We then pop the difference with ; before moving to the next iteration. All the characters not mentioned here are just control flow. There tend to be a lot of those in Cubix programs. • @MickyT Good approach, but you seem to be overcounting by 1. You could swap the 0 for a (, but that fails on the empty input. – user48543 Commented Oct 30, 2017 at 2:02 • apologies, will look at it again Commented Oct 30, 2017 at 2:10 # APL (Dyalog), 8 bytes +/2≠/⊃,⊢  Try it online! How? ⊃,⊢ - the list, with the first value repeated for the case of single element 2≠/ - changes list, not equal for every 2 elements +/ - sum # Brain-Flak, 50 bytes (([][()]){[{}({}[({})])]{{}()(<()>)}{}([][()])}<>)  Try it online! Since everyone is posting their 50 byte solutions here is mine (I have a 48 byte one but it was a simple modification of DjMcMayhem's so I did feel it worth posting) # Explanation This answer extensively uses value canceling. Un-golfed it looks like ([][()])({<{}({}[({})])>{<{}>()(<()>)}{}<([][()])>}<>)  Here we compute the delta's until the stack has one item left, each time we accumulate one value from the inner loop if the delta is non zero. This is a pretty straight forward way of doing it. To make this golfy we begin value canceling. The first one and the one that should be obvious to any hardened brain-flak golfer is the stack heights. It is a well known fact that ([])({<{}>...<([])>}{})  is the same as (([]){[{}]...([])}{})  When the values are modified by one, the same holds. This gives us (([][()]){[{}]<({}[({})])>{<{}>()(<()>)}{}([][()])}<>)  You may notice this didn't even save us bytes, but don't fret it will become more useful as we go on. We can perform another reduction, if you see a statement <(...)>{<{}> ...  you can actually reduce it to [(...)]{{} ...  This works because if we enter the loop [(...)] and {} will cancel, and if we don't the value of [(...)] already was zero in the first place and doesn't need to be canceled. Since we have an occurrence of this pattern in our code we can reduce it. (([][()]){[{}][({}[({})])]{{}()(<()>)}{}([][()])}<>)  That saved us 2 bytes but it also put two negs next to each other. These can be combined to save us another 2. (([][()]){[{}({}[({})])]{{}()(<()>)}{}([][()])}<>)  And that's our code. # Gaia, 2 bytes ėl  Try it online! This abuses a bug (or feature?) of Gaia, that run-length-encoding doesn't take the last run of elements into account. Note that I have double checked, it works for all test cases. • ė - Run length encoding (with the flaw described above). • l - Length. # PowerShell, 52 45 bytes (-7 bytes thanks to Julian) $i=0
$args|%{$i+=$p-ne$_-and$p-ne$n
$p=$_}
$i  Try it online! Takes input $args, dumps it into a for loop, each iteration checking whether the $previous value is -notequal to the current value $_, and whether the previous value is $null. Exploits the Boolean-to-int implicit converstion to accumulate that into $i. Outputs $i at the end. The initial $i=0 is needed to account for if the input is empty, and to (properly) account for when the input is a single value.

• 5 years late :) 45 bytes Commented Oct 10, 2022 at 2:49
• Where's the $n come into existence? @Julian Commented Oct 16, 2022 at 21:28 • Oh.$null. Derp. Commented Oct 16, 2022 at 21:29
• yep, it is not very aesthetic, but I can't think of any cleaner approach Commented Oct 17, 2022 at 0:17

## JavaScript (ES6), 35 bytes

a=>a.filter((e,i)=>e-a[i+1]).length

• I wonder if it could be shortened by using recursion. But my best attempt is 35 as well: f=([a,...b])=>1/a?!!(a-b[0])+f(b):0 Commented Oct 26, 2017 at 20:58
• @Arnauld I'd tried that too, but miscounted and thought it was 36 bytes, otherwise I'd have added it in as an alternative.
– Neil
Commented Oct 27, 2017 at 0:44

# Pyth, 5 bytes

l #.+


Test suite.

Explanation:

   .+  Deltas
#    Filter on identity (space)
l      Get length


# Perl 5, 37 + 2 (-ap) = 39 bytes

$\+=$F[$_]!=$F[$_-1]for 1..$#F}{\$\|=0


Try it online!

• 34 bytes, based on your answer: Try it online!. 31 bytes, using regex instead: Try it online!
Commented Oct 27, 2017 at 15:25

# J, 10 bytes

[:+/2~:/\]


Infixes of length 2... are they unequal? 2 ~:/\ ]

Sum the resulting list of 0s and 1s: +/

Try it online!

• [:+/0=-/\  ought to work for I think 9 bytes.
– cole
Commented Oct 30, 2017 at 19:02

# Pyth, 4 bytes

ltr8


Test suite

"literate"

The number of changes is equal to the number of runs, ignoring the first run if any. r8 run length encodes the input, t removes the first element if any, and l` finds the length of the resulting list.