# 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? 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. Oct 27, 2017 at 18:21
• @FlipTack By default, this is the consensus. Oct 28, 2017 at 13:33
• Is empty output for 0 acceptable? Nov 2, 2017 at 21:06
• @Titus yes it is. 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
Oct 26, 2017 at 20:45
• Easier test case format 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. 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. 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!

# 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 Oct 26, 2017 at 19:54
• @Riley Nicely done! :) Oct 26, 2017 at 19:55
• Slight improvement for 48 bytes Oct 27, 2017 at 2:57
• @WheatWizard I tried that also, but it loops forever on empty input. -0+1 = 1 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! 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 :( Oct 26, 2017 at 20:00
• I had this 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. 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 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.. 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). 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. 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;} Oct 27, 2017 at 13:08

# 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! Oct 27, 2017 at 2:41
• @NickClifford Thanks! 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. Oct 26, 2017 at 19:56
• 24 bytes: Max[Length@Split@#-1,0]& Oct 26, 2017 at 20:03
• 23: Length@Split@#~Max~1-1& 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

• @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. :) 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 Oct 30, 2017 at 2:02 • apologies, will look at it again Oct 30, 2017 at 2:10 # 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. # 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
# (implicit method call on ｢$_｣ }  # 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. ## 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 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 Oct 27, 2017 at 0:44 # Pyth, 5 bytes l #.+  Test suite. Explanation:  .+ Deltas # Filter on identity (space) l Get length  # 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 # Perl 5, 37 + 2 (-ap) = 39 bytes $\+=$F[$_]!=$F[$_-1]for 1..$#F}{$\|=0


Try it online!

# 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
Oct 30, 2017 at 19:02

# Ruby, 31 bytes

->a{a.chunk{|x|x}.drop(1).size}


Try it online!

• Instead of .drop(1) you can do [1..-1] Oct 27, 2017 at 16:03
• @Cyoce Unfortunately drop returns an Enumerator, not an Array, so that doesn't work. Oct 27, 2017 at 16:04
• huh. It returns an Array on my version. Oct 27, 2017 at 16:06
• @Cyoce Which version? Oct 27, 2017 at 16:08
• I'm on 1.9.3 but why can't you take the size of an Array anyway? Oct 27, 2017 at 16:09

# C (gcc 5.4.0), 61 bytes

f(c,v)int*v;{int*p=v,s=0;for(;p<v+c-1;s+=*p++!=*p);return s;}


Try it Online!

f is a function taking the length of the array and a pointer to the first element of the array, and returning the number of changes in the array;

This submission utilizes undefined behavior (*p++!=*p, p is used twice in an expression in which it is changed), which works on my machine (gcc 5.4.0) and on TIO, but may not work on other implementations or versions.

Explanation:

f(c,v)int*v;{ // old-style declaration for v, and implicit-int for c and return value
int*p=v,s=0; // p is a pointer to the current item, s is the number of changes
for(;p<v+c-1;s+=*p++!=*p); // for each consecutive pair of integers, if they are different, add one to the number of changes
return s; // return the number of changes
}

• Could you maybe add a link to an online testing environment? Oct 29, 2017 at 15:25
• @JonathanFrech Added Oct 29, 2017 at 18:11

# 05AB1E, 3 bytes

γ¦g


Try it online!

γ¦g  ~ Full program.
`