17
\$\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 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 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 at 14:29

43 Answers 43

1
2
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 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\$

AWK, 19 bytes

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

Pari/GP, 19 bytes

v(s)=gcd(s)==lcm(s)

Try it online!

\$\endgroup\$
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\$
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 at 2:09
  • \$\begingroup\$ @dingledooper oh that's what sets are called. thanks \$\endgroup\$
    – hyper-neutrino
    Apr 21 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 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 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\$

Julia, 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)
\$\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
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.