Count the changes in an array
MATL, 2 bytes
dz
Try it online! Or verify all test cases.
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!
Haskell, 33 bytes
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 abs
olute 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
.