20
\$\begingroup\$

Given a list of non-negative integers, return whether or not that list is all the same number.

Rules

  • Input and output can be taken/given in any reasonable and convenient format
  • Truthy/Falsey values can be represented as any value of your choice as long as it's reasonable and relatively consistent (e.g. 1 for falsey and >= 2 for truthy is fine)
  • There will always be at least 1 item in the input list
  • The list items are guaranteed to be in the range [0, 9] (\$0 \le n \le 9\$)
  • Standard loopholes apply

This is code golf, so the shortest program in each language wins. I've made a community wiki answer for trivial answers, so feel free to submit potentially longer programs.

Test Cases

[1, 1, 1, 1, 1, 1, 1] -> True
[1, 2, 3, 4] -> False
[6, 9, 6, 9, 6] -> False
[6] -> True
[7, 7] -> True
[4, 2, 0] -> False
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Relevant: Default policy for ouput in decision problems (since this challenge doesn't specify the allowed options for the output]. Anyway, it would be better for the challenge to explicitly specify what is allowed and what isn't \$\endgroup\$
    – Luis Mendo
    Apr 21, 2021 at 9:08
  • \$\begingroup\$ @LuisMendo Input and output can be taken/given in any reasonable and convenient format, that's pretty standard for more trivial challenges \$\endgroup\$ Apr 21, 2021 at 12:50
  • 3
    \$\begingroup\$ @RedwolfPrograms Sure, but I'm not talking about format. I understand format as outputting string '3' instead of number 3; or producing the output via program exit code. What I mean is what options for output are allowed: two consistent values? Non-consistent truthy/falsy? One consistent value for truthy and any inconsistent values for falsy? \$\endgroup\$
    – Luis Mendo
    Apr 21, 2021 at 14:29

51 Answers 51

1
2
2
\$\begingroup\$

Perl 5 -p, 13 bytes

$_=/^(.)\1*$/

Try it online!

Since the input is all single digit numbers, this wants the input without spaces.

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

APL (Dyalog Unicode), 5 bytes

×/⊢=⊃
×/ ⍝ product reduce
  ⊢=⊃ ⍝ three train, each element equal to first element

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ you can remove the parens for a 4-train. See (f g h k) here. \$\endgroup\$
    – Razetime
    Apr 24, 2021 at 4:32
  • 1
    \$\begingroup\$ @Razetime Oh, wow. Thanks :) \$\endgroup\$ Apr 25, 2021 at 3:27
  • \$\begingroup\$ alternatively ⍋≡⍒, ≠≡⍷⍨, or any of the solutions presented here youtube.com/watch?v=GZuZgCDql6g \$\endgroup\$
    – rak1507
    Apr 26, 2021 at 9:08
  • \$\begingroup\$ @rak1507 I hadn't committed them to memory yet, this is just what came to my head. That was a great talk though. \$\endgroup\$ Apr 26, 2021 at 14:18
2
\$\begingroup\$

Husk, 2 bytes

And thanks to Razetime for some other 2-byters

(the 1-byte Husk built-in is E (same))

hg

Try it online!

Returns truthy (nonempty list) if all elements are not the same, falsy (empty list) if they're all the same. Collects groups of equal values and returns the head by discarding the last group.

(Other 2-byters with various truthy/falsy & falsy/truthy return values: ËI, Ë=, #≠, and some 3-byters: ΠẊ=, hk=, hġ=, hü=)

\$\endgroup\$
1
  • \$\begingroup\$ two other builtin answers: ËI and Ë= \$\endgroup\$
    – Razetime
    Apr 25, 2021 at 7:33
2
\$\begingroup\$

x86-16 machine code, 6 bytes

Hexdump:

0000:0000  89 F7 AC F3 AE C3                                ......

Explanation

                                   ; Routine A. [All The Same?]
                                   ; Expects CX = Length of input,
                                   ;         SI = Initial address of list.

0000:0000  89F7        MOV DI, SI  ; A1 [Load]. Set DI to SI.
0000:0002  AC          LODSB       ;            AL = [SI++].
0000:0003  F3AE        REPZ SCASB  ; A2 [Compare].
                                   ;       ZF = 1
                                   ;       Loop CX times:
                                   ;           If AX != [DI]:
                                   ;               ZF = 0
                                   ;               Proceed to A3
                                   ;           DI ++
0000:0105  C3          RET         ; A3 [End]. End of algorithm.
                                   ;           ZF = 0 if not all same.
                                   ;           ZF = 1 if all same. █
\$\endgroup\$
1
2
\$\begingroup\$

Whitespace, 66 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Label_LOOP][S N
S _Duplicate_first_input][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate][N
T   T   S N
_If_neg_Jump_to_Label_DONE][T   S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_LOOP][T N
S T _Print_as_integer][N
N
N
_Exit_program][N
S S S N
_Create_Label_DONE][T   N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Takes the input-list new-line separated with -1 to indicate we're done with the inputs. Outputs -1 as truthy, and the first input as falsey (+4 bytes to output 0 instead if this is not allowed).

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer firstInput = STDIN as integer
Start LOOP:
  Integer next = STDIN as integer
  If (next == -1):
    Print next as integer to STDOUT
    (Stop program with error: no exit defined)
  If (firstInput == next):
    Go to next iteration of LOOP
  Else:
    Print firstInput as integer to STDOUT
    Stop program
\$\endgroup\$
2
\$\begingroup\$

Golfscript, 4 bytes

~.&,

For the input: a set of numbers should be placed in '[]' without commas.

For the output: 1 is a truthy value while integers greater than 1 are falsey.

Try it online!

Explanation:

I hope this does not count as a 'trivial solution'... :)

~    # Evals the input to generate a list. 
 .   # Duplicates the list. 
  &  # Does setwise AND. Doing AND on two same lists will have the effect of removing duplicate elements. 
   , # Returns the length of the remaining list. 
\$\endgroup\$
2
\$\begingroup\$

Python, 16 bytes

def f(a):b,={*a}

Attempt This Online!

Signals by exit code.

Python NumPy, 16 bytes

lambda a:a.ptp()

Attempt This Online!

Takes a numpy array and returns 0 for True and 1 or more for False.

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

TI-Basic, 5 bytes

min(Ans=min(Ans

Takes input in Ans. Outputs 0 for falsey, and 1 for truthy.

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

AWK, 18 bytes

1,$0=NF~gsub($1,e)

Attempt This Online!

Revisiting my former answer, I realized that if I wanted $0 to be printed every time, I can use range patterns. In fact, if begpat (the left part) is always true, then the range pattern is always true. So I substituted the appending ( )e technique to the range pattern 1,, saving one byte.

AWK, 19 bytes (former answer)

$0=(NF~gsub($1,e))e

Try it online!

In details:

       gsub($1,e)    Searches and substitutes every occurrence of the first number
                     of the input ($1) for a null variable (e). It returns the
                     number of substitutions made.

    NF~              Matches the Number of Fields (i.e., number of items) and the
                     number of substitutions.
                     We expect 1 or 0 as result, but there will be no output when
                     it parses as 0. (AWK skips falsey patterns, and 0 is falsey.)

   (             )e  Appending a null variable converts 1 to "1" and 0 to "0".
                     That's good, because strings are always true.

$0=                  Sets the original input to the resulting "1" or "0".
                     As the pattern is a string, it is printed.
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 18 bytes

a=>new Set(a).size

Try it online!

Couldn't find the name of the Set builtint. Thanks dingledooper :P (outputs using the 1,>1 method that pretty much everyone is using now)

Previously...

JavaScript (Node.js), 39 bytes

a=>a.map(x=>a[0]==x).reduce((x,y)=>x&y)

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ The obvious a=>new Set(a).size<2 works too. \$\endgroup\$ Apr 21, 2021 at 2:09
  • \$\begingroup\$ @dingledooper oh that's what sets are called. thanks \$\endgroup\$
    – hyper-neutrino
    Apr 21, 2021 at 2:10
  • \$\begingroup\$ For the non-trivial one, how about d=>d.some(x=>x!=d[0])? Should return false if all items are identical, and true otherwise (unless I've done a stupid). You can put a ! in front to make it return a more sensible interpretation of true and false. Also, is it okay if I post this as my own answer? :p \$\endgroup\$ Apr 21, 2021 at 2:21
  • \$\begingroup\$ @RedwolfPrograms i keep forgetting javascript list utilities like map and all are methods and not globals ;-; also sure :P \$\endgroup\$
    – hyper-neutrino
    Apr 21, 2021 at 2:24
1
\$\begingroup\$

Pyth, 2 bytes

l{

Test suite

Outputs 1 if all elements are equal, and some integer* greater than 1 otherwise.
* Number of unique elements.

\$\endgroup\$
1
\$\begingroup\$

CSASM v2.4.0.2, 57 bytes

Pops an ~arr:i32 from the stack, then pushes true (all elements are the same) or false (some elements are different).

func a:
dup
len
swap
newset
conv ~arr
len
comp.gt
push $f.o
ret
end

Explanation + Full Program:

.asm_name AllSame

func main:
    .local i : ~arr:i32,5
    .local j : ~arr:i32,5

    ; Initialize the arrays
    ; i = [ 1, 1, 1, 1, 1 ]
    push i
    push 1
    stelem 0

    push i
    push 1
    stelem 1

    push i
    push 1
    stelem 2

    push i
    push 1
    stelem 3

    push i
    push 1
    stelem 4

    ; j = [ 1, 2, 3, 4, 5 ]
    push [1..5]
    conv ~arr
    pop j

    clf.o

    ; Get the first result
    push i
    call a

    ; Print it
    push "Is 'i' all same? "
    swap
    add
    print.n

    clf.o

    ; Get the second result
    push j
    call a

    ; Print it
    push "Is 'j' all same? "
    swap
    add
    print.n

    ret
end

func a:
    dup
    ; [ array, array ]
    len
    ; [ array, length ]
    swap
    ; [ length, array ]
    newset
    ; [ length, set ]
    conv ~arr
    ; [ length, set elements ]
    len
    ; [ length, element count ]
    comp.gt
    ; If "length" is greater than "element count", then the set had duplicate
    ;   entries which were removed

    ; Push the comparison flag
    push $f.o
    ret
end
```
\$\endgroup\$
1
\$\begingroup\$

K (oK), 4 bytes

Solution:

1=#?

Try it online!

Explanation:

Is the count of the unique items equal to 1?

1=#? / the solution
   ? / unique
  #  / count
1=   / equal to 1?
\$\endgroup\$
1
\$\begingroup\$

MMIX, 36 bytes (9 instrs)

Takes array of bytes and length as two arguments, C conventions

00000000: 83020000 27010101 82ff0001 32ffff02  ³£¡¡'¢¢¢²”¡¢2””£
00000010: 52ff0002 f8000000 5b01fffb e3000001  R”¡£ẏ¡¡¡[¢”»ẉ¡¡¢
00000020: f8010000                             ẏ¢¡¡

Disassembly and explanation:

alleq   LDBU $2,$0,0        // x = *a
0H      SUBU $1,$1,1
        LDBU $255,$0,$1     // loop: t = a[--l]
        CMPU $255,$255,$2
        PBZ  $255,0F        // iflikely(t == x) goto skp
        POP  0,0            // return 0 (abuses how POP works)
0H      PBNZ $1,0B          // skp: iflikely(l) goto loop
        SETL $0,1
        POP  1,0            // return 1
\$\endgroup\$
1
\$\begingroup\$

Mascarpone, 25 bytes

,['0.]v*1['1.]v*']<[:,>!]v*' <:' >,<:,>!

Try It Online!

This program accepts strings similar to this one:

"[2 8 1 6 4]"

and prints either '1' or '0' to stdout, with no newline.

Explanation

,['0.]v*1['1.]v*']<[:,>!]v*' <:' >,<:,>!
,['0.]v*1                                    First we take and ignore the first input
                                             character '[', and create an interpreter
                                             for which the default operation is to print
         ['1.]v*']<                          '0'. Next we bind the operation "print '1'"
                                             to the symbol ']' under this interpreter.   
                   [:,>!]v*                  Now we push an operation that takes a symbol
                                             from stdin, extracts the operation associated
                                             with that symbol from the interpreter on the
                                             stack, and executes it.                     
                           ' <               We now bind this operation to the space
                              :' >           character.  Immediately, we extract the
                                             operation back out of the interpreter, and
                                  ,<         bind it to the next symbol from stdin, which
                                             is the first number in the list.  Finally, we
                                    :,>!     manually execute the function once, to begin
                                             the cycle.  Now, the interpreter will continue
                                             to take input until it receives a symbol that
                                             is neither space nor the first number.  The
                                             program will print '1' if that symbol is ']',
                                             otherwise it will print '0'.

I wrote a solution in 36 characters, however the input/output format is inconvenient enough that I don't think it qualifies:

,[$.]v*1['1.]v*']<[:,$,>!]v*,<:,$,>!

It takes strings similar to this:

"[2 8 1 6 4 ]"

and prints '1' if the items are all equal, and '[' otherwise.

As Mascarpone is character-set-agnostic (provided the set contains the 17 symbols used by the initial interpreter) and only 26 unique characters are needed for this program to succeed (the 17 original instructions, the space character, and the characters 2-9), we require only 5 bits per character. By this logic, the solutions would be 25 bytes and 22.5 bytes in size, respectively.

\$\endgroup\$
1
\$\begingroup\$

Desmos, 24 bytes

f(l)=(1[2...]-l)^2.total

Returns 0 for truthy, and a positive number (not 0) for falsey.

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
1
\$\begingroup\$

Python 3, 22 bytes

lambda n:len(set(n))<2

Try it online!

Set function takes all the unique elements of the group only.

\$\endgroup\$
1
\$\begingroup\$

J, 6 bytes

1=#&~.

Attempt This Online!

Outputs 0 for falsey, and 1 for truth.

How?

1=#&~.
   &    Compose:
  #     The length of
    ~.  The nub (of the input)
1=      Is it equal to one?
\$\endgroup\$
1
\$\begingroup\$

Batch, 93 bytes

@set i=%1
:l
@if %i:~,1%==%i:~-1% (if %i% gtr 9 (set/ai=%i%/10&goto:l)else echo 1)else echo 0

Takes input from the command line as a string of numbers. Outputs 0 for falsey, and 1 for truthy.

\$\endgroup\$
1
\$\begingroup\$

Ly, 6 bytes

a0I=u;

Try it online!

This one works by sorting the list of number and comparing the top and bottom of the stack.

a       - sort the stack, implicitly reads the numbers first
 0I     - copy the bottom entry to top of the stack
   =    - compare the top two entries
    u;  - print boolean result, exit to stop from auto printing the stack
\$\endgroup\$
1
\$\begingroup\$

Julia 1.0, 12 bytes

length∘∪

Try it online!

  • outputs 1 if all numbers are equal, >1 else
  • is for function composition
  • is union, equivalent to unique for a single argument. Set would also work for the same number of bytes (but is nicer)

Julia 1.8, 8 bytes

allequal

Attempt This Online! when ATO updates to 1.8

  • the boring solution

Julia 0.6, 3 bytes

var

Try it online!

  • outputs 0 or NaN for truthy, anything else for falsy
  • for Julia 1.0+, add using Statistics
  • std would work the same way
\$\endgroup\$
1
2

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.