20
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Is my answer valid if the result is always correctly calculated, but if it's 0, False is printed instead? \$\endgroup\$ – FlipTack Oct 27 '17 at 15:54
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Pavel Oct 27 '17 at 18:21
  • \$\begingroup\$ @FlipTack By default, this is the consensus. \$\endgroup\$ – totallyhuman Oct 28 '17 at 13:33
  • \$\begingroup\$ Is empty output for 0 acceptable? \$\endgroup\$ – Titus Nov 2 '17 at 21:06
  • \$\begingroup\$ @Titus yes it is. \$\endgroup\$ – Pavel Nov 2 '17 at 22:21

49 Answers 49

18
\$\begingroup\$

MATL, 2 bytes

dz

Try it online! Or verify all test cases.

Explanation

     % Implicit input
d    % Consecutive differences
z    % Number of nonzeros
     % Implicit display
\$\endgroup\$
9
\$\begingroup\$

Python 3, 38 bytes

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

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ Huh, did know know you could use a default arg like that, nice find. \$\endgroup\$ – xnor Oct 26 '17 at 20:45
  • \$\begingroup\$ Easier test case format \$\endgroup\$ – Erik the Outgolfer Oct 27 '17 at 9:44
  • \$\begingroup\$ @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. \$\endgroup\$ – Ioannes Oct 27 '17 at 17:40
  • \$\begingroup\$ @Ioannes Once there's only one element (x) left, y>() will evaluate to False, so the code following and doesn't get executed. \$\endgroup\$ – Dennis Oct 27 '17 at 17:47
7
\$\begingroup\$

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 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.

\$\endgroup\$
6
\$\begingroup\$

Python 2, 42 bytes

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

Try it online!

\$\endgroup\$
5
\$\begingroup\$

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
<>
\$\endgroup\$
5
\$\begingroup\$

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
    (<{}>)

    # Add 1 to 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
)
\$\endgroup\$
  • 1
    \$\begingroup\$ Congrats for 10k rep! \$\endgroup\$ – Pavel Oct 26 '17 at 19:59
  • \$\begingroup\$ @Pavel Thanks! It took me forever to get the last few hundred. I've been too busy with other stuff :( \$\endgroup\$ – Riley Oct 26 '17 at 20:00
  • \$\begingroup\$ I had this \$\endgroup\$ – H.PWiz Oct 26 '17 at 20:02
  • \$\begingroup\$ @H.PWiz I had that at one point, but I like how the pop cancels the stack height push. \$\endgroup\$ – Riley Oct 26 '17 at 20:04
5
\$\begingroup\$

Haskell, 35 bytes

-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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Also 35 \$\endgroup\$ – H.PWiz Oct 26 '17 at 19:41
  • \$\begingroup\$ 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.. \$\endgroup\$ – ბიმო Oct 27 '17 at 16:53
5
\$\begingroup\$

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!

\$\endgroup\$
  • 2
    \$\begingroup\$ 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). \$\endgroup\$ – Olivier Grégoire Oct 27 '17 at 9:43
  • \$\begingroup\$ @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. \$\endgroup\$ – Luke Stevens Oct 27 '17 at 10:01
  • 3
    \$\begingroup\$ 56 bytes: a->{int s=0;for(int i:a)s+=a[0]!=(a[0]=i)?1:0;return s;} \$\endgroup\$ – Nevay Oct 27 '17 at 13:08
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Clever usage of the sign builtin! \$\endgroup\$ – Nick Clifford Oct 27 '17 at 2:41
  • \$\begingroup\$ @NickClifford Thanks! \$\endgroup\$ – Cinaski Oct 27 '17 at 7:27
4
\$\begingroup\$

Wolfram Language (Mathematica), 23 24 26 29 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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 26 bytes. \$\endgroup\$ – totallyhuman Oct 26 '17 at 19:56
  • 1
    \$\begingroup\$ 24 bytes: Max[Length@Split@#-1,0]& \$\endgroup\$ – JungHwan Min Oct 26 '17 at 20:03
  • \$\begingroup\$ 23: Length@Split@#~Max~1-1& \$\endgroup\$ – Martin Ender Oct 27 '17 at 7:22
4
\$\begingroup\$

Retina, 24 21 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!

\$\endgroup\$
4
\$\begingroup\$

Symbolic Python, 120 117 bytes

Golfed 3 bytes by removing an explicit cast to integer (using unary +) for the counter variable - this means that if there are no changes in the array the output will be False instead of 0, but this is allowed by meta.

___=-~(_==_)
__('___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)')
__('__=___=_>_'+';___+=_[__]!=_[-~__];__=-~__'*___)
_=___

Try it online!

# LINE 1: Generate value '2' for utility
___=-~(_==_)

# LINE 2: Get len(input) - 1
__('___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)')
   '___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)'     # Generate string '___=~-len(_)'
            `_>_`[___::___]                       #    'le' spliced from 'False'
                           +`__`[-~___]           #    'n' indexed from '<function ...>'
   '___=~-'+                           +'(_)'     #    Remaining characters in plaintext
__(                                          )    # Execute this to get len(input) - 1

# LINE 3: Main calculation loop
__('__=___=_>_'+';___+=_[__]!=_[-~__];__=-~__'*___) 
__(                                               ) # Execute:
   '__=___=_>_'                                     #   Set var1, var2 to 0
               +';                           '*___  #   len(input) - 1 times do:
                       _[__]!=_[-~__]               #   Compare input[var1, var1 + 1]
                  ___+=              ;              #   Add this to var2
                                      __=-~__       #   Increment var1

# LINE 4: Set output variable ('_') to the result calculated.
_=___                                       
\$\endgroup\$
  • 2
    \$\begingroup\$ =_= what is this wizardry? \$\endgroup\$ – totallyhuman Oct 27 '17 at 19:35
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 3 bytes

¥ĀO

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Husk, 4 bytes

#IẊ≠

Try it online!

\$\endgroup\$
3
\$\begingroup\$

R, 24 bytes

cat(sum(!!diff(scan())))

Try it online!

Same as the MATL answer, just used sum(!!diff)) since there's no nnz.

\$\endgroup\$
  • \$\begingroup\$ +1 I thought using rle would be shorter, but nope, length(rle()$v) uses too many characters and is off by one. \$\endgroup\$ – Neal Fultz Oct 29 '17 at 16:42
  • \$\begingroup\$ @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. :) \$\endgroup\$ – Giuseppe Oct 29 '17 at 16:48
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ @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. \$\endgroup\$ – user48543 Oct 30 '17 at 2:02
  • \$\begingroup\$ apologies, will look at it again \$\endgroup\$ – MickyT Oct 30 '17 at 2:10
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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 「$_」
}
\$\endgroup\$
3
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 35 bytes

a=>a.filter((e,i)=>e-a[i+1]).length
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Arnauld Oct 26 '17 at 20:58
  • \$\begingroup\$ @Arnauld I'd tried that too, but miscounted and thought it was 36 bytes, otherwise I'd have added it in as an alternative. \$\endgroup\$ – Neil Oct 27 '17 at 0:44
2
\$\begingroup\$

Pyth, 5 bytes

l #.+

Test suite.

Explanation:

   .+  Deltas
  #    Filter on identity (space)
l      Get length 
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

J, 10 bytes

[:+/2~:/\]

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

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ [:+/0=-/\ ought to work for I think 9 bytes. \$\endgroup\$ – cole Oct 30 '17 at 19:02
2
\$\begingroup\$

Ruby, 31 bytes

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

Try it online!

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

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
}
\$\endgroup\$
  • \$\begingroup\$ Could you maybe add a link to an online testing environment? \$\endgroup\$ – Jonathan Frech Oct 29 '17 at 15:25
  • \$\begingroup\$ @JonathanFrech Added \$\endgroup\$ – pizzapants184 Oct 29 '17 at 18:11
2
\$\begingroup\$

05AB1E, 3 bytes

γ¦g

Try it online!

An alternative to Erik's answer.

γ¦g  ~ Full program.

γ    ~ Group into runs of equal adjacent elements.
 ¦   ~ Remove the first group (if there are any).
  g  ~ Length.
\$\endgroup\$
  • \$\begingroup\$ Ah, missed that that was a case. \$\endgroup\$ – Magic Octopus Urn Nov 2 '17 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.