# Question
Title: Convert C header names to C++ header names
In the C standard library, header names end with a `.h` suffix:

```
stdio.h

```

In C++, those header names are available in an alternative form, with a `c` prefix instead:

```
cstdio

```

Write a function that converts the first form into the second. You can do the conversion in-place, or leave the original string intact and return a new string. Whatever feelds natural in your language of choice.

The code must be compiled/interpreted without errors. Compiler warnings are acceptable.

Here is your baseline C solution. It has **70 characters** and generates a warning about `strlen`:

```
void f(char*h){int i=strlen(h);h[--i]=0;while(--i)h[i]=h[i-1];*h='c';}

```

The shortest solution (measured in number of characters) wins.

**Update:** If your language of choice does not support functions, whole programs are also acceptable.

**Update:** As suggested by FUZxxl, here is a complete list of the header files in the C standard library:

```
assert.h
ctype.h
errno.h
float.h
limits.h
locale.h
math.h
setjmp.h
signal.h
stdarg.h
stddef.h
stdio.h
stdlib.h
string.h
time.h

```

Specifically, there are no header names with multiple dots in them.

# Answer
> 37 votes
# 80386 machine code, 13 bytes

Hexdump of the code:

```
b0 63 86 01 41 3c 2e 75 f9 c6 01 00 c3

```

Source code (can be compiled by Visual Studio):

```
__declspec(naked) void __fastcall conv(char s[])
{
    _asm {
        mov al, 'c';            // b0 63
    myloop:
        xchg al, [ecx];         // 86 01
        inc ecx;                // 41
        cmp al, '.';            // 3c 2e
        jne myloop;             // 75 f9
        mov byte ptr [ecx], 0;  // c6 01 00
        ret;                    // c3
    }
}

```

It converts the string in-place. The code is so simple, it doesn't need to save and restore registers (using only `al` and `ecx`, which the `fastcall` convention allows to clobber).

# Answer
> 14 votes
# Python: 19 characters

```
lambda s:'c'+s[:-2]

```

# Answer
> 14 votes
# CJam, 6 bytes

```
'clW(<

```

This is a full program which reads the string via STDIN

**Explanation**:

```
'c               "Put character c on stack";
  l              "Read a line from STDIN";
   W             "W is a predefined variable with value -1";
    (            "Decrease the value by 1";
     <           "Remove last 2 characters from the string on stack, the input argument";

```

Try it online here

# Answer
> 12 votes
## Java 8 — 25 characters

```
h->"c"+h.replace(".h","")

```

# Answer
> 11 votes
# brainfuck - ~~25~~ 23 bytes

```
,[>,]<-----.<,<[<]>[.>]

```

> If your language of choice does not support functions, whole programs are also acceptable.

This is a whole program that takes input from STDIN.

```
,[>,]      get all bytes of input
<-----.    subtract 5 from last byte (always "h"; "h" minus 5 = "c") and print result
<,         set second last byte to 0 by abusing comma
<[<]>      go to first byte
[.>]       print byte and move right until hitting 0

```

# Answer
> 10 votes
## Haskell — 23 characters

```
('c':).takeWhile(/='.')

```

## Haskell — 16 characters, as suggested by nimi

```
('c':).init.init

```

# Answer
> 10 votes
# C, 38

See on Ideone

```
f(s,o){snprintf(o,strlen(s),"c%s",s);}

```

`s` is a pointer to the input string, and `o` is where the output should be written to.

I found a way to abuse `snprintf`. The output string conveniently happens to be one character shorter than the input, and the maximum length of the string written by `snprintf` is 1 less than the `n` argument, so it cuts off the `.h`. Note: this technique will not work with Microsoft's implementation because it does the wrong thing and fails to null-terminate the string.

# Answer
> 9 votes
# TIS Node Type T21 Architecture - 85 bytes

**This answer is just for fun; the language came into existence after this challenge was written and I therefore cannot win with it. (Not that I was going to.)**

Okay, I had a little fun with this one. I probably *should* just call the language "TIS-100", but why break character? :D

TIS-100 is a game about programming a computer with a totally unique and bizarre architecture. I wrote a custom puzzle for this challenge, which allows me to take input and check output against a known-correct "string". Unfortunately, there's no way to handle strings or characters, so this program simply uses the ASCII value of each character for input and output.

If you'd like to see it in action, you can use this emulator, or just watch me run it in the actual game here. Note that in the video, the final line of the first node is `D:MOV UP NIL`. After finishing the video, I realized I could golf that down to `D:ADD UP`. Functionally there's no difference, because the value of ACC is immediately overwritten anyway.

This is the string I used for my byte count:

```
MOV 99 ANY
MOV -46 ACC
ADD UP
JEZ D
ADD ACC ANY
JRO -5
D:ADD UP
MOV UP ANY
MOV UP ANY

```

That's the text of each non-empty node, seperated by newlines (effectively adding 1 byte for each node used beyond the first, mirroring our rule about code in multiple files).

# Answer
> 8 votes
**Windows Batch file 11**

```
@echo c%~n1

```

The first parameter passed in is %1. The ~n modifier returns just the filename without extension.

If it's acceptable to echo the expanded command to the screen as well, then the initial @ could be removed.

# Answer
> 7 votes
## J (9 characters)

```
'c',_2}.]

```
* `|y` is the *magnitude* of `y` (also called absolute value)
* `x }. y` drops `|x` items from `y`; items are dropped from the front if `x` is positive, from the end if `x` is negative.
* `x , y` appends `x` and `y`.
* `'c' , _2 }. y` does the transformation you want; in tacit notation this can be expressed as `'c' , _2 }. ]`.

# Answer
> 7 votes
## Dyalog APL (8 characters)

```
'c',¯2↓⊢

```

This solution is exactly the same as the J solution I submitted but uses one character less due to  being one character less than `}.`.

# Answer
> 7 votes
# piet (9x11 = 99 8X11=88)

## another try (2x37 = 74)

Hard to make it much smaller since it needs to generate a 99 ('c') and a 46('.'), and that takes space in piet.

# Answer
> 7 votes
# Ostrich 0.6.0, 8 characters

```
););"c\+

```

`)` is the "right uncons" operator. When applied to a string, it turns, for example, ``foo`` into ``fo` `o``. `;` is used to pop the extra character off, and this is done again.

Then, `"c` is pushed. This is simply a shorthand for ``c``.

`\+` swaps the top two stack elements and concatenates them.

# Answer
> 6 votes
## F# - ~~39~~ ~~37~~ 31

*31 - Because typeinference in F# rocks!*

```
fun s->("c"+s).Replace(".h","")

```

*37*

```
fun(s:string)->"c"+s.Replace(".h","")

```

*39*

```
fun(s:string)->"c"+s.Remove(s.Length-2)

```

# Answer
> 6 votes
# gema, 6

```
*.h=c*

```

(Gema is an obscure macro language.)

# Answer
> 5 votes
# GNU sed -r, 14

sed doesn't really have any concept of functions, so here is a complete sed program instead:

```
s/(.*)../c\1/

```

### Output

```
$ sed -r 's/(.*)../c\1/' <<< stdio.h
cstdio
$

```

The `-r` has been included in the score as one extra character.

# Answer
> 4 votes
# Bash, 18

```
f()(echo c${1%.*})

```

### Output:

```
$ f stdio.h
cstdio
$

```

# Answer
> 3 votes
# Pyth, 7 characters

```
L+\cPPb

```

Explanation:

```
L         def y(b):return
 +\c                      "c" +
    PPb                         b[:-1][:-1]

```

Try this:

```
L+\cPPb
y"stdio.h

```

on the online Pyth Compiler/Executor

---

If full programs were allowed:

# Pyth, 6 characters

```
+\cPPQ

```

# Answer
> 3 votes
# Prelude, 31 characters

Since full program submissions are apparently acceptable, here is a program that reads the C-style header from STDIN and prints the C++-style header to STDOUT:

```
99+9+(?)###(#
9(1-)       ^)(!)

```

This requires a standard-compliant interpreter which prints output as character codes. If you're using the Python interpreter you'll need to set `NUMERIC_OUTPUT = False`.

It also requires that there's no trailing newline on STDIN.

## Explanation

In Prelude all lines are executed in parallel, one column at a time. Each line has its own stack, initialised to an infinite amount of `0`s.

```
99+9+
9(1-)

```

This is the shortest I could come up with to get a `99` onto the top stack (the character code of `c`). First I add up `18` on the top stack and push a `9` onto the bottom stack. The bottom then counts down to `0` in a loop, while the top stack adds more `9`s up. This adds up to `99` on the top stack, and the bottom stack is left with `0`s again. Note that all of `+9+` is part of the loop, so there are actually two addition operations per iteration, but that's not an issue, thanks to the infinite supply of `0`s underneath.

Now `(?)` reads STDIN, one character at a time and pushes onto the top stack. The loop terminates at the end of the input, when `?` pushes a zero. `###` gets rid of that zero, the `h` and the `.`. Now the next loop pops numbers from the top stack while copying them to the bottom stack. This essentially reverses the stack. Note that the opening and closing parentheses are on different lines - this is not an issue, because the vertical position of the `)` is irrelevant in Prelude, but it saves me a byte on the first line.

Lastly, `(!)` prints all the characters until the stack is empty.

# Answer
> 3 votes
# C++14, 41 characters

```
[](auto&s){s="c"+s.substr(0,s.size()-2);}

```

Inspired by this other answer. I made it a separate answer because here I use a feature that is new in c++14, generic lambda.

See it in action here.

# Answer
> 2 votes
## Perl — 20 characters

```
sub{c.pop=~s/..$//r}

```

Note how `c` is a bareword and as such this requires a lack of `use strict`. This must be used as an expression, not a statement.

# Answer
> 2 votes
## T-SQL — 58 characters

```
CREATE PROC Q(@ VARCHAR(MAX))AS
SELECT'c'+LEFT(@,LEN(@)-2)

```

Run as EXEC Q (your string here)

# Answer
> 2 votes
# C, 64

Mildly shorter than the c reference:

```
f(char*h){char*d=strstr(h,".");memmove(h+1,h,d++-h);*d=0;*h=99;}

```

Probably more golfing to be done with this.

---

### C, 48 (libc hack)

```
f(char*h){strcpy(h+1,h);*strstr(h,".")=0;*h=99;}

```

The `strcpy` manpage explicitly states "The strings may not overlap". However I found that the libc I am using appears to be coded safely to handle this correctly all the same. This is GNU C Library (Ubuntu EGLIBC 2.19-0ubuntu6.4) on Ubuntu 14.04.

# Answer
> 2 votes
# Marbelous, 24

```
@063
-Z//
3W<C+Z
]]!!
@0

```

Takes input through STDIN, outputs to STDOUT.

This works by checking each byte with `.` (`0x46`). As `0x46` cannot fit inside a single base-36 digit, we subtract 35 (`Z`) before comparing, and add it back before outputting.

Each marble is duplicated by `3W` (three-way duplicator, but the left side is discarded off the side of the board). The marble sent downwards fetches the next byte from STDIN. The marble to the right is checked to `.`, then either outputted, or sent to `!!`, which terminates the program.

The program starts by passing `c` (`0x63`) through, which will be output to STDOUT.

Try it online here. Libraries must be enabled, cylindrical boards must be disabled.

# Answer
> 2 votes
# JavaScript (ES6) 20

Can't believe ES6 was still missing

```
s=>'c'+s.slice(0,-2)

```

# Answer
> 2 votes
# Perl, 15 (14 + -p)

```
s/(.*)\.h/c$1/

```

# Answer
> 2 votes
## mk, 34 characters

mk(1) is the Plan 9 replacement for make. Just for fun, this mkfile converts C header names into C++ header names:

```
c%:Q:
    :

%.h:Q: c%
    echo $prereq

```

There is a single tab before `:` and `echo`. Use like this:

```
% mk stdio.h
cstdio

```

# Answer
> 2 votes
# Vyxal, 5 bytes

```
\cpṪṪ

```

Explanation:

```
\cpṪṪ   # full program
\c      # c
  p     # prepend using implicit input
   ṪṪ   # remove last two letters

```

Try it Online!

# Answer
> 1 votes
# CoffeeScript - 16

```
(x)->"c"+x[..-3]

```

# Answer
> 1 votes
# TI-BASIC 83/84, 15

```
"c"+sub(Ans,1,length(Ans)-2

```

# Answer
> 1 votes
# Ruby: 16 characters

```
->x{?c+x[0..-3]}

```

Or, more correct solution as suggested by @mbuettner

```
->x{?c+x[/\w+/]}

```

You can call it like this:

```
->x{?c+x[/\w+/]}.call 'stdio.h'
# cstdio

```

# Answer
> 1 votes
## R, 33

```
function(x)sub("(.+)..","c\\1",x)

```

This function uses regular expressions.

Example usage:

```
> (function(x)sub("(.+)..","c\\1",x))("stdio.h")
[1] "cstdio"

```

# Answer
> 1 votes
# MS QuickBasic or QB64 ~ 33 bytes

```
A$=left$(A$,len(A$)-2)
A$="c"+A$

```

A$ is the name of the file

# Answer
> 1 votes
## Go, ~~47~~,46

```
func h(s string)string{return"c"+s[:len(s)-2]}

```

I know I'm not winning anything with this, but I thought I might as well go for it. No pun intended

# Answer
> 1 votes
# C++ 14, 48

```
[](string s){return "c"+s.substr(0,s.size()-2);}

```

# Answer
> 1 votes
# \>\<\>, ~~22~~ 21 bytes

Since full programs are now allowed...

```
i:0(?v
~}-5~/r
o;!?l<

```

## Explanation

```
i:0(?v      Keep reading input until EOF
~}-5~/r     Pop the -1 from EOF, turn 'h' -> 'c' with 5- and shift to back, pop '.', reverse stack
o;!?l<      Keep outputting until the stack is empty

```

# Answer
> 1 votes
# K, 7 bytes

```
"c",-2_

```

Pretty simple. Just drops 2 chars off the end and prepends a `c`.

Also, despite how it looks, this is actually a function:

```
f:"c",-2_
f"stdio.h"

```

# Answer
> 1 votes
# Awk: 10 characters

```
$0="c"$1

```

Sample run:

```
bash-4.3$ awk -F. '$0="c"$1' <<< 'stdio.h'
cstdio

```

# Answer
> 1 votes
# , 5 bytes

```
éc$xx

```

Try it online!

Hexdump:

```
00000000: e963 2478 78                             .c$xx

```

This is a full program that takes input from STDIN.

## Explanation

```
éc     insert the character 'c'
$      go to the end of the line
xx     delete two characters

```

This is `ic<esc>$xx` in pure Vim.

# Answer
> 1 votes
# Excel formula, ~~36~~ 23 bytes

If the input is put in cell A1,

```
="c"&LEFT(A1,LEN(A1)-2)

```

### Explanation

```
="c"&LEFT(A1,LEN(A1)-2)
="c"&                     Return the letter 'c' concatenated with...
     LEFT(            )   the first...
             LEN(A1)-2    (the length of input, minus 2 from the '.h') characters...
          A1,             of the input.

```

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
¨¨'cì

```

**Try it online.**
Header `ε` is used to for-each over the input-list to verify all test cases instead of just one.
Footer  is to close this for-each, and print the results with new-line delimiter.

**Explanation:**

```
¨¨       # Remove the last two characters of the input
    ì    # Prepend:
  'c     #  "c"

```

# Answer
> 1 votes
# Japt, ~~7~~ 6 bytes

```
ic ¯-2
ic     # Given the default input, prepend a 'c' at the start
   ¯-2 # and trim off the last two letters.

```

Try it online!

# Answer
> 1 votes
# Whitespace, 63 bytes

```
[S S S T    T   S S S T T   N
_Push_99_c][T   N
S S _Print_as_character][N
S S N
_Create_Label_LOOP][S S S N
S_Push_0][S N
S _Duplicate][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate][S S S T   S T T   T   S N
_Push_46_.][T   S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

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

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

**Explanation in pseudo-code:**

```
Print "c"
Start LOOP
  Character i = STDIN as character
  if(i == '.')
    EXIT program (with error)
  Print i
  Go to next iteration of LOOP

```

Program stops with an error: Label\_EXIT not found.

# Answer
> 1 votes
# *Acc!!*, 43 bytes

```
Write 99
N
Count i while _/96 {
Write _
N
}

```

Try it online!

### Algorithm

* Write `c`
* Read a character into the accumulator
* Loop while that character is a lowercase letter:
    + Write the character
    + Read another character

# Answer
> 0 votes
# TI-89 Basic, 56 bytes

```
:Def a(a)=Func
:Return "c"+sub(a,1,length(a)-2
:End Func

```

# Answer
> 0 votes
# Julia: 19 characters

```
f(s)="c"*s[1:end-2]

```

Sample run:

```
julia> f(s)="c"*s[1:end-2]
f (generic function with 1 method)

julia> print(f("stdio.h"))
cstdio

```

# Answer
> 0 votes
# Perl (program) 15

```
s/(.*)\.h/c\1/

```

It converts filenames supplied on std input, and needs to be run with the p flag, so that's one more character I believe. Eg

```
echo stdio.h | perl -p header.pl

```

output:

```
cstdio

```

Note to sticklers: I just spotted that this may be invalid because challenge implies that programs are only acceptable if the language *doesn't* support functions. However, I'm not going to throw it all away at this stage! Ah well.

Update: Augh! And I hadn't spotted page 2 of the answers either. Please refer to @malkaroee's effectively identical answer posted 4 months ago. ... Hang on, who resurrected this thread?

# Answer
> 0 votes
## Lua, 39 bytes

```
function f(n)return "c"..n:sub(1,-3)end

```

# Answer
> 0 votes
# C# 6, 52 bytes

```
class P{string C(string f)=>"c"+f.Replace(".h","");}

```

# C# \<6, 58 bytes

```
class P{string C(string f){return"c"+f.Replace(".h","");}}

```

# Answer
> 0 votes
# MATLAB, 19

```
@(c)[99,c(1:end-2)]

```

Fairly straight forward. Prepends 'c' to the input string less the last two letters. MATLAB automatically converts the 99 (ASCII value) to 'c' when appending to a character string.

# Answer
> 0 votes
# Tcl, 36 bytes

```
proc H h {set s c[regsub ..$ $h ""]}

```

Try it online!

# Answer
> 0 votes
# Stackers (27 bytes)

```
«h ®h h cc ( ~ ~

```

## Ungolfed Version

```
«h "define a table called h
®h "read STDIN to h
h "read h to the stack
cc  "add the value for 'c' to the stack
(   "put c on the bottom of the stack
~ ~ "destroy the top two values on the stack
   "print stack bottom two top

```

Stackers is a programming language I created myself that is meant to be based on stacks, with variables and tables thrown in

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 41 bytes

```
	INPUT ARB . O RPOS(2)
	OUTPUT ='c' O
END

```

Try it online!

# Answer
> 0 votes
# Thunno 2 `j`, 4 bytes

```
2ẓ'c

```

Attempt This Online!

#### Explanation

```
2ẓ'c  '# Implicit input
2ẓ     # Remove last two characters
  'c  '# Push the character "c"
       # Join the stack
       # Implicit output

```

# Answer
> 0 votes
# Raku, 13 bytes

```
{'c'~S/..$//}

```

Try it online!

`S/..$//` returns the result of chopping off the last two characters of the string, and `'c' ~` prepends a "c" to the front.

---
Tags: code-golf, string, conversion
---


title: Evaluating Logic Gates

text:
# Question
Title: Evaluating Logic Gates
Logic gates are functions which perform basic logic operations. In this problem, we will account for the following 6 logic gates: `AND`, `OR`, `XOR`, `NAND`, `NOR`, and `XNOR`. Each of these takes two boolean inputs \\$ a \\$ and \\$ b \\$, and outputs a boolean. Below are the truth tables which show the output of each gate given two inputs.

## Task

Given two boolean inputs \\$ a \\$ and \\$ b \\$, return/output a list of the names of all gates which would return a Truthy value. The order doesn't matter, but the names must be in the exact format as given in the 2nd sentence of the above paragraph (not the ones in the diagram). You are also allowed to output them exclusively in lowercase, if desired.

## Clarifications

* You may also output a delimiter-separated string
* I will allow leading/trailing spaces

## Test Cases

### Input

```
0 0
0 1
1 0
1 1

```

### Output

```
[NOR, NAND, XNOR]
[OR, NAND, XOR]
[OR, NAND, XOR]
[OR, AND, XNOR]

```

This is , so the shortest code in bytes wins!

# Answer
> 29 votes
# Python 3, ~~53 50~~ 49 bytes

*Thanks @JonathanAllan for saving 1 byte!*

```
lambda a,b:"NOR N"[a|b:5-a*b]+"AND X"+"NOR"[a^b:]

```

Try it online!

# Answer
> 8 votes
# , 46 bytes

```
;:@'AND NAND OR NOR XOR XNOR'#~*,*:,+.,+:,~:,=

```

Try it online!

*-5 bytes thanks to Bubbler*

We execute a train `*,*:,+.,+:,~:,=` corresponding to the gates on the arguments, which will produce a single boolean mask of the results.

We then apply that mask as a filter `#~` on the list of words, which is in the same order.

*Note:* Since the returned strings of are of unequal length, J requires them to be boxed.

# Answer
> 6 votes
# Python 2.7, ~~117~~ ~~111~~ ~~102~~ 98 bytes

*-6 bytes thanks to @math junkie!
-13 bytes thanks to @Surculose Sputum!*
Try it online!

Probably could be made shorter with `lambda` but I don't know how to use it:

```
a,b=input()
s="or nand xor"
if a==b:s=s.replace("o","no")
if a&b:s=s.replace("na","a")[1:]
print s

```

EDIT: Yep. This program uses string manipulation to solve the problem, which I thought was simpler, but now I'm not so sure.

# Answer
> 6 votes
# Ruby, 49 bytes

```
->a,b{"#{?N[a|b]}OR #{?N[a&b]}AND X#{?N[a^b]}OR"}

```

Try it online!

Interpolates `'N'` into the output string conditionally for each gate.

Alternatively, a direct port of @Surculose Sputum's excellent Python answer (be sure to upvote it!) is also 49 bytes:

```
->a,b{"NOR "[a|b,4]+"NAND X"[a&b,6]+"NOR"[a^b,3]}

```

Try it online!

# Answer
> 6 votes
# , ~~39~~ 37 bytes

```
[:;(_5<\'NAND NOR XNOR')}.~&.>*,+.,~:

```

Try it online!

-2 bytes thanks to @Jonah.

A solution that pretty much works like Surculose Sputum's Python 3 answer.

### How it works

```
NB. The three segments in the new version
_5<\'NAND NOR XNOR'
    'NAND NOR XNOR'  NB. a length-13 string
_5<\                 NB. enclose non-overlapping length-5 chunks
      (which works because the three N's to filter appear at indexes 0, 5, 10)

NB. Previous version
[:;('NAND ';'NOR X';'NOR')}.~&.>*,+.,~:  NB. Input: two bits as left/right args
                                *,+.,~:  NB. evaluate AND, OR, XOR
   ('NAND ';'NOR X';'NOR')               NB. corresponding three segments
                             &.>  NB. pair up both sides unboxed and
                          }.~     NB.   drop the first char from left if right is 1
[:;  NB. Remove boxing and concatenate into a single vector

```

# Answer
> 5 votes
# 05AB1E, 28 bytes

```
.•UNœ5Z’dµ•#εI…PàONè.Vi'nõ.;

```

Try it online!

# Answer
> 5 votes
# JavaScript (ES6), 55 bytes

```
a=>b=>'1OR 3AND X5OR'.replace(/\d/g,n=>n>>a+b&1?'N':'')

```

Try it online!

### How?

For each gate type, we use the sum of \\$a\\$ and \\$b\\$ to right-shift a bit mask. We test the least significant bit of the result to find out if we must return the complementary form of the gate.

```
   a  | 1 | 0 | 1 | 0 |
   b  | 1 | 1 | 0 | 0 |
------+---+-------+---+---------
  a+b | 2 |   1   | 0 | decimal
------+---+-------+---+---------
  NOR | 0 |   0   | 1 |    1
 NAND | 0 |   1   | 1 |    3
 XNOR | 1 |   0   | 1 |    5

```

---

# JavaScript (ES6), 55 bytes

Using a template literal is just as long.

```
a=>b=>['N'[a|b]]+`OR ${['N'[a&b]]}AND X${['N'[a^b]]}OR`

```

Try it online!

# Answer
> 5 votes
# C (gcc), ~~65~~ ~~60~~ 58 bytes

```
f(a,b){printf("NOR %s X%s"+(a|b),"NAND"+a*b,"NOR"+(a^b));}

```

Try it online!

# Answer
> 5 votes
# brainfuck, 234 bytes

```
>-[-[-<]>>+<]>-[<<++>+>-]<<+<<<-[+>++[++<]>]>-->>[>>>>[-]<<<<[>>+>>+<<<<-]<]<<,<,[>+<-]>[>+>+>>+<<<<-]>>>>--[>.<[-]]>>.>.>+++.>.[<]<<[>>+<<-]>+>[<[-]>[-]]<[->+<]>[>.<[-]]>+.+++.<<<<[>>>+<<<-]>>>>>>>>.<<<<++++++.<-[>>>.<<<[-]]>>>+.+++.

```

Try it online!

Takes input as two bytes (0 or 1) on stdin, outputs space-separated to stdout without trailing whitespace.

The TIO link has the `11` test case because I couldn't figure out how to type the null character into a web browser, but if you delete the second input character it will do the same thing as the `10` test-case, and if you delete both it will be the same as the `00` test-case.

Here's my annotated version (the two input bytes are `b` and `a`, their sum is `c`):

```
-[-[-<]>>+<]>- *32* from https://esolangs dot org/wiki/Brainfuck_constants#32
[<<++>+>-]      64 32 *0*
<<+<<<            *0* 0 0 65 32
-[+>++[++<]>]>-- *78* 65 32 from https://esolangs dot org/wiki/Brainfuck_constants#78

>>

 [>>>>[-]<<<<[>>+>>+<<<<-]<] 0 *0* 0 0 78 65 78 65 32

<<
,<,          *b* a     0 0 0 0 78 65 78 65 32
[>+<-]>      0 *b plus a=c* 0 0 0 0 78 65 78 65 32
[>+>+>>+<<<<-]>>>> 0 0 c c 0 *c* 78 65 78 65 32

--                      0 0 c c 0 *c minus 2* 78 65 78 65 32
[>.<[-]]>>.>.>+++.>.    0 0 c c 0 0   78 65 78 *68* 32    (N)AND space  print N if c != 2
[<]<<[>>+<<-]>>         0 0 c 0 0 *c* 78 65 78 68 32
<+>[<[-]>[-]]<[->+<]>   0 0 c 0 0 *!c* 78 65 78 68 32
[>.<[-]]>+.+++.         0 0 c 0 0 0  *82* 65 78 68 32     (N)OR         print N if c == 0
< <<<[>>>+<<<-]>>>      0 0 0 0 0 *c* 82 65 78 68 32
>>>>>.<<<<++++++.<      0 0 0 0 0 *c* 88 65 78 68 32      space X
-[>>>.<<<[-]]           0 0 0 0 0 *0* 88 65 78 68 32      (N)           print N if c != 1
>>>+.+++.               0 0 0 0 0 0   88 65 *82* 68 32

```

# Answer
> 4 votes
# Retina 0.8.2, 37 bytes

```
00
N2N
11
ODN
\d+
OND
D
AND X
O|$
OR

```

Try it online!

Input is as a single 2-digit string (one of `00`, `01`, `10`, or `11`). Performs a series of replacements to arrive at the required output.

**Explanation**

`AND X` is a string common to all 4 outputs, so we encode the string as `D`.

`OR` appears in a bunch of places so we encode that as `O`.

Then, we can replace each pair of digits with a string of `N`s, `O`s and `D`s. (The `00 -> N2N` and the `\d+ -> OND` are golfs arising from `10` and `01` yielding the same output and sharing some overlap with the output for `00`.

Finally, we just replace the `O`s and `D`s with the expanded string mentioned above and we get the required list!

# Answer
> 4 votes
# Bash \+ Core utilities, ~~53~~ 49 bytes

```
tr 01 N\\0<<<"$[$1|$2]OR $[$1&$2]AND X$[$1^$2]OR"

```

Try it online!

This is a full program. Input is passed as arguments, and the output is written to stdout.

# Answer
> 4 votes
# Pyth, 37 bytes

```
AQ%"%sOR X%sOR %sAND"*R\N!M[|GHxGH&GH

```

Try it online!

Takes a list of two values as input, outputs in the form `AND OR XNOR`

### Explanation

```
AQ                                     # Q is the input. Set G:=Q[0], H:=Q[1]
  %                                    # Format a string (printf-style)
   "%sOR X%sOR %sAND"                  # Format string
                     *R\N!M[|GHxGH&GH  # replacement values as a list:
                           [           # [                        ]
                            |GH        #  G or H
                               xGH     #          G xor H
                                  &GH  #                   G and H
                         !M            # map each to its negation
                     *R\N              # map each x to "N"*x

```

(Ab)uses the fact that in Python and thus Pyth, `True == 1` and `False == 0` and thus `"N"*True == "N"` and `"N"*False == ""`.

# Answer
> 4 votes
# Jelly, 23 bytes

```
S11,:Sµ“×®ṫ.¡Ḍẹhɗ»x€⁸¦0

```

A monadic Link accepting a list of two integers (in `[0,1]`) which yields a list of characters - the gate names separated by spaces.

**Try it online!** Or see the test-suite.

### How?

Observe that there are three outputs, aligning with the sums and that the sum \\$1\\$ and sum \\$2\\$ outputs are the sum \\$0\\$ one missing certain characters. When one-indexed the sum \\$1\\$ needs characters `1` and `11` removed while the sum \\$2\\$ one needs characters `1` and `5` removed. Furthermore \\$\lfloor \frac{11}{2} \rfloor = 5\\$.

```
S11,:Sµ“×®ṫ.¡Ḍẹhɗ»x€⁸¦0 - Link: list of integers, B  e.g [0,0]            [1,1]            [1,0] (or [0,1])
S                       - sum (B)                        0                2                1
 11                     - literal eleven                 11               11               11
   ,                    - pair                           [11,0]           [11,2]           [11,1]
     S                  - sum (B)                        0                2                1
    :                   - integer division               [inf,nan]        [5,1]            [11,1]
      µ                 - start a new monadic link, call that X
       “×®ṫ.¡Ḍẹhɗ»      - compressed string              "NOR NAND XNOR"  "NOR NAND XNOR"  "NOR NAND XNOR"
                   € ¦  - sparse application...
                    ⁸   - ...to indices: chain's left argument
                  x   0 - ...action: repeat zero times   "NOR NAND XNOR"  "OR AND XNOR"    "OR NAND XOR"

```

# Answer
> 3 votes
# APL (Dyalog Unicode), 30 bytes

```
∊'NAND ' 'NOR X' 'NOR'↓⍨¨∧,∨,≠

```

Try it online!

A port of my own J answer.

### How it works

```
∊'NAND ' 'NOR X' 'NOR'↓⍨¨∧,∨,≠
                         ∧,∨,≠  ⍝ AND, OR, XOR
 'NAND ' 'NOR X' 'NOR'↓⍨¨       ⍝ Drop an N from the string segments at ones
∊                               ⍝ Flatten

```

# Answer
> 3 votes
# 05AB1E, 42 bytes

```
.•Vs’9ìï´¸•.•B»Î5γ'¸•DŠ‚s.•B»¯4qld•‚«IðмCè

```

Try it online!

Makes a list: `["nor nand xnor", "or nand xor", "or nand xor", "or and xnor"]`; the input is read as a binary number and that corresponds to the position in the list. This could probably be reduced heavily as I see the other 05ab1e answer just uses `"nand nor xnor"` as its string.

# Answer
> 3 votes
# x86-16 machine code, IBM PC DOS, ~~57~~ 52 bytes

**Binary:**

```
00000000: a182 0025 0101 8bd8 ba2f 0152 0ac4 7401  ...%...../.R..t.
00000010: 42b4 09cd 21ba 2801 84df 7401 42cd 215a  B...!.(...t.B.!Z
00000020: 32df 7401 42cd 21c3 4e41 4e44 2058 244e  2.t.B.!.NAND X$N
00000030: 4f52 2024                                OR $

```

**Listing:**

```
A1 0082     MOV  AX, [0082H]        ; load command line chars into AH/AL
25 0101     AND  AX, 0101H          ; ASCII convert
8B D8       MOV  BX, AX             ; save input to BX for later
BA 012F     MOV  DX, OFFSET NOR     ; DX = string 'NOR'
52          PUSH DX                 ; save 'NOR' for later
0A C4       OR   AL, AH             ; OR or NOR?
74 01       JZ   OUT_NOR            ; is OR?
42          INC  DX                 ; increment string pointer to skip 'N'
        OUT_NOR:
B4 09       MOV  AH, 9              ; DOS write string function
CD 21       INT  21H                ; write to STDOUT
BA 0128     MOV  DX, OFFSET NAND    ; DX = string 'NAND X'
84 DF       TEST BL, BH             ; AND or NAND?
74 01       JZ   OUT_NAND           ; is AND?
42          INC  DX                 ; increment string pointer to skip 'N'
        OUT_NAND:
CD 21       INT  21H                ; write string to STDOUT
5A          POP  DX                 ; Restore DX = 'NOR'
32 DF       XOR  BL, BH             ; XOR or XNOR?
74 01       JZ   OUT_XOR            ; is OR?
42          INC  DX                 ; increment string pointer to skip 'N'
        OUT_XOR:
CD 21       INT  21H                ; write string to STDOUT
C3          RET                     ; return to DOS

    NAND    DB  'NAND X$'
    NOR     DB  'NOR $'

```

A standalone PC DOS executable. Input via command line, output string to `STDOUT`.

**I/O:**

# Answer
> 2 votes
# OIL, 81 bytes

```
5
1
5
NAND OR XOR
10
NAND NOR XNOR
1
9
20
10
AND OR XNOR
6
14
17
4
10
3
4
5
3
4
3

```

As usual with golfed OIL code, we use cells as both data and code. All the strings also serve as references to the cell #0 (which will later contain the second input), and we use cell #6 (the one containing a `1`) as both a reference to cell #1, as well as the value `1`.

# Answer
> 2 votes
# Aceto, 67 bytes

```
pdA`ANpn
"Ln>"D"L
RON'  Ov
 "p   Vu
p^`p"pX
N''XRO
irHL "<`
riMdpN'

```

Try it online!

---

I'm using quick storage for one of the inputs, the stack for the other. It's mostly conditionally escaped movement to avoid printing `N`, but I also used the reverse-and-jump-to-the-end trick for a few saved bytes.

# Answer
> 2 votes
## Common Lisp, 154 bytes

Not a short answer, but relies on `BOOLE`, which is a function that is practically never used:

```
(lambda(a b)(loop for(n o)in`((and,boole-and)(nand,boole-nand)(or,boole-ior)(nor,boole-nor)(xor,boole-xor)(xnor,boole-eqv))if(/=(boole o a b)0)collect n))

```

Readable version:

```
(loop
   for (name op) in `((and  ,boole-and)
                      (nand ,boole-nand)
                      (or   ,boole-ior)
                      (nor  ,boole-nor)
                      (xor  ,boole-xor)
                      (xnor ,boole-eqv))
   unless (= (boole op a b) 0)
   collect name)

```

All couples `(name op)` in the list are made of `name`, a symbol used for the output, and `op`, a constant integer value that represents a particular boolean operation. The `boole` functions knows how to perform the operation based on such value. Note that `xnor` is the equivalence operation, namely `boole-eqv`.

The loop builds a list of names such that the associated operation yields a non-zero result.

Indeed, if you do:

```
(boole boole-nand 1 1)

```

The result is `-2`, a.k.a. `-10` in binary; this is because those operations assume an *infinite* two's complement representation (https://comp.lang.lisp.narkive.com/OXYD1hNK/two-s-complement-representation-and-common-lisp)

# Answer
> 2 votes
# Factor, 55 bytes

```
[ + { "NOR NAND XNOR""OR NAND XOR""OR AND XNOR" } nth ]

```

Try it online!

Add and index into list of strings. This one's pretty boring, so here's a longer but more interesting version:

# Factor, 73 bytes

```
[ [ or ] [ and ] [ xor ] 2tri [ "" "N"? ] tri@ "%sOR %sAND X%sOR"printf ]

```

Try it online!

My first submission in Factor! Hopefully the first of many, since this language is really cool. Technically this doesn't run on new versions of the language because I didn't put spaces after some strings, but it works on the old version TIO has. (I would use ATO, but it's offline at the moment.)

Explanation:

`[ ... ]` Quotation (anonymous function) taking two booleans
`[ or ] [ and ] [ xor ] 2tri` Apply each of the three quotations `or`, `and`, `xor` on the two booleans
`[ "" "N"? ] tri@` Apply to each of the three results: If true, "", else "N"
`"%sOR %sAND X%sOR"printf` Insert each "" or "N" into the right part of the string, and print.

# Answer
> 2 votes
# Python 3, 60 bytes

Not really close to the gold, but found it interesting that just picking from the list of options is within 11 bytes of the best python answer, and more than 30 bytes smaller than the other python answer. Shows how impressive golfing those 11 bytes are imo.

Also shorter than some other langs that i think could also implement the same method.

```
lambda a,b:['nor nand xn','or nand x','or and xn'][a+b]+'or'

```

Try it online!

# Answer
> 1 votes
# Io, 65 bytes

Port of Surculose Sputum's Python answer.

```
method(a,b,"NOR "slice(a|b).."NAND X"slice(a&b).."NOR"slice(a^b))

```

Try it online!

# Answer
> 1 votes
# Charcoal, 160 bytes

```
×N¬ΣθOR ×N‹Σθ²AND X×N↔⊖ΣθOR

```

Try it online! Link is to verbose version of code. Takes input as an array or string of two bits. Explanation: Just interpolates the `N`s as appropriate based on the count of `1` bits (zero for the first `N`, less than 2 for the second, and absolute difference from 1 for the third).

# Answer
> 1 votes
# Haskell, 78 Bytes

```
a?b=[h(a||b)"OR""NOR",h(a&&b)"AND""NAND",h(a/=b)"XOR""XNOR"];h x a b|x=a|9>0=b

```

---
Tags: code-golf, logic-gates
---


title: Logarithmic Incrementation

text:
# Question
Title: Logarithmic Incrementation
In this challenge you will write a function that takes a list (ordered set) containing real numbers (the empty list is an exception, as it has nothing) and calculates $$f(x)=\begin{cases}1 & \text{if } |x|=0 \\ x\_1+1 & \text{if } |x|=1 \\ \log\_{|x|}\sum\_{n=1}^{|x|}{|x|}^{x\_n} & \text{otherwise} \end{cases}$$ where \\$|x|\\$ is the length of list \\$x\\$ and \\$x\_n\\$ is the \\$n^\text{th}\\$ item in the list \\$x\\$ using 1-based indexing. But why is this called “logarithmic ***incrementation***”? Because there is an interesting property of the function: $$f(\\{n,n\\})=n+1$$ Amazing, right? Anyways, let’s not go off on a tangent. Just remember, this is , so the shortest answer wins! Oh, right, I forgot the legal stuff:

* Standard loopholes apply.
* In a tie, the oldest answer wins.
* Only numbers that your language can handle will be input.

### Test cases:

```
[] -> 1
[157] -> 158
[2,2] -> 3
[1,2,3] -> 3.3347175194727926933796024072445284958617665867248313464392241749...
[1,3,3,7] -> 7.0057883515880885509228954531888253495843595526169049621144740667...
[4,2] -> 4.3219280948873623478703194294893901758648313930245806120547563958...
[3,1,4] -> 4.2867991282182728445287736670302516740729127673749694153124324335...
[0,0,0,0] -> 1
[3.14,-2.718] -> 3.1646617321198729888284171456748891928500222706838871308414469486...

```

Output only needs to be as precise as your language can reasonably do.

# Answer
# APL (Dyalog Unicode), ~~22~~ 15 bytes

Anonymous tacit prefix function implementing $$f(x)=x\_1\cdot\big\[1=\lvert x\rvert\big\]+\log\_{\lvert x \rvert} \sum\_{n=1}^{\lvert x\rvert}1^{\lvert x\rvert-n}\cdot\lvert x\rvert^{x\_n}$$

```
(⊃×1=≢)+≢⍟1⊥≢*⊢

```

Try it online!

`(`

the first element

`×` times

`1=` whether (1) or not (0) one equals

the length of the argument

`)+` plus

`≢⍟` the length-logarithm of

`1⊥` the sum (lit. the base-one evaluation) of

the length

`*` raised to the power of (each element in)

the argument

### Old solution: APL (Dyalog Extended), 22 bytes

Anonymous prefix lambda.

```
{0::1+⊃⍵⋄+/⍢((≢⍵)∘*)⍵}

```

Try it online!

`{``}` "dfn"; argument is

`0::` if any error happens:

`1+` increment

`⊃⍵` the first element of the argument

`+/⍢(``)⍵` the sum of the argument, under the influence of:

`(``)∘*` raising to the power of:

`≢⍵` the tally of elements (length of the argument)
> 7 votes

# Answer
# JavaScript (ES7), 62 bytes

```
a=>a.map(v=>t+=n**v,t=0,n=a.length)&&(L=Math.log)(t)/L(n)||++a

```

Try it online!

### How?

Given the input list \\$a\\$ and its length \\$n\\$, we compute:

$$t=\sum\_{i=0}^{n-1}n^{a\_i}$$

We then try to compute \\$log\_n(t)=log(t)/log(n)\\$.

If the result is `NaN`, we return `++a` instead.

This will happen if:

* \\$n=0\\$ : we try to compute \\$\log(0)/\log(0)\\$
* \\$n=1\\$ : we try to compute \\$\log(1)/\log(1) = 0/0\\$

This gives the correct answer in both cases because:

* if \\$n=0\\$, we increment the empty array, which gives \\$1\\$.
* if \\$n=1\\$, there's a single atom \\$x\\$ in \\$a\\$ which is coerced to a number and incremented.
> 6 votes

# Answer
# Haskell, 54 bytes

```
f[]=1
f[x]=1+x
f x|n<-sum$1<$x=logBase n$sum$map(n**)x

```

Try it online!

# Haskell, 56 bytes

```
f[]=1
f[x]=1+x
f x|n<-sum$x>>[1]=logBase n$sum$map(n**)x

```

Try it online!

# Haskell, 70 bytes

```
f[]=1;f[x]=1+x;f x|let n=fromIntegral$length x=logBase n$sum$map(n**)x

```

Try it online!
> 4 votes

# Answer
# , ~~50~~ 44 bytes

*Edit: -1 byte thanks to @Dominic van Essen.*

```
\(x,`?`=sum,l=?x|1)`if`(l<2,x?1,log(?l^x,l))

```

Attempt This Online!
> 3 votes

# Answer
# Python NumPy, 81 bytes

```
lambda l:[sum(l)+1,w(l*(x:=w(l*0)))/x][x>0]
from numpy import*
w=logaddexp.reduce

```

Attempt This Online!

Takes a numpy array for input.

Test harness nicked from @AnttiP.

#### How?

Uses the almost-builtin: `numpy.logaddexp.reduce` Shame it's such a mouthful.
> 3 votes

# Answer
# Python, 85 76 bytes

Essentially by @Albert.Lang

```
lambda l:math.log(sum(map(pow,[L:=len(l[2:])+2]*L,l+l+[0,0])),L)
import math

```

Attempt This Online!
> 2 votes

# Answer
# Excel, 57 bytes

```
=LET(x,A1#,y,ROWS(x),IF(y-1,LOG(SUM(y^x),y),IFNA(x+1,1)))

```

Input is vertical spilled range `A1#`.
> 2 votes

# Answer
# Python NumPy, 70 bytes

```
lambda l:math.log(sum(L**l),L)if(L:=len(l))>1else sum(l)+1
import math

```

Attempt This Online!

A rather dirty mix which expects a numpy array as input to take advantage of vectorised arithmetic but later uses the log from std lib math because it allows to specify the base.

Test harness from @AnttiP via @loopywalt.
> 2 votes

# Answer
# Go, 160 bytes

```
import."math"
type F=float32
func f(N[]F)F{L,s:=F(len(N)),0.0
if L<1{return 1}
if L<2{return N[0]+1}
for i:=0;i<int(L);i++{s+=Pow(L,N[i])}
return Log(s)/Log(L)}

```

Attempt This Online!
> 2 votes

# Answer
# Ruby, ~~57~~ 53 bytes

```
->x{k=x.size;k>1?Math::log(x.sum{|c|k**c},k):x.sum+1}

```

Try it online!
> 2 votes

# Answer
# Vyxal, 24 Bytes

```
□L2<[?1+,]□L:ẋ□e∑∆l□L∆l/

```

### My first Vyxal answer!

Try it online! (List is given as input of numbers separated by newlines. This will not work if there is a trailing or leading newline in the input.)

If you want the output as a decimal instead of a fraction, use the  flag.

If the length is `2` or above, it applies the general formula and implicitly prints the result. If the length is `1` or `0`, it adds `1` to the number. With a list of length `1`, this just increments the number and prints it. With a list of length `0`, it increments it to get `1` and prints it, but then throws an error. Luckily, `STDERR` is ignored by default.
> 2 votes

# Answer
# Desmos, 68 67 ~~65~~ 53 Bytes

Thanks to AidenChow for -12 Bytes!

```
l=a.length
f(a)=\{l=0,l=1:a[1]+1,\log_l(l^a.\total)\}

```

Now needs a keypress before it works
Without needing keypress (and visible) (~~66~~ 65 Bytes):
-1 from AidenChow

```
f(a)=\left\{l=0,l=1:a[1]+1,log_l(l^a.total)\right\}withl=a.length

```

Link
> 1 votes

# Answer
# Charcoal, 27 bytes

```
Ｉ⎇Φθκ▷math.log⟦ΣＸＬθθＬθ⟧⊕↨θ¹

```

Attempt This Online!\** Link is to verbose version of code. Explanation: Port of @AnttiP's Python answer.

```
   θ                        Input array
  Φ                         Filtered where
    κ                       Index is not zero
 ⎇                          If still not empty then
                  θ         Input array
                 Ｌ          Length
                Ｘ           Vectorised raise to power
                   θ        Input array
               Σ            Summed
     ▷math.log⟦       ⟧     Logarithm to base
                     θ      Input array
                    Ｌ       Length
                         θ  Otherwise input array
                        ↨ ¹ Summed via "base 1" conversion*
                       ⊕    Incremented
Ｉ                           Cast to string
                            Implicitly print

```

\*Base 1 conversion returns `0` for an empty list, which `Sum` does not.
\**I'm using ATO instead of TIO because the version of Charcoal on TIO incorrectly prints floats whose value is just below that of an integer.
> 1 votes

# Answer
# PARI/GP, 48 bytes

```
x->if(1<n=#x,log(vecsum(n^x))/log(n),n,x[1]+1,1)

```

Attempt This Online!
> 1 votes

# Answer
# 05AB1E, ~~17~~ 15 bytes

```
g©ImO®.n®_+®i+`

```

Try it online or verify all test cases.

**Explanation:**

```
g©ImO®.n  # Otherwise portion of the formula:
g         #  Push the length of the (implicit) input-list
 ©        #  Store it in variable `®` (without popping)
  I       #  Push the input-list
   m      #  Take the length to the power of each element
    O     #  Sum them together
     ®.n  #  Take the base-`®` logarithm of that sum
®_+       # n=0 case of the formula:
®_        #  Push length `®` again, and check whether it's 0 (1 if 0; 0 otherwise)
  +       #  Add that to the value
®i+`      # n=1 case of the formula:
®i        #  If length `®` is 1:
  +       #   Add the current value to the wrapped value of the input-list
   `      #   And unwrap it by popping and pushing its value to the stack
          # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Pyth, 15 bytes

```
.x.ls^lQQlQhe+Z

```

Try it online!

### Explanation

```
.x.ls^lQQlQhe+ZQ    # implicitly add Q
                    # implicitly assign Q = eval(input())
.x                  # try:
     ^lQQ           #   length(Q) to the power of each element of Q
    s               #   sum all elements
  .l     lQ         #   take the log base length Q
                    # except: (log will error if length is 0 or 1)
             +ZQ    #   prepend 0 to Q
            e       #   take the last element
           h        #   and increment it

```
> 1 votes

# Answer
# Prolog (SWI), 105 bytes

```
[H|T]*L*S:-T*L*N,S is N+L^H,!.
_*0.
A-K:-A=[B],K is B+1,!;length(A,L),L>1,A*L*S,K is log(S)/log(L),!;K=1.

```

Try it online!

Defines a predicate `A-K` which matches the ordered list `A` to its logarithmic incrementation `K`.
> 1 votes

# Answer
# Scala, 95 bytes

Golfed version. Try it online!

```
l=>l match{case Nil=>1 case Seq(x)=>1+x case _=>{val n=l.size;log(l.map(pow(n,_)).sum)/log(n)}}

```

Ungolfed version. Try it online!

```
import scala.math._

object Main {
  def f(l: List[Double]): Double = {
    l match {
      case Nil => 1.0
      case List(x) => 1 + x
      case _ => {
        val n = l.count(_ => true)
        log(l.map(pow(n, _)).sum) / log(n)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    println(f(List(3.0, 3.0)))
  }
}

```
> 0 votes

# Answer
# Perl 5 List::Util, 43 bytes

```
sub{@_>1?log(sum map@_**$_,@_)/log@_:1+pop}

```

Try it online!
> 0 votes

---
Tags: code-golf, math
---


title: Is this a function?

text:
# Question
Title: Is this a function?
Given a list of `(key, value)` pairs, determine whether it represents a function, meaning that each key maps to a consistent value. In other words, whenever two entries have equal keys, they must also have equal values. Repeated entries are OK.

For example:

```
# Not a function: 3 maps to both 1 and 6
[(3,1), (2,5), (3,6)]

# Function: It's OK that (3,5) is listed twice, and that both 6 and 4 both map to 4
[(3,5), (3,5), (6,4), (4,4)]

```

**Input:** An ordered sequence of `(key, value)` pairs using digits 1 to 9. You may not require a particular ordering. You may alternatively take the key list and value list as separate inputs.

**Output:** A consistent value for functions, and a different consistent value for non-functions.

**Test cases:** The first 5 inputs are functions, the last 5 are not.

```
[(3, 5), (3, 5), (6, 4), (4, 4)]
[(9, 4), (1, 4), (2, 4)]
[]
[(1, 1)]
[(1, 2), (2, 1)]

[(3, 1), (2, 5), (3, 6)]
[(1, 2), (2, 1), (5, 2), (1, 2), (2, 5)]
[(8, 8), (8, 8), (8, 9), (8, 9)]
[(1, 2), (1, 3), (1, 4)]
[(1, 2), (1, 3), (2, 3), (2, 4)]

```

Here they are as two lists of inputs:

```
[[(3, 5), (3, 5), (6, 4), (4, 4)], [(9, 4), (1, 4), (2, 4)], [], [(1, 1)], [(1, 2), (2, 1)]]
[[(3, 1), (2, 5), (3, 6)], [(1, 2), (2, 1), (5, 2), (1, 2), (2, 5)], [(8, 8), (8, 8), (8, 9), (8, 9)], [(1, 2), (1, 3), (1, 4)], [(1, 2), (1, 3), (2, 3), (2, 4)]]

```

---

**Leaderboard:**

```
var QUESTION_ID=118960,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/118960/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 38 votes
# Python 2, 34 bytes

```
lambda x:len(dict(x))==len(set(x))

```

Try it online!

Creates a Dictionary and a Set from the input and compare their lengths.
Dictionaries can't have duplicated keys, so all the illegal (and repeated) values are removed.

# Answer
> 22 votes
## Haskell, 36 bytes

```
f x=and[v==n|(k,v)<-x,(m,n)<-x,k==m]

```

Try it online!

Outer (-\>`(k,v)`) and inner (-\> `(m,n)`) loop over the pairs and whenever `k==m`, collect the truth value of `v==n`. Check if all are true.

# Answer
> 20 votes
# Brachylog, ~~5~~ 4 bytes

```
dhᵐ≠

```

Try it online!

Full program. As far as I can tell, the reason that this is beating most other golfing languages is that  is a builtin in Brachylog, whereas most of the other golfing languages need to synthesize it.

## Explanation

```
dhᵐ≠
d     On the list of all unique elements of {the input},
 h    take the first element
  ᵐ     of each of those elements
   ≠  and assert that all those elements are different

```

As a full program, we get `true` if the assertion succeeds, or `false` if it fails.

# Answer
> 17 votes
# Pyth, 5 bytes

I'm pretty happy with this one.

```
{IhM{
       implicit input
    {  removes duplicate pairs
  hM   first element of each pair
{I     checks invariance over deduplication (i.e. checks if no duplicates)

```

Try it online!

# Answer
> 10 votes
## Retina, 25 bytes

```
1`({\d+,)(\d+}).*\1(?!\2)

```

Try it online!

Input format is `{k,v},{k,v},...`. Prints `0` for functions and `1` for non-functions. I could save two bytes by using linefeeds instead of the commas in the input format, but that's messed up.

# Answer
> 10 votes
# Brachylog, 13 bytes

```
¬{⊇Ċhᵐ=∧Ċtᵐ≠}

```

Try it online!

### Explanation

```
¬{          }      It is impossible...
  ⊇Ċ               ...to find a subset of length 2 of the input...
   Ċhᵐ=            ...for which both elements have the same head...
       ∧           ...and...
        Ċtᵐ≠       ...have different tails.

```

# Answer
> 7 votes
# 05AB1E, ~~11~~ ~~9~~ 7 bytes

Saved 2 bytes thanks to *kalsowerus*.

```
Ùø¬DÙQ,

```

Try it online!

**Explanation**

```
Ù           # remove duplicates
 ø          # zip
  ¬         # get the first element of the list (keys)
   D        # duplicate list of keys
    Ù       # remove duplicates in the copy
     Q      # compare for equality
      ,     # explicitly print result

```

# Answer
> 7 votes
# MATL, 8 bytes

```
1Z?gs2<A

```

Inputs are: an array with the `value`s, followed by an array with the `key`s.

Output is `1` for function, `0` otherswise.

Try it online!. Or verify all test cases.

### Explanation

`1Z?`

Builds a sparse matrix. Initially all entries contain `0`; and `1` is added to each entry `(i, j)` where `j` and `i` are the input `key`, `value` pairs.

`g`

The matrix is converted to logical; that is, entries exceeding `1` (corresponding to duplicate `key`, `value` pairs) are set to `1`.

`s`

The sum of each column is computed. This is the number of different `value`s for each `key`.

`2<A`

A function will have all such sums less than `2`.

# Answer
> 6 votes
# R, 33 bytes

This is my version for R. This takes advantage of the `ave` function. I have allowed for empty input by setting defaults on the key and value parameters. `ave` is producing a mean of the values for each of the keys. Fortunately this returns the means in the same order as the input values, so a comparison to the input will indicate if there is different values. Returns `TRUE` if it is a function.

```
function(k=0,v=0)all(ave(v,k)==v)

```

Try it online!

# Answer
> 5 votes
## JavaScript (ES6), ~~45~~ 38 bytes

*Saved 6 bytes thanks to @Neil*

```
a=>a.some(([k,v])=>m[k]-(m[k]=v),m={})

```

Returns `false` or `true` for functions and non-functions, respectively.

This works by constantly subtracting the old value of each function (`m[k]`) and the new one (`m[k]=v`, which also stores the new value). Each time, there are three cases:

* If there was no old value, `m[k]` returns `undefined`. Subtracting anything from `undefined` results in `NaN`, which is falsy.
* If the old value is the same as the new one, `m[k]-v` results in `0`, which is falsy.
* If the old value is different from the new one, `m[k]-v` results in a non-zero integer, which is truthy.

Therefore, we just have to make sure that `m[k]-(m[k]=v)` is never truthy.

# Answer
> 5 votes
## Mathematica, 24 bytes

```
UnsameQ@@(#&@@@Union@#)&

```

Explanation: `Union` deletes duplicated pairs, then `#&@@@` gets the first element from each pair (like `First/@` but with fewer bytes). If there is any repetition in these first elements, the pairs don't make a function, which we check with `UnsameQ`.

(This might have the highest density of `@` characters in any program I've written…)

# Answer
> 5 votes
# J-uby, ~~48~~ ~~33~~ ~~25~~ 21 bytes

-3 bytes thanks to Jordan!

```
:size*:==%[:to_h,~:|]

```

### Explanation

```
:size*:==%[:to_h,~:|]

# "readable"
(:size * :==) % [:to_h, ~:|]

# transform :% to explicit lambda
->(x){ (:size * :==).(:to_h ^ x, ~:| ^ x)

# apply explicit x to functions
->(x){ (:size * :==).(x.to_h, x|x) }

# expand :* (map over arguments)
->(x){ :==.(:size.(x.to_h), :size.(x|x) }

# simplify symbol calls to method calls
->(x){ x.to_h.size == (x|x).size }

# :| is set union for arrays; x|x just removes duplicates, like :uniq but shorter
->(x){ x.to_h.size == x.uniq.size }

```

# First Approach, 33 bytes

```
-[:[]&Hash,:uniq]|:*&:size|:/&:==

```

This one is longer than the equivalent Ruby solution, but it was fun to make.

Attempt of explanation by transforming to Ruby:

```
-[:[]&Hash,:uniq]|:*&:size|:/&:==

# "readable"
-[:[] & Hash, :uniq] | (:* & :size) | (:/ & :==)

# turn into explicit lambda
->(x){ (:/ & :==) ^ ((:* & :size) ^ (-[:[] & Hash, :uniq] ^ x)) }

# simplify expressions now that we have an explicit x
->(x){ :== / (:size * [Hash[x], x.uniq]) }

# translate to equivalent Ruby code
->(x) { [Hash[x], x.uniq].map(&:size).reduce(:==) }

# simplify reduce over explicit array
->(x) { Hash[x].size == x.uniq.size }

```

I could save 2 bytes with a newer version by replacing `:uniq` with `~:|`

# Answer
> 4 votes
# 05AB1E, 9 bytes

Code:

```
ãü-ʒ¬_}}Ë

```

Explanation:

```
ã            # Cartesian product with itself
 ü-          # Pairwise subtraction
   ʒ  }}     # Filter out elements where the following is not true:
    ¬_       #   Check whether the first digit is 0
        Ë    # Check if all equal

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 4 votes
# Bash + coreutils, 17

```
sort -u|uniq -dw1

```

Input is given via STDIN. `key` and `value` are `Tab` separated and each pair is newline-delimited.

`sort` removes the duplicate key-value pairs. `uniq -d` only outputs duplicates, and so outputs the empty string in the case of a function, and a non-empty string otherwise - when there are duplicate keys that map to different values.

Try it online.

# Answer
> 4 votes
# Jelly, 6 bytes

```
QḢ€µQ⁼

```

Try it online!

**Explanation**

```
QḢ€µQ⁼
Q      - Remove duplicate pairs
 Ḣ€    - Retrieve the first element of each pair
   µ   - On the output of what came before..
     ⁼ - Are the following two equal (bit returned)?
    Q  - The output with duplicates removed
       - (implicit) the output.

```

Here is an alternate method, also 6 bytes:

```
QḢ€ṢIẠ

```

Try it online!

Instead of testing with removing duplicate keys, this sorts () and checks if the difference between terms (`I`) is all truthy ()

# Answer
> 4 votes
# R, ~~36~~ 33 bytes

```
function(k,v)any(v[match(k,k)]-v)

```

Try it online!

anonymous function; returns `FALSE` for functions and `TRUE` for not.

This ~~is being beaten by~~ is finally tied with MickyT's answer!!

# Answer
> 4 votes
# Jelly, 6 bytes

```
nþ`ḄCȦ

```

Try it online!

### How it works

```
nþ`ḄCȦ  Main link. Argument: M (n×2 matrix)

nþ`     Construct the table of (a != b, c != d) with (a, b) and (c, d) in M.
   Ḅ    Unbinary; map (0, 0), (0, 1), (1, 0), (1, 1) to 0, 1, 2, 3 (resp.).
    C   Complement; map each resulting integer x to 1 - x.
     Ȧ  All; test if all resulting integers are non-zero.

```

# Answer
> 4 votes
# Actually, 4 bytes

```
╔♂F═

```

Try it online!

Explanation:

```
╔♂F═
╔     uniquify (remove duplicate pairs)
 ♂F   take first items in each pair (keys)
   ═  are all of the keys unique?

```

# Answer
> 4 votes
# K (ngn/k), 11 bytes

```
{r~?r:*'?x}

```

Try it online!

Port of chunes' factor answer.

## Explanation

```
{r~?r:*'?x}

{         }     /function
        ?x      /distinct values
      *'        /first value of each
    r:          /store in r
 r~?            /is distinct?

```

# Answer
> 3 votes
# , 30 bytes

```
Úç^¨.*©î±$/d
ÎwD
ç/HdG
Íî
Ò1lD

```

Try it online!

Outputs `1` for functions and nothing for non-functions.

# Answer
> 3 votes
# CJam, ~~19~~ 17 bytes

Saved 2 bytes thanks to Martin Ender

```
0l~$2ew{:.=~!&|}/

```

Outputs `0` for functions and `1` for non-functions.

Try it online!

**Explanation**

```
0                     e# Push a 0. We need it for later.
 l~                   e# Read and eval a line of input.
   $                  e# Sort it by the keys.
    2ew               e# Get all consecutive pairs of the sorted list.
       {              e# For each pair of pairs:
        :.=           e#  Check if the keys are equal and if the values are equal.
           ~!&        e#  Determine if the keys are equal AND the values are not equal.
              |       e#  OR with 0. If any pair indicates that the input is not a function,
                      e#  this will become 1 (and remain 1), otherwise it will be 0.
               }/     e# (end block)

```

# Answer
> 3 votes
# , ~~95~~ 66 bytes

```
function(k,v)any(sapply(k,function(x){length(unique(v[k==x]))-1}))

```

*Saved 29 bytes thanks to Jarko Dubbeldam.*

Anonymous function. Outputs `FALSE` if a function and `TRUE` if not (sorry). Takes as arguments a list of keys and a list of values, like so.

```
> f(c(1,2,5,1,2),c(2,1,2,2,5))
[1] TRUE # not a function

```

Loops through all keys and grabs the length of the set of unique values for that key. If `any` of them are \> 1, return `TRUE`.

This is being beaten by MickyT's answer, and also Giuseppe's. upvote one of those.

# Answer
> 3 votes
# Mathematica, 35 bytes

```
(l=Length)@Union@#==l@<|Rule@@@#|>&

```

Pure function taking a list of ordered pairs as input and returning `True` or `False`. Exploits the fact that `Union@#` deletes repeated ordered pairs, but `<|Rule@@@#|>` (an association) deletes all but one ordered pair with a particular first element. So we can just compare the `Length`s of the two outputs to check whether the input list is a function.

# Answer
> 3 votes
# APL (Dyalog), ~~16~~ ~~12~~ ~~11~~ 9 bytes

```
(∪≡⊢)⊃¨∘∪

```

Try it online!

### Explanation

```
∪             Unique, remove duplicates; (3 5) (3 5) => (3 5)
¨∘            For each element
⊃             Pick the first sub element (3 5) (2 3) => 3

 ≡            Check whether the arguments (listed below) are the same
  ⊢           The right argument
∪             And the right argument with duplicates removed

```

Prints `0` for false and `1` for true

# Answer
> 3 votes
# brainfuck, 71 bytes

```
,[[-[->>+<<]+>>],>[[->+<<->]<[<<]>]>[-<+>]<<[->+<]+[-<<]>>,]-[--->+<]>.

```

Try it online!

Input is taken as a flat string: for instance, the first test case would be `35356444`. To get the representation shown in the original question, simply add a total of six commas to the program at the right points.

Output is `U` for functions and `V` for non-functions.

### Explanation

For any ASCII code point n, f(n) is stored at cell 2n+1. Cells 2n and 2n+2 are working space, and 0, 2, 4, 6, ... 2n-2 are a trail of breadcrumbs to lead back to cell 0. When the input is proven not to be a function, f(0) is set to 1 (among various side effects).

```
,                  input first key
[                  start main loop
 [-[->>+<<]+>>]    move to cell 2n, leaving a trail of breadcrumbs
 ,                 input value corresponding to current key
 >[                if key already has a value:
   [->+<<->]<      copy existing value, and compare to new value
   [<<]            if values are different, go to cell -2
   >               go back to cell 2n+1 (or -1 if mismatch)
 ]
 >[-<+>]           move existing value back to cell 2n+1 (NOP if no existing value, move the 1 from cell 0 to cell -1 if mismatch)
 <<[->+<]          copy new value to cell 2n+1 (NOP if there was already a value)
 +[-<<]>>          follow breadcrumbs back to cell 0 (NOP if mismatch)
 ,                 input next key
]                  (if mismatch, cell -2 becomes the next "cell 0", and the next key is also effectively changed by the breadcrumbs left lying around)
-[--->+<]>.        add 85 to cell 1 and output the result

```

# Answer
> 3 votes
# Desmos, 46 bytes

```
U=L.unique
f(L)=0^{U.length-U.x.unique.length}

```

Function returning 1 for functions and 0 for non-functions.

Equivalent, but slightly longer:

```
f(L)=0^{L.unique.length-L.unique.x.unique.length}

```

Try it on Desmos!

# Answer
> 3 votes
# Factor, 28 bytes

```
[ members keys all-unique? ]

```

Try it online!

* `members` Get the unique elements
* `keys` Get the keys of an associative array as a sequence
* `all-unique?` Are they all unique?

```
             ! { { 1 2 } { 2 1 } { 5 2 } { 1 2 } { 2 5 } }
members      ! { { 1 2 } { 2 1 } { 5 2 } { 2 5 } }
keys         ! { 1 2 5 2 }
all-unique?  ! f

```

# Answer
> 3 votes
# Julia, 14 bytes

```
!x=x⊆Dict(x)
```

Attempt This Online!

# Answer
> 2 votes
# MATL, 12 bytes

```
iFFvXu1Z)SdA

```

The input is 2-column matrix, where the first column is key and the second is value.

Try it online!

### Explanation

```
i     % Input: 2-column matrix
FFv   % Postpend a row with two zeros. This handles the empty case
Xu    % Unique rows. This removes duplicate (key, value) pairs
1Z)   % Select first column, that is, key. We need to check if all
      % keys surviving at this point are different
S     % Sort
d     % Consecutive differences
A     % Are all values nonzero?

```

# Answer
> 2 votes
# Perl 6, 38 bytes

```
!*.unique(:as(~*)).repeated(:as(*[0]))

```

Try it

# Answer
> 2 votes
# Pyth - ~~9~~ 8 bytes

```
ql.d{Ql{

```

Try it

It works by removing any repeated pairs first ({Q); then it compares the length of the list to the length of a dictionary created from the list (if the same x value occurs more than once, the dictionary constructor uses only the last one, resulting in the dictionary being shorter than the list)

# Answer
> 2 votes
# PHP, 49 bytes

```
foreach($_GET as[$x,$y])($$x=$$x??$y)-$y&&die(n);

```

Prints nothing for functions and `n` for non-functions.

# Answer
> 2 votes
# JavaScript (ES6) from ETHproductions', 35 bytes

```
a=>a.some(([k,v])=>a[~k]-(a[~k]=v))

```

# Answer
> 2 votes
# GolfScript, ~~30~~ ~~17~~ ~~14~~ 12 bytes

```
~.|{0=}%..|=

```

Try it online!

Outputs 1 for true, 0 for false.

Explanation:

```
~.|{0=}%..|= Full program, implicit input
             Stack: "[[3 5] [3 5] [6 4] [4 4]]"
~            Evaluate input
             Stack: [[3 5] [3 5] [6 4] [4 4]]
 .|          Make unique with setwise or with itself
             Stack: [[3 5] [6 4] [4 4]]
   {0=}%     Get first element of each
             Stack: [3 6 4]
        ..|  Duplicate and make unique again
             Stack: [3 6 4] [3 6 4]
           = Compare
             Stack: 1
             Implicit output

```

# Answer
> 2 votes
# Jelly, 5 bytes

```
ĠịE€Ạ

```

Takes input as a list of keys and a list of values.

Try it online!

# Answer
> 2 votes
# Vyxal, 5 bytes

```
UvhÞu

```

Try it Online!

Port of chunes' factor answer

```
U     # Uniquify
 vh   # Get the first of each
   Þu # Are they all unique?

```

# Answer
> 2 votes
# Jelly, 3 bytes

```
EƙẠ

```

Try it online!

Uses the same input format as Dennis's solution, and does almost exactly the same thing. Considering that `ƙ` had been implemented for half a year at that point, the only conclusion I can draw is that even he couldn't remember how the damn thing works :P

Stumbled on this because I thought of `ŒṬSṠƑ`, which is way funnier (directly implements the classic "vertical line test") but unfortunately errors given any empty lists.

# Answer
> 1 votes
# Python 3, ~~32~~ ~~30~~ 29 bytes

Thanks MD XF for saving 2 bytes with a different approach, and xnor for another byte with yet another approach

```
lambda x:{*x}>dict(x).items()

```

Try it online!

Prints `False` for yes, `True` for no.

```
lambda x:not dict(x).items()^x

```

Try it online!

Also 30 bytes:

```
lambda x:not x-dict(x).items()

```

Try it online!

Alternatively (thanks xnor):

```
lambda x:{*x}<=dict(x).items()

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~39~~ ~~30~~ 29 Bytes

Thanks to @ValueInk for saving 9 bytes!

```
->x{Hash[x].size==(x|x).size}

```

Port of @Rod's Python 2 answer.

# Answer
> 1 votes
# CJam, ~~14~~ ~~11~~ 9 bytes

```
_&0f=__&=

```

Try it online!

Takes input as an array of key/value pairs on the stack, returns `1` if the input is a function, and `0` if it's not.

This solution is based on the snippet `_&`, which de-duplicates an array by taking the set intersection of it with itself. I do this twice, first on the full input (to get rid of any exactly duplicated key/value pairs) and then on just the keys (to see if there are any duplicate keys still left after the first de-duplication).

Here's the full code with comments:

```
_&           "remove duplicate key/value pairs from input";
  0f=        "remove the values, leaving only the keys";
     _       "make a copy of the array of keys";
      _&     "remove duplicate keys from the copy";
        =    "compare the de-duplicated key array with the original";

```

# Answer
> 1 votes
# Ruby, 24 Bytes

```
->x{!x.uniq.uniq! &:pop}

```

Note that this only works if the points are given in `[value, key]` order, i.e. backwards. To be used like:

```
f = ->x{!x.uniq.uniq! &:pop}
p f.([[1,3], [5,2], [6,3]])
p f.([[5,3], [5,3], [4,6], [4,4]])

```

One of the funky quirks of `uniq!` is that it returns `nil` if no changes are made and the modified array if changes are made. If everything's already unique, you get a false-y value.

You asked for consistent values, so this gives a consistent `true` and `false`. If you're happy to just get a truthy value for one case and a falsey value for the other then we can save a byte by removing the first `!`.

# Answer
> 1 votes
# Husk, 5 bytes

```
S=ü←u

```

Try it online!

### Explanation

```
S=ü←u  -- example input: [(3,5),(3,5),(6,4),(4,4)]
    u  -- remove duplicates: [(3,5),(6,4),(4,4)]
S      -- is it ..
 =     -- .. equal to it
  ü    -- | remove duplicates by
   ←   -- | | first element (key): [3,6,4]
       -- | : [(3,5),(6,4),(4,4)]
       -- : 1

```

---

### Alternative, 5 bytes

This one might be cheating, since it assumes that the pairs are ordered by their `key`s which imo would make more sense:

```
ΛË→ġ←

```

Try it online!

### Explanation

Note that all non-zero integers in Husk are truthy:

```
ΛË→ġ←  -- example input: [(3,5),(3,5),(6,4),(4,4)]
   ġ   -- group elements by
    ←  -- | first element (key): [3,3,6,4]
       -- : [[(3,5),(3,5)],[(6,4)],[(4,4)]]
Λ      -- do all elements satisfy
 Ë     -- | all elements equal by
  →    -- | | second element (value): [[5,5],[4],[4]]
       -- : [3,2,2]
       -- : 4

```

# Answer
> 1 votes
# Javascript, 41

```
v=>!v.some(([a,b])=>new Map(v).get(a)!=b)

```

```
const F = v=>!v.some(([a,b])=>new Map(v).get(a)!=b)

// Helper code to display test results on page

const $ = s => document.querySelector(s);

const displayArea = $("#displayArea");

const testFunctions = [
  [
    [3, 5],
    [3, 5],
    [6, 4],
    [4, 4]
  ],
  [
    [9, 4],
    [1, 4],
    [2, 4]
  ],
  [],
  [
    [1, 1]
  ],
  [
    [1, 2],
    [2, 1]
  ]
];
const testNotFunctions = [
  [
    [3, 1],
    [2, 5],
    [3, 6]
  ],
  [
    [1, 2],
    [2, 1],
    [5, 2],
    [1, 2],
    [2, 5]
  ],
  [
    [8, 8],
    [8, 8],
    [8, 9],
    [8, 9]
  ],
  [
    [1, 2],
    [1, 3],
    [1, 4]
  ],
  [
    [1, 2],
    [1, 3],
    [2, 3],
    [2, 4]
  ]
];

function println(text) {
  displayArea.append(text);
  displayArea.append(document.createElement("br"));
}

testFunctions.forEach(value => println(JSON.stringify(value) + F(value)));

println("");

testNotFunctions.forEach(value => println(JSON.stringify(value) + F(value)));
```

```
<div id="displayArea"></div>
```

# Answer
> 1 votes
# Pip `-x`, 10 bytes

```
UQa#=UQaZb

```

Takes input as two command-line arguments: a key list and a value list. Attempt This Online!

### Explanation

```
UQa#=UQaZb
  a         The key list
UQ          Uniquified
   #=       Is the same length as
       a    The key list
        Z   Zipped with
         b  The value list
     UQ     Uniquified

```

# Answer
> 1 votes
# PowerShell for Windows, 40 bytes

```
!($args|sort -u|group{$_[0]}|? c* -gt 1)

```

Try it online!

Where `c*` is the shortcut for the `count` property.

# Answer
> 1 votes
# Arturo, 31 bytes

```
$=>[=unique<=map unique&=>last]

```

Try it

Takes pairs in reverse order. That is, `[value,key]`.

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
UṬhDU⁼

```

(No ATO link since it's down at the moment)

#### Explanation

```
UṬhDU⁼  # Implicit input
U       # Uniquify the input
 Ṭ      # Transpose it
  h     # Get the first item
   D    # Duplicate it
    U⁼  # And check if it's all unique
        # Implicit output

```

# Answer
> 1 votes
# Julia 1.0, 27 bytes

```
~x=allunique(first.(x∪x))

```

Try it online!

# Answer
> 0 votes
# C (gcc), ~~95~~ 94 bytes

*Thanks to @hvd for saving a byte!*

```
i;r,l;f(int*k,int*v){int m[10]={0};for(r=i=0;l=k[i];++i)!m[l]?m[l]=v[i]:v[i]-m[l]?++r:0;r=!r;}

```

Takes input as pointers to two zero-terminated arrays.

Try it online!

# Answer
> 0 votes
# Python 2, 55 bytes

```
i=[j[0] for j in set(input())];print len(set(i))==len(i)

```

Try it online!

# Answer
> 0 votes
# PHP, 83 Bytes

prints 1 for function and nothing for non functions

```
<?$r=[];foreach($_GET as$v)in_array($v,$r)?:$k[($r[]=$v)[0]]++;echo max($k?:[1])<2;

```

Testcases

# Answer
> 0 votes
# JS (ES5), 75 bytes

```
c=function (a){m={};for(i=0;i<a.length;i++)if(m[a[i]]-(m[a[i]]=i))return 1}

```

# Answer
> 0 votes
# Befunge-98, 40 bytes

```
&:#@!#._:&:a1p1g:9`3j>;#_-3j@.1_#;$a1g1p

```

Try it online!

Input consists of zero-terminated sequence of numbers `v₁ k₁ v₂ k₂ v₃ k₃ …`, output is `0` if the sequence represents a function, `1` if not.

## Explanation

Key-value pairs are stored in the funge space on the second row (immediately below the program code).

```
&:#@!#._:&:a1p1g:9`3j>;#_-3j@.1_#;$a1g1p
&                                         S: v = read()
 :# !# _                                  if v != 0 goto N
   @ #.                                   return v
         &:a1p1g                          N: k = read(), m[10] = k, w = m[k]
                 9`3j>;#_        ;        if w > 9 goto P
        :       :        -3j   _#         if v == w goto P
                            @.1           return 1
                                  $a1g1p  P: m[v] = m[10], goto S

```

`w > 9` in the fifth line is a shortcut for `w == 32` which is the value of an uninitialized cell.

# Answer
> 0 votes
# Java 8, 74 bytes

This is a lambda from `Iterable<int[]>` or `int[][]` to `int` or `Integer` (1 indicates function, 0 non-function). It checks each pair of mappings for compliance.

```
l->{for(int[]a:l)for(int[]b:l)if(a[0]==b[0]&a[1]!=b[1])return 0;return 1;}

```

Try It Online

# Answer
> 0 votes
# Ruby 1.9+, 20 bytes

```
->a{a|a==[*Hash[a]]}

```

In recent versions of Ruby, converting an array to a hash (dictionary) and then back preserves its order, so we can do an equality comparison instead of using `.size`. Otherwise this is similar to the more general Ruby answer, including the trick of removing duplicates by unioning the input array with itself.

---
Tags: code-golf, decision-problem
---