title: No strings (or numbers) attached

text:
# Question
Title: No strings (or numbers) attached
If you like this, consider participating in:

---

Make 12 **snippets/expressions**, in the same language, that result in the numbers 0 through 10, and 42 respectively, but without writing any literal numeric, string, or character data.

Build-in data, like `PI()` and `ALPHABET()`, are fine, and so are e.g. CJam's U, X, Y, Z, and A constants, and Processing's BLEND, CHORD, CENTER, BREAK, and LINES.

Every snippet must be able to stand on its own, i.e. they may not be interdependent. However, inside a single snippet, you may assign a variable and use it freely, as long as you refer to it directly by name, and not through a string containing its name.

All the snippets must be valid on the submitter’s computer at the time of submission (as reported by SE), but may not rely on unusual local conditions like number of files in a directory, the exact date or time, or specific input from the user.

### Examples of valid snippets

3: `INT(LOG10(YEAR(TODAY())))` because it remains true in the foreseeable future
4: `CUBICROOT(LEN(CHARACTERSET()))` because a 256 letter character set is very common
8: `SQRT(SYSTEMTYPE())` because 64-bit systems are very common

### Examples of invalid snippets

5: `LEN(USERNAME())` because most people do not use “Admin” as login :-)
9: `LOG10(SYSTEMMEMORY())` because it only works on systems with exactly 1 GB of memory
42: `CODE("*")` because it contains a string/character literal

The result of each snippet must result in an actual number (value, int, float, etc.) that can be used for further calculations using the same language as the snippet, i.e not a text string representing that number.

Only character based languages allowed.

Score is total byte count of all the 12 snippets combined. Newlines separating the snippets are not counted in.

Note that the above rules may prevent some languages from participating, even if they are Turing complete.

### FAQ

**Q** Can the programs accept any input?
**A** Yes, but you may not just ask for input and enter the relevant number.

**Q** Are physical digits (non-data) digits allowed?
**A** Yes, e.g. `LOG10()`.

**Q** Do Symbols in Ruby count as literals?
**A** Yes.

**Q** Does score include newlines between each snippet?
**A** No.

**Q** Is TI-BASIC "character based" enough to be valid?
**A** Yes.

**Q** Do false and true count as number literals?
**A** No, they are acceptable.

**Q** Can we use a number literal to call a function if that's the only way and the number doesn't influence the output of the function?
**A** Yes, if that is the normal way to write code in your language.

**Q** My language assumes there is a \[something\] at the start of each program/expression. Must I include it, or should my snippets just work if placed in the middle of a program/expression?
**A** They should just work in the middle of a program/expression.

**Q** What about regex literals?
**A** Forbidden, except for languages that only do regexes.

**Q** Is one piece of code that could print all the specified numbers acceptable?
**A** No, they have to be separate and mutually independent.

**Q** May I assume a boilerplate like `int main() {}...` or equivalent?
**A** Yes.

**Q** What output datatypes are allowed?
**A** Any numeric datatype, like int, float, etc.

**Q** Do I need to print the result of each snippet?
**A** No, making the result available for subsequent use is enough.

**Q** Are pre-set variables allowed?
**A** Yes, and they become reset (if changed) for every snippet.

**Q** Are π and *e* considered number literals?
**A** No, you may use them.

**Q** May I return 4 and 2 in different cells for 42?
**A** No, they must be connected as one number.

**Q** Bytes or characters?
**A** Bytes, but you may choose any desired codepage.

**Q** May constant functions and preset variables like J's `9:`, Actually's `9`, and Pretzel's `9` be used?
**A** Yes, if the vocabulary is finite (19 for J, 10 for Actually and Pretzel).

# Answer
> 21 votes
# Hexagony, 13 bytes

```

1
2
3
4
5
6
7
8
9
10
42

```

Try it online!

In Hexagony, `0` through `9` are **functions** that multiply the current memory by 10, and then add the number represented by the function name. Therefore, the first snippet is empty as memories start off as `0`.

For example, if the current memory is `65`, executing the function `3` will make the current memory `653`.

(To downvoters: downvote all you want; I am ready.)

# Answer
> 51 votes
# Funciton, 1222 bytes

Apart from numeric literals, there are two ways I can produce a value (any value at all) in Funciton: stdin and lambda expressions. Stdin is a single box while a full lambda expression requires more syntax, so I’m going with stdin. However, while stdin could be anything, all of the following work regardless of what input is provided.

All of the library functions used here existed before the challenge was posted.

## 0 (40 bytes in UTF-16)

```
╔╗┌┐
║╟┤└┼┬┐
╚╝└─┘└┘

```

This uses the raw syntax for less-than. A value is never less than itself, so the result of this is 0.

## 1 (52 bytes in UTF-16)

```
╔╗┌─╖┌─╖
║╟┤⌑╟┤ɕ╟
╚╝╘═╝╘═╝

```

returns a lazy sequence containing a single element and `ɕ` counts the number of elements. (The lazy sequence is lazy enough that this snippet doesn’t actually evaluate stdin at all!)

## 2 (70 bytes in UTF-16)

```
╔╗┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟
╚╝╘═╝╘═╝╘═╝

```

= 2¹. `ʂ` generates all subsequences of a sequence, and thus turns a sequence of *n* elements into one with 2ⁿ.

## 3 (88 bytes in UTF-16)

```
╔╗┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟
╚╝╘═╝╘═╝╘═╝╘═╝

```

= 2 + 1.  increments a value by 1.

## 4 (88 bytes in UTF-16)

```
╔╗┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟
╚╝╘═╝╘═╝╘═╝╘═╝

```

= 2².

## 5 (106 bytes in UTF-16)

```
╔╗┌─╖┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟┤♯╟
╚╝╘═╝╘═╝╘═╝╘═╝╘═╝

```

= 4 + 1.

## 6 (106 bytes in UTF-16)

```
╔╗┌─╖┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟┤!╟
╚╝╘═╝╘═╝╘═╝╘═╝╘═╝

```

= 3 factorial.

## 7 (110 bytes in UTF-16)

```
┌───┐┌─╖┌─╖┌─╖╔╗
│┌─╖├┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤A╟┘╘═╝╘═╝╘═╝╚╝
 ╘╤╝

```

= A(2, 2) (Ackermann function).

## 8 (118 bytes in UTF-16)

```
┌────┐┌─╖┌─╖┌─╖╔╗
│┌──╖├┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤<<╟┘╘═╝╘═╝╘═╝╚╝
 ╘╤═╝

```

= 2 \<\< 2 (shift-left).

## 9 (128 bytes in UTF-16)

```
┌───┐┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤×╟┘╘═╝╘═╝╘═╝╘═╝╚╝
 ╘╤╝

```

= 3 × 3.

## 10 (146 bytes in UTF-16)

```
┌───┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤ʂ╟┤⌑╟╢║
└┤+╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝
 ╘╤╝

```

= 5 + 5.

## 42 (170 bytes in UTF-16)

```
┌──────┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖┌─╖├┤!╟┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤♯╟┤×╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝
 ╘═╝╘╤╝

```

= 6 × (6 + 1).

# Answer
> 26 votes
# JavaScript, ~~144~~ ~~141~~ ~~140~~ ~~138~~ ~~132~~ ~~125~~ 123 bytes

*With help from @edc65, @Sjoerd Job Postmus, @DocMax, @usandfriends, @Charlie Wynn and @Mwr247!*

```
result.textContent = [

+[]                          ,// 0  (3 bytes)
-~[]                         ,// 1  (4 bytes)
-~-~[]                       ,// 2  (6 bytes)
-~-~-~[]                     ,// 3  (8 bytes)
-~Math.PI                    ,// 4  (9 bytes)
-~-~Math.PI                  ,// 5  (11 bytes)
-~-~-~Math.PI                ,// 6  (13 bytes)
Date.length                  ,// 7  (11 bytes)
(a=-~-~[])<<a                ,// 8  (13 bytes) = (2 << 2)
(a=~Math.E)*a                ,// 9  (13 bytes) = (-3 * -3)
(a=-~-~[])<<a|a              ,// 10 (15 bytes) = ((2 << 2) | 2)
(a=Date.length)*--a           // 42 (19 bytes) = (7 * 6)

];
```

```
<pre id="result"></pre>
```

# Answer
> 16 votes
# Mouse-2002, ~~27~~ ~~26~~ ~~17~~ 14 bytes

The first snippets push 0-10, and `ZR+` pushes `25` then `17` and `25 17 + 42 =` is `1`.

```
A
B
C
D
E
F
G
H
I
J
K
ZR+

```

# Answer
> 15 votes
# CJam, ~~27~~ 24 bytes

```
U    e# 0
X    e# 1
Y    e# 2
Z    e# 3
Z)   e# 3 + 1
YZ+  e# 2 + 3
ZZ+  e# 3 + 3
AZ-  e# 10 - 3
YZ#  e# 2³
A(   e# 10 - 1
A    e# 10
EZ*  e# 14 × 3

```

*Thanks to @MartinBüttner for -1 byte!*

Try it online!

# Answer
> 12 votes
## Perl 5, ~~86~~ ~~75~~ ~~71~~ 66 bytes

All `^F`s are literal control characters (0x06 in ASCII), and hence a single byte.

```
$[          # array start index, defaults to 0                                  2
!$[         # !0 is 1                                                           3
$^F         # max sys file descriptor number, 2 on all sane systems             2
++$^F       # 2 + 1                                                             4
~-$]        # 5 - 1                                                             4
int$]       # $] is Perl version, int truncates                                 5
length$~    # 1 + 5                                                             8
~~exp$^F    # floor(e^2)                                                        7
$^F<<$^F    # 2 bitshift-right 2                                                6
-!$[+ord$/  # -1 + 10                                                          10
ord$/       # input record separator, newline by default, ord gets ASCII val    5
ord($"^$/)  # 32 + 10                                                          10

```

Thanks to msh210 for saving 11 bytes and Dom Hastings for 9 bytes!

# Answer
> 12 votes
# Brainfuck, 70 bytes

```
+
++
+++
++++
+++++
++++++
+++++++
++++++++
+++++++++
++++++++++
--[>+<++++++]>-

```

Each line must be run individually.

The first 10 are self explanatory: we increment the value of the cell via each plus.

The 42 is a lot more complex. It relies on the fact the most brainfuck interpreter use 8-bit cells, meaning that all operations on it are done modulo 256. The `--` sets cell #0 to 254. Then we enter a loop which runs until cell #0 is 0. Each iteration adds 1 to cell #1 and adds 6 to cell #0. This loops runs 43 times, so cell #1 is 43. Finally, we subtract 1 from cell #1 to make it 42.

I got the most efficient 42 ever found from http://esolangs.org/wiki/Brainfuck\_constants

# Answer
> 12 votes
## Darkness, 339 303 bytes

This is where Darkness really *shines*. Get it? :~)!

**Without printing** (replaced the space with `\s` in the first line since it won't show otherwise):

```
\s

█

██

███

████

█████

██████

███████

████████

█████████

██████████

██████████████████████████████████████████

```

**With printing:**

```
■

█■

██■

███■

████■

█████■

██████■

███████■

████████■

█████████■

██████████■

██████████████████████████████████████████■

```

Each line must be run individually in this case since the program terminates in the light (a space). However, it is possible to write this on one or several lines in the same program.

Regular darkness (█) increments a register by 1, and the ■ instruction (some sort of mini-darkness) outputs the contents of the register.

# Answer
> 10 votes
# Prolog, ~~113~~ 99 bytes

**Snippets:**

```
e-e              % 0.0
e/e              % 1.0
e/e+e/e          % 2.0
ceil(e)          % 3
ceil(pi)         % 4
ceil(e*e-e)      % 5
ceil(e+e)        % 6
floor(e*e)       % 7
ceil(e*e)        % 8
ceil(pi*e)       % 9
ceil(pi*pi)      % 10
ceil(e^e*e)      % 42

```

Combines the mathematical constants **e** and **pi** in different ways converted to int.

**Edit:** Saved 14 bytes by utilizing floats for 0-2.

# Answer
> 10 votes
## MATL, 30 bytes

```
O
l
H
I
K
Kl+
HI*
KYq
HK*
IH^
K:s
IH^:sI-

```

`H`, `I`, and `K` are predefined constants for 2, 3, and 4 (like `pi`). `O` and `l` are functions that returns a matrix of zeros (`O`) or ones (`l`), the default size is 1x1. `:` makes a vector, and `s` sums it, so `K:s` makes a vector from 1 to 4 and sums it to get 10. `Yq` is the n-th prime function, so `KYq` is the 4th prime, 7.

# Answer
> 9 votes
# C#, no usings, 234 bytes

```
new int()                       // 0
-~new int()                     // 1
-~-~new int()                   // 2
-~-~-~new int()                 // 3
-~-~-~-~new int()               // 4
-~-~-~-~-~new int()             // 5
-~-~-~-~-~-~new int()           // 6
-~-~-~-~-~-~-~new int()         // 7
-~-~-~-~-~-~-~-~new int()       // 8
(int)System.ConsoleKey.Tab      // 9
(int)System.TypeCode.UInt32     // 10
(int)System.ConsoleKey.Print    // 42

```

This is much more boring than I initially thought it was going to be. I had pretty varied ideas, such as `new[]{true}.Length` and `true.GetHashCode()` and `typeof(int).Name.Length` and `uint.MinValue` etc., but `new int()` beat them all.

# Answer
> 9 votes
# PHP, ~~157~~ ~~145~~ 91 bytes

First time posting on Code Golf, figured I'd give it a shot. I'll get better eventually :P If you see any obvious (to you) spots where I could save characters, let me know.

EDIT: Realized I didn't need the semicolons, since these are just snippets.

EDIT2: Thanks to Blackhole for many suggestions!

```
LC_ALL
DNS_A
~~M_E
~~M_PI
LOCK_NB
LC_TIME
LOG_INFO
INI_ALL
IMG_WBMP
SQL_DATE
SQL_TIME
LOG_INFO*INI_ALL

```

# Answer
> 9 votes
# PowerShell, 147 bytes

These use `+` to implicitly cast things to integers. The later numbers use Enums from the .Net Framework unerpinnings of PowerShell which happen to have the right values.

```
+$a                          #0, 3 bytes (unset vars are $null, +$null == 0)
+$?                          #1, 3 bytes (bool previous result, default $true, +$true == 1)
$?+$?                        #2, 5 bytes (same as #1, twice)
$?+$?+$?                     #3, 8 bytes (beats [Int][Math]::E)
$?+$?-shl$?                  #4, 11 bytes (-shl is shift-left)
$?+$?+$?+$?+$?               #5, 14 bytes
$?+$?+$?-shl$?               #6, 14 bytes (enum value, + casts to integer)
+[TypeCode]::Int16           #7, 18 bytes
$?+$?-shl$?+$?               #8, 14 bytes
+[consolekey]::tab           #9, 18 bytes
+[TypeCode]::UInt32          #10, 19 bytes
+[consolekey]::Print         #42, 20 bytes

#Total:                      147 bytes

```

---

* `-~-~-~` used in JavaScript, C# and PHP answers would be `- -bnot - -bnot - -bnot` in PowerShell.
* `x^y` exponentiation used in Perl answers, or `x**y` in Python or JavaScript ES7, would be `[Math]::Pow($x,$y)`
* constants *e* and *Pi* are the character-heavy `[Math]::E` and `[Math]::PI`

# Answer
> 9 votes
# Python 2, ~~191~~ ~~159~~ ~~158~~ ~~157~~ ~~156~~ ~~149~~ 146 bytes

My first submission ever, I hope I got everything right ! Based on the time I spent on this, I guess there's surely a better one for a few of them.

```
# 0 | Bytes : 5
int()

# 1 | Bytes : 5
+True

# 2 | Bytes : 6
-~True

# 3 | Bytes : 8
-~-~True

# 4 | Bytes : 10
-~-~-~True

# 5 | Bytes : 12
-~-~-~-~True

# 6 | Bytes : 14
-~-~-~-~-~True

# 7 | Bytes : 16
-~-~-~-~-~-~True

# 8 | Bytes : 15
a=True;a<<a+a+a

# 9 | Bytes : 19
a=True;(a<<a+a+a)+a

# 10 | Bytes : 20
int(`+True`+`int()`)

# 42 | Bytes : 16
~-len(`license`)
# Especially proud of this one !

Total byte count: 146

```

Many thanks to FryAmTheEggman !

# Answer
> 8 votes
# DC, 35 bytes

```
K
KZ
IZ
Iv
EI-
FI-
IZd*
IIZ/
Ivd+
IIv-
IIZ-
IKZ-
I
EdE++

```

To test the snippets append a `f` to print the stack and pass that string to `dc`:

```
$ echo 'EdE++f' | dc
42

```

# Answer
> 7 votes
## TI-BASIC, 41 bytes

0~10:

```
X
cosh(X
int(e
int(π
-int(-π
int(√(π³
int(π+π
int(e²
int(eπ
int(π²
Xmax

```

42:

```
int(π²/ecosh(π

```

In TI-BASIC, all uninitialized single-letter variables start at 0, and `Xmax` (the right window boundary of the graph screen) starts at 10.

The mathematical constant `π` is one byte, but `e` is two bytes.

# Answer
> 6 votes
# Python 2, ~~306~~ ~~275~~ 274 bytes

I used the fact that for any *x* (integer and not 0) the expression `x/x` equals 1 and played around with some bitwise operations.

I adjusted the snippets such that they still meet the requirements (thanks @nimi this saved me 24 bytes), but you have to manually test them. Here is the code and individual byte counts:

```
zero.py Bytes: 7
len({})
--------------------------
one.py  Bytes: 12
r=id(id)
r/r
--------------------------
two.py  Bytes: 17
r=id(id)
-(~r/r)
--------------------------
three.py    Bytes: 20
r=id(id)
-(~r/r)|r/r
--------------------------
four.py Bytes: 20
r=~id(id)/id(id)
r*r
--------------------------
five.py Bytes: 26
r=~id(id)/id(id)
(r*r)|r/r
--------------------------
six.py  Bytes: 25
r=~id(id)/id(id)
(r*r)|-r
--------------------------
seven.py    Bytes: 27
r=~id(id)/id(id)
-~(r*r|-r)
--------------------------
eight.py    Bytes: 24
r=-(~id(id)/id(id))
r<<r
--------------------------
nine.py Bytes: 29
r=-(~id(id)/id(id))
r-~(r<<r)
--------------------------
ten.py  Bytes: 31
r=~id(id)/id(id)
-r*((r*r)|r/r)
--------------------------
answer.py   Bytes: 37
r=-(~id(id)/id(id))
(r<<r*r)|(r<<r)|r
--------------------------
Total byte count: 274

```

# Answer
> 5 votes
# Math++, 92 bytes total

0 (1 bytes): `a`

1 (2 bytes):`!a`

2 (3 bytes):`_$e`

3 (4 bytes): `_$pi`

4 (7 bytes): `_$e+_$e`

5 (8 bytes): `_($e+$e)`

6 (9 bytes): `_$pi+_$pi`

7 (8 bytes): `_($e*$e)`

8 (9 bytes): `_($e*$pi)`

9 (10 bytes): `_($pi*$pi)`

10 (12 bytes): `_$e*_($e+$e)`

42 (19 bytes): `_($pi+$pi)*_($e*$e)`

# Answer
> 5 votes
## Javascript (Browser Env), ~~155~~ ~~136~~ 130 bytes

```
+[]
-~[]
-~-~[]
-~-~-~[]
-~-~-~-~[]
-~-~-~-~-~[]
-~-~-~[]<<-~[]
-~-~-~-~-~-~-~[]
-~[]<<-~-~-~[]
~(~[]+[]+-[])
-~[]+[]+-[]
-~(top+top.s).length // Requires browser environment

```

*Thanks to: <br>@Ismael Miguel: 155 -\> 136 -\> 130 bytes*

# Answer
> 5 votes
## Seriously, ~~39~~ 33 bytes

Stuff in parentheses is explanations:

```
 (single space, pushes size of stack, which is 0 at program start)
 u (space pushes 0, u adds 1 (1))
 ⌐ (space pushes 0, ⌐ adds 2 (2))
 u⌐ (space pushes 0, u adds 1 (1), ⌐ adds 2 (3))
 ⌐⌐ (space pushes 0, ⌐⌐ adds 2 twice (4))
 ⌐P (space pushes 0, ⌐ adds 2 (2), P pushes the 2nd prime (5))
Hl▓ (H pushes "Hello, World!", l pushes length (13), ▓ pushes pi(13) (6))
QlP (Q pushes "QlP", l pushes length (3), P pushes the 3rd prime (7))
Ql╙ (Q pushes "QlP", l pushes length (3), ╙ pushes 2**3 (8))
úl▓ (ú pushes the lowercase English alphabet, l pushes length (26), ▓ pushes pi(26) (9))
 u╤ (space pushes 0, u adds 1 (1), ╤ pushes 10**1 (10))
HlPD (H pushes "Hello, World!", l pushes length (13), P pushes the 13th prime (43), D subtracts 1 (42))

```

Hexdumps of programs:

```
20
2075
20a9
2075a9
20a9a9
20a950
486cb2
516c50
516cd3
a36cb2
2075d1
486c5044

```

Thanks to quintopia for 6 bytes!

# Answer
> 5 votes
# dc, 42 bytes

```
K
zz
OZ
zzz+
OZd*
OdZ/
zzzz*
Ozz+-
OdZ-
Oz-
O
Od+dz++

```

## Results

```
0
1
2
3
4
5
6
7
8
9
10
42

```

There aren't many ways to generate new numbers with dc. I use `O`: output base, initially 10; `K`: precision, initially 0; `z` stack depth, initially 0; `Z` significant digits of operand. We combine these with the usual arithmetic operators.

# Test program

```
#!/bin/bash

progs=(                                         \
    "K"                                         \
    "zz"                                        \
    "OZ"                                        \
    "zzz+"                                      \
    "OZd*"                                      \
    "OdZ/"                                      \
    "zzzz*"                                     \
    "Ozz+-"                                     \
    "OdZ-"                                      \
    "Oz-"                                       \
    "O"                                         \
    "Od+dz++"                                   \
)

a=0
results=()
for i in "${progs[@]}"
do
    results+=($(dc -e "${i}p"))
    (( a+=${#i} ))
done

echo "#dc, $a bytes"
echo
printf '    %s\n' "${progs[@]}"
echo
echo '##Results'
echo
printf '    %s\n' "${results[@]}"

```

# Answer
> 5 votes
# MS Excel formulas, ~~163~~ ~~151~~ ~~150~~ 143 bytes

Not exactly a programming language, but here it goes...

```
0:  -Z9                         (03 bytes)
1:  N(TRUE)                     (07 bytes)
2:  TYPE(T(Z9))                 (11 bytes)
3:  TRUNC(PI())                 (11 bytes)
4:  TYPE(TRUE)                  (10 bytes)
5:  ODD(PI())                   (09 bytes)
6:  FACT(PI())                  (10 bytes)
7:  ODD(PI()+PI())              (14 bytes)
8:  EVEN(PI()+PI())             (15 bytes)
9:  TRUNC(PI()*PI())            (16 bytes)
10: EVEN(PI()*PI())             (15 bytes)
42: EVEN(CODE(-PI())-PI())      (22 bytes)

```

`PI()` is used in most cases as it is the shorter way (that I am aware of) to introduce a numeric value without using a number or string literal. `N` converts various things (incl. booleans) to numbers, and `T` converts various things to text. `TYPE` returns 2 for a text argument and 4 for a boolean argument. `TRUNC` discards fractional part (i.e. rounds positive numbers down), `EVEN` rounds up to the next even number, and `ODD` rounds up to the next odd number. `CODE(-PI())` is the ASCII code of the first character of the conversion to text of -π, i.e. 45 (for "-").

EDIT: Removed equal signs from the byte count (-12!) - as pointed out by Nᴮᶻ in the comments, they are not supposed to be included.

EDIT 2: Assuming the rest of the worksheet is empty, it is possible to use a reference to an empty cell as zero (again, suggested by Nᴮᶻ) provided that we include a minus sign (or use it in other numeric expression) to resolve type ambiguity.

# Answer
> 4 votes
# Japt, ~~34~~ ~~33~~ 30 bytes

*1 byte saved thanks to @ThomasKwa*

```
T
°T
C-A
D-A
E-A
F-A
G-A
°G-A
Iq
´A
A
H+A

```

Here's what each of the different chars means:

```
T    0
A    10
B    11
C    12
D    13
E    14
F    15
G    16
H    32
I    64
q    sqrt on numbers
°    ++
´    --

```

# Answer
> 4 votes
## Mathematica, 101 bytes

```
a-a
a/a
⌊E⌋
⌈E⌉
⌈π⌉
⌊E+E⌋
⌈E+E⌉
⌊E*E⌋
⌈E*E⌉
⌈E*π⌉
⌈π*π⌉
⌊π*π^π/E⌋

```

I'm pretty sure some of these are suboptimal. Those rounding brackets are really expensive.

For consistency, the first two could also be `E-E` and `E/E` of course, but I thought it's quite nifty to get `0` and `1` from a computation with undefined variables.

# Answer
> 4 votes
## Dyalog APL, ~~59~~ 52 bytes

*-7 bytes by @NBZ*

I wasn't about to let one of @NBZ's questions go without an APL answer!

```
⍴⍬            0
⎕IO           1
⍴⎕SD          2
⎕WX           3
⍴⎕AI          4
⌈⍟⎕PW         5
⌊⍟⎕FR         6
⍴⎕TS          7
+⍨⍴⎕AI        8
⌊○○⎕IO        9; floor(pi^2 times ⎕IO)
⍴⎕D           10
⍎⌽⍕⌈*○≢#    42

```

In the last snippet, by NBZ, `≢#` equals 1. ceil(e^(pi\*1)) is calculated as 24, whose digits are then swapped.

Constants used:

* , is the empty numeric one-dimensional vector. Therefore, its shape `⍴⍬` is 0.
* `#` is a special vector of length 1.
* `⎕IO` (index origin) starts at 1.
* `⎕AV`, the character set, is of length 256.
* `⎕PW`, the print width, is 79 characters.
* `⎕WX`, window expose (whatever that is) is 3.
* `⎕FR`, the float representation, is 645. I have no idea what this is either.
* `⎕D`, "digits", is '0123456789'.
* `⎕TS`, timestamp, has seven elements: Year, month, day, hr, min, sec, ms.
* `⎕SD`, screen dimensions, has two elements: width and height.
* `⎕AI`, account info, has four elements. I don't know what they are.

# Answer
> 4 votes
# Marbelous, 98 bytes

Not terribly exciting, it relies on the `?n` devices which turn any marble into a random value in the range 0..n (inclusive) a side effect of this is that `?0` turns any marble into a 0 regardless of input. I think the use of literals is permitted because the value does not affect the outcome and there is no other way to call a function once in Marbelous.

0:

```
00  # A hexadicemal literal: value 0
?0  # Turn any marble into a random value from the range 0..0 (inclusive)

```

1:

```
00
?0
+1  # increment by one

```

...

9:

```
00
?0
+9

```

10:

```
00
?0
+A  # increment by 10

```

42:

```
00
?0
+L  # increment by 21
+L

```

# Answer
> 4 votes
# DUP, 68 bytes

```
[
 [
  [
[)]!
[ )]!
[  )]!
[)~_]!
[ )~_]!
[  )~_]!
[   )~_]!
[)$+]!
[ )$+~_$+]!

```

`Try it here.`

There are a LOT of ways to do this, but I'm abusing the return stack for this one.

# Explanation

To fully figure this out, you need to understand DUP's behavior regarding lambdas. Instead of pushing the lambda itself to the stack, it actually pushes the current IP to the stack when the lambda is detected. That can explain the first 3 snippets, which involve lambdas.

The next snippets use the return stack. When `!` is executed, the current IP is pushed to the return stack, and the top of the stack is set as the new IP to start lambda execution. `)` pops a number from the return stack onto the data stack.

That's pretty much enough to explain the rest of the snippets. If you still don't get it, keep in mind that the `Step` button is quite handy!

# Answer
> 4 votes
## \>\<\>, 86 bytes

* 0: `ln;`
* 1: `lln;`
* 2: `llln;`
* 3: `lll+n;`
* 4: `lll:+n;`
* 5: `llll+n;`
* 6: `llll++n;` or `llll:+n;`
* 7: `lllll+n;`
* 8: `lllll:+n;`
* 9: `lllll++n;` or `llllll+n;`
* 10: `llll+:+n;` or `lll:l+*n;`
* 42: `llll*ll+*n;`

Relies on stack size to get its literals.

# Answer
> 4 votes
# 05AB1E, ~~40~~ ~~38~~ 24 bytes

```
¾
X
Y
XÌ
Y·
T;
T;>
T;Ì
TÍ
T<
T
žwT+

```
* Push counter\_variable
* Push 1
* Push 2
* Push 1+2
* Push 2\*2
* Push 10/2
* Push (10/2)+1
* Push (10/2)+2
* Push 10-2
* Push 10-1
* Push 10
* Push 32, 10, add

# Answer
> 3 votes
## Pyth, ~~35~~ ~~34~~ 33 bytes

*-1 byte by @Mimarik*

There are a number of possibilities for some programs.

**0, 1 byte**

```
Z

```

**1, 2 bytes**

```
hZ
!Z

```

**2, 3 bytes**

```
hhZ
eCG
eCd
lyd
lyb
lyN

```

**3, 3 bytes**

```
l`d

```

**4, 3 bytes**

```
l`b
eCN

```

**5, 4 bytes**

```
hl`b
telG

```

**6, 3 bytes**

```
elG

```

**7, 4 bytes**

```
tttT
helG

```

**8, 3 bytes**

```
ttT

```

**9, 2 bytes**

```
tT

```

**10, 1 byte**

```
T

```

**42, 4 bytes**

```
yhyT

```

All of these involve either basic double (`y`), +1 (`h`) and -1 (`t`) commands, or `l` (length of a string). The Z variable is initialized to zero.

For 5, `b` is initialized to a newline character. Backtick gives `"\n"` (including the quotes, and the length of that string is 4.

Try them here!

# Answer
> 3 votes
## , 123 bytes

```
+!pi                #  0  -   4 bytes
+TRUE               #  1  -   5 bytes
nchar(NA)           #  2  -   9 bytes
floor(pi)           #  3  -   9 bytes
cars$d[pi]          #  4  -  10 bytes
ncol(CO2)           #  5  -   9 bytes
nrow(BOD)           #  6  -   9 bytes
cars$s[pi]          #  7  -  10 bytes
sum(dim(BOD))       #  8  -  13 bytes
floor(pi*pi)        #  9  -  12 bytes
ceiling(pi*pi)      # 10  -  14 bytes
nrow(CO2)/nchar(NA) # 42  -  19 bytes
                    # Total 123 bytes

```

# Answer
> 3 votes
## R, ~~166~~ 165 bytes

I made a PI based answer

```
pi-pi                         # 0
pi/pi                         # 1
(pi+pi)/pi                    # 2
floor(pi)                     # 3
ceiling(pi)                   # 4
ceiling(pi)+pi/pi             # 5
floor(pi+pi)                  # 6
ceiling(pi+pi)                # 7
floor(pi*pi)-pi/pi            # 8
floor(pi*pi)                  # 9
ceiling(pi*pi)                # 10
ceiling(pi^pi+pi+sqrt(pi))    # 42

```

# Answer
> 3 votes
# 80386 machine code, 73 bytes

Hexdump:

```
33 c0
33 c0 40
33 c0 40 40
33 c0 40 40 40
33 c0 40 40 40 40
33 c0 40 8d 04 80
33 c0 40 8d 04 80 40
33 c0 40 8d 04 80 40 40
33 c0 40 8d 04 c0 48
33 c0 40 8d 04 c0
33 c0 40 8d 04 c0 40
33 c0 40 8d 04 c0 8d 04 80 48 48 48

```

The snippets calculate the required value in the `eax` register, suitable as a return value from a function.

I used various combinations of the following instructions:

```
xor eax, eax         (33 c0)    eax = 0
inc eax              (40)       eax = eax + 1
dec eax              (48)       eax = eax - 1
lea eax, [eax+eax*4] (8d 04 80) eax = eax * 5
lea eax, [eax+eax*8] (8d 04 c0) eax = eax * 9

```

The numbers here are too small to use all the possibilities of the instruction set - the only noteworthy thing here is the easy multiplication by 5 and 9. For example, here is a 13-byte snippet whose result is 2016:

```
33 c0      xor eax, eax             eax = 0
40         inc eax                  eax = 1
8d 0c c0   lea ecx, [eax+eax*8]     ecx = 9
8d 04 89   lea eax, [ecx+ecx*4]     eax = 45
f7 e0      mul eax                  eax = 2025
2b c1      sub eax, ecx             eax = 2016

```

# Answer
> 3 votes
# Visual Basic for Applications, 68 bytes

VBA has a lot of builtin constants and public enums. I opted not to use any external or MS Office-specific library - only base VBA:

```
-x                     '=0  (2 bytes)
x^x                    '=1  (3 bytes)
vbGet                  '=2  (5 bytes)
vbLong                 '=3  (6 bytes)
vbLet                  '=4  (5 bytes)
vbDouble               '=5  (8 bytes)
vbYes                  '=6  (5 bytes)
vbNo                   '=7  (4 bytes)
vbSet                  '=8  (5 bytes)
vbObject               '=9  (8 bytes)
vbError                '=10 (7 bytes)
vbKeyPrint             '=42 (10 bytes)

```

Total = 68 bytes. Notice that by default, undeclared variables (such as `x` above) are all set to blank Variants, that may be interpreted, depending on context, as `0` or as an empty string. However, both operators `-` and `^` force it to be numeric. Also, in VBA, `0^0` is evaluated to 1 (instead of generating an error as one might expect). I'll also post an answer without constants.

# Answer
> 3 votes
# Jelly, 31

```
<blank>
‘
‘‘
‘‘‘
‘‘²
‘‘²‘
‘‘‘Ḥ
⁴H’
⁴H
‘‘‘²
⁵
⁴Ḥ⁵+

```

## Explanation

0: Outputs 0 by default

1. Increment
2. Increment twice
3. Increment thrice
4. Increment twice and square
5. Increment twice, square, and increment
6. Increment thrice and double
7. Halve sixteen and decrement
8. Halve sixteen
9. Increment thrice and square
10. Ten

42: Double sixteen and add ten

# Answer
> 3 votes
# Haskell, ~~212 210 198 196 190 187~~ 134 bytes

Edit: After reading in the FAQ that using `pi` is allowed, throwing everything away and doing it all using `pi`only saves a lot of bytes.

```
pi-pi                     -- 0.0,  5 bytes
pi/pi                     -- 1.0,  5 bytes
succ$pi/pi                -- 2.0, 10 bytes
floor pi                  --   3,  8 bytes
ceiling pi                --   4, 10 bytes
succ.ceiling$pi           --   5, 15 bytes
floor$pi+pi               --   6, 11 bytes
ceiling$pi+pi             --   7, 13 bytes
pred.floor$pi*pi          --   8, 16 bytes
floor$pi*pi               --   9, 11 bytes
round$pi*pi               --  10, 11 bytes
floor$pi**pi+pi+pi        --  42, 18 bytes

```

However, I still like the old approach more as using a number to generate other numbers feels a bit like cheating.

```
sum[]                     --  0,  5 bytes
length[LT]                --  1, 10 bytes
fromEnum GT               --  2, 11 bytes
length[LT ..]             --  3, 13 bytes
length$show[()]           --  4, 15 bytes
length.show$False         --  5, 17 bytes
length$show[True]         --  6, 17 bytes
length.show$Left()        --  7, 18 bytes
length.show$Right()       --  8, 19 bytes
length$show[Just[]]       --  9, 19 bytes
length$show[LT ..]        -- 10, 18 bytes
fromEnum.succ.last$show() -- 42, 25 bytes

```

`LT`,`EQ` and `GT` are the values of the `Ordering` Type. As `Ordering` is an instance of `Enum`, `fromEnum GT` yields `2` and `[LT ..]` creates the list `[LT,EQ,GT]`. `show` converts all instances of the `Show` type class to strings.

Bonus:
42 in 42 bytes: `length.show$Just$[LT ..]>>[EQ,GT]>>[GT,LT]`
How long is nothing? `length Nothing`

Saved 3 bytes thanks to nimi and 3 bytes thanks to xnor.

# Answer
> 3 votes
# PHP, ~~38~~ 37 bytes

Note: uses IBM-850 encoding.

```
+_          #0
+~╬         #1
+~═         #2
+~╠         #3
+~╦         #4
+~╩         #5
+~╔         #6
+~╚         #7
+~Ã         #8
+~ã         #9
+~╬¤        #10
+~╦═        #42

```

# Explanation

Undefined constants in PHP have their name as default value. The resulting string is then negated to result in `"0"`, `"42"` etc. Finally, it's converted to integer using the leading `+`.

# Tweaks

* Saved a byte by exploiting the fact that converting any string results in `0` when converted to `int`, except when it matches `/^[0-9.]+/`

# Answer
> 2 votes
# D1ffe7e45e, 112

```
0
02
020
0202
02020
020202
0202020
02020202
020202020
0202020202
02020202020
202020202020202020202020202020202020202020

```

Each line is a different snippet.

The numbers in the program don't count as number literals since they're only used as commands.

The final one can definitely be golfed more.

EDIT: I got the interpreter working and all snippets work. If you'd like to test if yourself, add `0f0f` to the end of the snippet so the program terminates.

# Answer
> 2 votes
# O, 36 bytes

```
l
Nl
CA-
DA-
EA-
FA-
FA-)
A(((
A((
A(
A
A.+.+))

```

Mostly finding the difference of hex letters,

`CA-` = `13-11` = `2` `DA-` = `14-10` = `3`

`(` and `)` decrement and increment respectively,

`A((` = `10-1-1` = 8

`.+` duplicates the top of the stack and adds it together

```
A.+.+))
10.+.+))
20.+))
40))
42

```

The first two get the length of the stack (`l`), which zero, or one when a blank CodeBlock is pushed to the stack (`N`).

# Answer
> 2 votes
# Pyth, 50 40 bytes

```
Z
hZ
hhZ
hhhZ
hhhhZ
hhhhhZ
ttttT
tttT
ttT
tT
T
yhyT

```

In Pyth, Z=0 and T=10. h is head, which means the next variable + 1. (e.g. `hhZ` == 2). t is tail, which means the next variable - 1 (e.g. `tttT` == 7). The last line is the fanciest: we essentially do double(1 + double(10)).

Try it out here!

Thomas Kwa has golfed a superior solution.

# Answer
> 2 votes
# Javascript, 159 chars

No any variables

Any line between ``` is a code snippet. The whole code is a test. It returns an array `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 42]`. If returning string "42" instead of number 42 is ok, code can be made 3 schars less (remove `|[]`).

```
`
+[]
-~[]
!![]+!![]
~~Math.PI
-~Math.PI
-~Math.PI|!![]
Math.PI<<!![]
Math.PI<<!![]|!![]
!![]<<Math.PI
Math.PI*Math.PI^[]
(-~Math.PI|!![])<<!![]
-~Math.PI+[]+(!![]+!![])|[]
`.split('\n').filter(Boolean).map(eval)

```

# Answer
> 2 votes
## k4, 41 bytes

Most of this is a cheap hack—every builtin function in `k` has an internal id number, and `.` retrieves them. Entries of the form `.(x)` are implemented thus; others are commented.

A question: are we supposed to *generate* the numbers or *print* them? E.g., for zero, should we return some numeric type containing zero as a value, or should we display the exact string `0`? I ask because in there are several default settings that could be useful here, but they all have (32-bit) integer type, which means that in recent (3.x) versions of q/k4, they are displayed on the console with a type suffix of `i` appended. The following assumes `0i` is a valid form of `0`, but has alternatives in the comments.

```
\p     /  0: the default network port (none); alternatively, #(), the count of the empty list
#`     /  1: the count of a null symbol atom; alternatively, if this is considered a character literal, use .(+)
\W     /  2: the default starting day of the week (monday), counting from saturday as 0; alternatively, .(-)
.(*)   /  3
.(%)   /  4
#!`    /  5: the number of namespaces loaded by default (works in 3.2 or 3.3; in earlier versions, use this as 4 and .(&) as 5)
.(|)   /  6
\P     /  7: the default numeric precision (7 significant figures); alternatively, #.j, the count of the .j namespace; alternatively, .(^)
.(=)   /  8
.(<)   /  9
.(>)   / 10
.(var) / 42

```

# Answer
> 2 votes
# C, 202 bytes

```
enum{a}; // 0, 8

enum{a,b}; // 1, 10

enum{a,b,c}; // 2, 12

enum{a,b,c,d}; // 3, 14

enum{a,b,c,d,e}; // 4, 16

enum{a,b,c,d,e,f}; // 5, 18

enum{a,b,c,d};c*d; // 6, 18

enum{a,b,c,d,e};d+e; // 7, 20

enum{a,b,c};c<<c; // 8, 17

enum{a,b,c};b+(c<<c); //  9, 21

enum{a,b,c};c+(c<<c); // 10, 21

enum{a,b,c,d,e,f};c*f*e+c; // 42, 26

```

**Printed Version, 730 bytes**

```
enum{a,b,c,d,e};char m[d]={(d<<e)+a,a};main(){printf(m);} // 0, 57

enum{a,b,c,d,e};char m[d]={(d<<e)+b,a};main(){printf(m);} // 1, 57

enum{a,b,c,d,e};char m[d]={(d<<e)+c,a};main(){printf(m);} // 2, 57

enum{a,b,c,d,e};char m[d]={(d<<e)+d,a};main(){printf(m);} // 3, 57

enum{a,b,c,d,e};char m[d]={(d<<e)+e,a};main(){printf(m);} // 4, 57

enum{a,b,c,d,e};char m[d]={(d<<e)+e+b,a};main(){printf(m);} // 5, 59

enum{a,b,c,d,e};char m[d]={(d<<e)+e+c,a};main(){printf(m);} // 6, 59

enum{a,b,c,d,e};char m[d]={(d<<e)+e+d,a};main(){printf(m);} // 7, 59

enum{a,b,c,d,e};char m[d]={(d<<e)+e+e,a};main(){printf(m);} // 8, 59

enum{a,b,c,d,e,f};char m[d]={(d<<e)+f+e,a};main(){printf(m);} // 9, 61

enum{a,b,c,d,e,f,g,h,i,j,k};char m[d]={k*d+h,k*k,a};main(){printf(m,k);} // 10, 72

enum{a,b,c,d,e,f,g,h,i,j,k};char m[d]={k*d+h,k*k,a};main(){printf(m,k*e+c);} // 42, 76

```

# Answer
> 2 votes
# , 36 bytes (12 chars)

```
Ḁ
ḁ
Ḃ
ḃ
Ḅ
ḅ
Ḇ
ḇ
Ḉ
ḉ
Ḋ
Ḫ

```

`Try it here (test-suite-style, Firefox only).`

There are variables for numbers from 0-256. (One of the benefits of choosing from UTF-8 is that you can dedicate a whole charset of 256 characters just to this kind of stuff. (Of course, byte count is a side effect.))

# Answer
> 2 votes
# J, ~~46~~ ~~43~~ 42 bytes

Thanks to Nᴮᶻ for the help and exploration!

```
%_         NB. Inverse of infinity
_.         NB. Indeterminate value, evaluates to 1
2:_
3:_
4:_
5:_
6:_
7:_
8:_
9:_
+~5:_      NB. verb magic
(7:*6:)_   NB. 7 * 6

```

Here are some other programs:

```
(number): (representation)
1:  *_             NB. signum of infinity                                          same bytes
1:  #a:            NB. The tally of the Ace/Empty box                              +1 byte
1:  1:_            NB. The constant function with infinity;                        +1 byte
2:  #_`_           NB. The tally of infinity gerund-ed with itself                 +1 byte
2:  #_,_           NB. (same)                                                      +1 byte
2:  #_;_           NB. (same)                                                      +1 byte
42: (*:+])6:_      NB. verb magic / 6 squared plus 6                               +1 byte
42: +:<.o.7:_      NB. double floor pi times 7                                     +1 byte
42: <.(#a.)%6:_    NB. Tally of alphabet (256) divided by 6 (6:_) floored (<.);    +3 bytes
42: a+*~(a=:6:_)   NB. 6 squared plus 6.                                           +4 bytes
42: (a=:6:_)+:*a   NB. 6 squared plus 6.                                           +4 bytes
42: #C.>.%:^@^2:_  NB. I'm not entirely sure how this works                        +5 bytes

```

# Answer
> 2 votes
# Perl 6, ~~84~~ 81 bytes

```
+$           #  0
++$          #  1
-+^++$       #  2
-+^e         #  3
-+^π         #  4
1+-+^π       #  5
floor τ      #  6
-+^τ         #  7
floor e*π    #  8
floor π*π    #  9
-+^(τ+e)     # 10
-+^(e**e*e)  # 42

```

**Constants used**

```
> e
2.71828182845905
> π
3.14159265358979
> τ
6.28318530717959

```

**An attempt at some explanation**

#0: `$` is an anonymous state variable, the + coerces it to a number, and by default its value is 0
#1: `++$` increases the state var by 1, giving us 1
#2: `+^` as a prefix is the Integer bitwise negation operator, use that with `++$` (1) and we get -2, use `-` to negate it and give 2
#3: Use `+^` with `e`, which is coerced to `Int`, giving -3 which then gets negated with `-`
#4: Same as #3 but with `π`
#5: Same as #4 but add 1
I think the rest are easy to follow with the above bits explained.

# Answer
> 2 votes
# Visual Basic for Applications, no named constants, 134 bytes

That's tougher:

```
-x                     '=0  (2 bytes)
x^x                    '=1  (3 bytes)
x^x+x^x                '=2  (7 bytes)
x^x+x^x+x^x            '=3  (11 bytes)
Len(Year(x))           '=4  (12 bytes)
Len(Year(x)&-x)        '=5  (15 bytes)
Day(x)Mod Month(x)     '=6  (18 bytes)
Len(Time())-x^x        '=7  (15 bytes)
Len(Time())            '=8  (11 bytes)
Len(Time()&-x)         '=9  (14 bytes)
Len(Date())            '=10 (11 bytes)
Day(x)+Month(x)        '=42 (15 bytes)

```

Total = 134 bytes. Again, `-` and `^` force undeclared variables (Variants) to be treated as numeric, and in VBA `0^0` evals to 1.

The concatenation operator force numbers to string form, so `-x` is 0 and `&-x` is `& "0"`.

For `Day`, `Month` and `Year` functions, zero corresponds to december 31, 1899.

I also used the fact that (at least for most locales), VBA date strings have 10 characters and time strings have eight...

Thanks! This was a funny challenge.

# Answer
> 2 votes
## Hoon, 89 bytes

```
`@`&
`@`|
+(|)
+:!=(+)
+:!=(-<)
+:!=(->)
+:!=(+<)
+:!=(+>)
+:!=(-<-)
+:!=(-<+)
+:!=(->-)
+:!=(->->-)

```

0 is just "yes" (0) casted to an atom

1 is just "no" (1) casted to an atom

2 is incremented "no" - `.+` automatically casts to an atom, so no need for `@`

3 - 42 are the fun ones: It's using the `!=` rune, which compiles an arbitrary Hoon expression to Nock. In this case, it's compiling axis navigation syntax into the Nock expression `[0 axis]`, which I then take the tail of with `+:expr`.

In Hoon, all variable accesses are actually just indexing into a binary tree, and it allows you to index manually as well. The syntax is alternating sets of `-`/`+` and `<`/`>`, each one being head/tails for the current node. I also use `+axis`, which is a bit shorter for 8, 9, and 42.

# Answer
> 2 votes
# Haskell, 295 bytes

0: `length[]`
1: `length[()]`
2: `length[(),()]`
3: `length[(),(),()]`
4: `length[(),(),(),()]`
5: `length[(),(),(),(),()]`
6: `length[(),(),(),(),(),()]`
7: `length[(),(),(),(),(),(),()]`
8: `length[(),(),(),(),(),(),(),()]`
9: `length[(),(),()]*length[(),(),()]`
10: `length[(),()]*length[(),(),(),(),()]`
42: `length[(),(),(),(),(),()]*length[(),(),(),(),(),(),()]`

# Answer
> 2 votes
# R, 100 bytes

Copied the solutions for 6 and 7 from @MiloChen here.

```
+F                   # | 0     | 2 bytes
+T                   # | 1     | 2 bytes
T+T                  # | 2     | 3 bytes
T+T+T                # | 3     | 5 bytes
T+T+T+T              # | 4     | 7 bytes
T+T+T+T+T            # | 5     | 9 bytes
nrow(BOD)            # | 6     | 9 bytes
cars$s[pi]           # | 7     | 10 bytes
cars$s[pi]+T         # | 8     | 12 bytes
(pi*pi)%/%T          # | 9     | 11 bytes
(pi*pi)%/%T+T        # | 10    | 13 bytes
(pi^pi+pi+pi)%/%T    # | 42    | 17 bytes
                     # | total | 100 bytes

```

This saves some bytes compared to the 123 and 165 solutions.

# Answer
> 2 votes
# Jolf, 26 bytes

```
<empty>
lέ
lq
mfπ
Uά
½t
mfτ
mΓCt
wwt
wt
t
mQ

```

Okay, so I have a 42-builtin. I'm obsessed with that number. Also for forty-two, `lm,t`: the length of the integer partitions of ten.

## Explanations

The empty program is a truth machine, and, since given no input, just output's a zero.

is the length of a tab, i.e., 1.

`lq` is the length of the source code, i.e., 2.

`mfπ` is the floor of pi, i.e., 3.

is the square root of 16, i.e., 4.

`½t` is half ten, i.e., 5.

`mfτ` is the floor of tau (i.e. twice pi), i.e., 6

`mΓCt` is the length of the collatz sequence beginning with ten, i.e. `7`.

`wwt` is `10-1-1`, i.e., 8.

`wt` is `10-1`, i.e., 9.

`t` is 10.

`mQ` is the builtin for 42.

---

# Alternate solution

Except for `0` and `10`, a solution with `@<char with charcode value of N>` would be golfier solution for `N`, however, even though it doesn't use any literals (it actually reads the source code's next character), it isn't in the spirit of the challenge. This would tally 20 bytes.

# Answer
> 2 votes
## Ruby, 194 bytes

```
[]<=>[]
[[]].size
[[],[]].size
Dir.name.size
Hash.name.size
Float.name.size
Method.name.size
Integer.name.size
NilClass.name.size
TrueClass.name.size
FalseClass.name.size
Integer.name.size*Method.name.size

```

# Answer
> 2 votes
## Perl6 (~~117~~ 112) no state

```
e-e
e/e
e.floor
e.round
pi.ceiling
floor e+e
tau.floor
tau.ceiling
floor pi*e
floor pi*pi
round pi*pi
tau.floor*tau.ceiling

```

# Answer
> 2 votes
## BASH, 318 bytes

0 to 3 are exit code, other ones are stored in A

bytes count is split as follow :2-5-5-26-23-32-26-38-26-33-32-70

```
#0
ls
#1
cd \\
#2
ls \\
#3
cd \\
A=$?
A=$(($A+$A+$A))
#4
ls \\
A=$?
A=$(($A*$A))
#5
cd \\
A=$?
A=$(($A+$A+$A+$A+$A))
#6
ls \\
A=$?
A=$(($A+$A+$A))
#7
cd \\
A=$?
A=$(($A+$A+$A+$A+$A+$A+$A))
#8
ls \\
A=$?
A=$(($A*$A*$A))
#9
A=$?
A=$(($A+$A+$A))
#10
ls \\
A=$?
A=$(($A+$A+$A+$A+$A))
#42
@
A=$?
cd \\
B=$?
cd \\
C=$?
C=$(($C+$C+$C))
B=$(($A-$B))
A=$(($B/$C))

```

7 is more than probably golfable a bit more, as is 42

# Answer
> 2 votes
## Racket 205 bytes

```
(- pi pi)
(/ pi pi)
(/(+ pi pi)pi)
(floor pi)
(ceiling pi)
(sub1(floor(+ pi pi)))
(floor(+ pi pi))
(ceiling(+ pi pi))
(floor(sub1(* pi pi)))
(floor(* pi pi))
(ceiling(* pi pi))
(floor(+ pi pi(expt pi pi)))

```

Output:

```
0.0
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
42.0

```

# Answer
> 2 votes
# Haskell, 133 bytes

Pi-based, three floating point answers with the rest being integers:

```
 0: (5)  pi-pi
 1: (5)  pi/pi
 2: (10) (pi+pi)/pi
 3: (8)  round pi
 4: (10) ceiling pi
 5: (15) succ.ceiling$pi
 6: (11) floor$pi+pi
 7: (13) ceiling$pi+pi
 8: (16) floor$cosh pi-pi
 9: (11) floor$pi*pi
10: (11) round$pi*pi
42: (18) floor$pi**pi+pi+pi

```

# Answer
> 2 votes
## QBIC, 14 bytes

Thank you @Adám, for clarifying part of the rules. Brought the byecount down to 14.

```
a
q
r
s
t
u
v
w
x
y
z
v*w

```

All lower-case letters are numerical variables in QBIC, which default to 0. Exceptions are the letters q-z, which get initialised to 1-10. 42 is simply 6\*7.

# Answer
> 2 votes
# Processing, ~~65~~ 44 bytes

```
X
Y
Z
HSB
Z*Z
LINES
HSB*Z
TAB-Z
MITER
X+TAB
-~TAB
BOX+Y

```

### Explanation

Using the hint from the question, I decided to use Processing constants to produce these numbers. These constants contain a numerical value. So to gather them, I used `PConstants.java`.

Here is the list of all the constants I used:

```
X      == 0
Y      == 1
Z      == 2
HSB    == 3
LINES  == 5
MITER  == 8
TAB    == 9 (char)
BOX    == 41

```

After this, all that was left for me to do is to choose the combinations of these constants that produce the numbers 1 to 10 and 42. Finally, I ended up with these:

```
println(X);//0
println(Y);//1
println(Z);//2
println(HSB);//3
println(Z*Z);//2 * 2 = 4
println(LINES);//5
println(HSB*Z);//3 * 2 = 6
println(TAB-Z);//9 - 2 = 7
println(MITER);//8
println(X+TAB);//0 + 9 = 9
println(-~TAB);//-~9 = 10
println(BOX+Y);//41 + 1 = 42

```

Several notes:

`TAB` has a char value of `9`, meaning that if I print `TAB`, I print a literal tab. So to convert it to an int, I just add `0` to it.

And that's it!

### Edit

I discovered PConstants.java. It appears to contain all of the constants that exist in Processing. All that research I did is on the Processing Reference is not needed anymore. Time to cut down on the bytes :)

# Answer
> 2 votes
# Elixir, 267 bytes

Elixir's syntax doesn't exactly lend itself to golfing, and its strong typing makes this pretty hard too.

```
length []                                             # 0
length [[]]                                           # 1
length [[],[]]                                        # 2
floor :math.pi                                        # 3  (:math is technically a literal, but Elixir's atoms are neccessary to access many modules)
ceil :math.pi                                         # 4
length [[],[],[],[],[]]                               # 5
floor :math.pi+:math.pi                               # 6
ceil :math.pi+:math.pi                                # 7
(ceil :math.pi+:math.pi)+length [[]]                  # 8
floor :math.pi*:math.pi                               # 9
length(Atom.to_charlist URI)                          # 10 (URI is an alias to Elixir.URI which is 9 characters long)
(length(Atom.to_charlist Version))*(floor :math.pi)   # 42 (length of "Elixir.Version" times 3)

```

Try it online!

# Answer
> 2 votes
# Deadfish / Deadfish~, Score: 62 / 56

0: `o`

1: `io`

2: `iio`

3: `iiio`

4: `iiso`

5: `iisio`

6: `iisiio`

7: `iiisddo` or `{i}dddo` (Deadfish~ only)

8: `iiisdo` or `{i}ddo` (Deadfish~ only)

9: `iiiso` or `{i}do` (Deadfish~ only)

10: `iiisio` (Deadfish) or `{i}o` (Deadfish~)

42: `iisiisiiiiiio` (Deadfish) or `{iiii}iio` (Deadfish~)

Amazingly, up to 9, vanilla deadfish is as efficient! I put these together because they're almost identical.

# Answer
> 2 votes
# Uiua, ~~37~~ 36 bytes

```
⌊⚂
⌊η
⌈η
⌊π
⌈π
⌈+πη
⌊τ
⌈τ
⌈+τη
⌊×ππ
⌈×ππ
⌊+τⁿππ

```

Try it!

~~I will be curious to see if anyone has any two-byters for 0. I found a dozen three-byters.~~ Found one!

```
⌊⚂      # floor of random float in [0,1)
⌊η      # floor of eta (number of radians in a quarter circle)
⌈η      # ceiling of eta
⌊π      # floor of pi (ratio of circle's circumference to diameter)
⌈π      # ceiling of pi
⌈+πη    # ceiling of eta plus pi
⌊τ      # floor of tau (ratio of circle's circumference to radius)
⌈τ      # ceiling of tau
⌈+τη    # ceiling of eta plus tau
⌊×ππ    # floor of pi squared
⌈×ππ    # ceiling of pi squared
⌊+τⁿππ  # floor of pi to the pi plus tau

```

# Answer
> 2 votes
# Vyxal, 22 bytes

```

›
⇧
›⇧
⇧⇧
₀½
⇧T
₀⇩‹
₀⇩
₀‹
₀
₄E∑⇧

```

Try it Online!

I think all of these are optimal aside from maybe 7 and 42, but I couldn't find anything shorter. 0, 1, 2, and 10 are definitely optimal at least.

```
      # 0
›     # 0 + 1
⇧     # 0 + 2
›⇧    # 0 + 1 + 2
⇧⇧    # 0 + 2 + 2
₀½    # 10  / 2
⇧T    # (0 + 2) * 3
₀⇩‹   # 10 - 2 - 1
₀⇩    # 10 - 2
₀‹    # 10 - 1
₀     # 10
₄E∑⇧  # digitsum(2 ** 26) + 2

```

# Answer
> 1 votes
# dc, 44

Score does not include newlines between each snippet.

If CJam's U, X, Y, Z, and A constants are allowed, then I assume `dc`'s representation of 10-15 as A-F is also OK.

```
z
zZ
CI-
DI-
EI-
FI-
II+E-
II+D-
II+C-
II+B-
A
IB+CI-*

```

@yeti's answer is better.

# Answer
> 1 votes
# beeswax, ~~50~~ 46 bytes

(~~62~~ 57 bytes, if IPs are not initialized)

Explanation of instructions:

```
P    increment top lstack value
M    decrement top lstack value
z    all lstack values = 0
F    all lstack values = top
G    get value from absolute(row,column) = lstack(2nd,3rd) value.
@    flip 1st and 3rd lstack values
.    top=top*2nd value
+    top=top+2nd value
!    bitwise NOT
(bel) ASCII control character 7, not printable

```

Instructions for number creation without using numbers, with multiple examples, if the byte lengths are the same. Prepend z if the bee is not in an initialized state:

```
 initialized  to 0                         not initialized to 0
                                                  prepend z
no instruction              [0,0,0]•       z
P                           [0,0,1]•       zP
PP                          [0,0,2]•       zPP
PPP                         [0,0,3]•       zPPP
PPF. or PPPP or PPF+        [0,0,4]•       zPPF.
PPF.P or PPF+P or PPPPP     [0,0,5]•       zPPF.P
PPPF+ or PPF++ or PPFP.     [0,0,6]•       zPPPF+
PPPF+P or PPF..M            [0,0,7]•       zPPF..M
(bel)*1FG                   [0,0,7]•  ← this would make ‘7’ one byte shorter
PPF..                       [0,0,8]•       zPPF..
PPPF.                       [0,0,9]•       zPPPF.
PPPF.P                      [0,0,10]•      zPPPF.P
*PFG                        [0,0,42]•      *PFG (in this configuration the IP is always initialized)

```

You can clone my beeswax GitHub repository here.

# Answer
> 1 votes
# Staq, 60 bytes

```
&              0
&i             1
&ii            2
&iii           3
&iiq           4
&iiqi          5
&iiqii         6
&iiiqdd        7
&iiiqd         8
&iiiq          9
&iiiqi        10
&iiqii&+qX+   42

```

Instructions:

```
& push 0 on top of stack
i increment top stack value
d decrement top stack value
q square top stack value
+ add top and 2nd stack values, put sum on top of stack
X delete 2nd stack value

```

# Answer
> 1 votes
# Cardinal, 50 bytes

Instructions, with alternatives if they have the same lengths:

```
0:  IPs are initialized to 0, otherwise, use instruction 0
1:  +
2:  ++
3:  +++
4:  ++++     or ++=*    or ++=t
5:  +++++    or ++=t+   or ++=*+
6:  +++=*    or ++=**
7:  +++=*+   or ++=tt-
8:  ++=tt
9:  +++=t
10: ++=tt*   or +++=t+
42: +++=*=t*

```

Explanation:

IPs in Cardinal carry length 2 stacks around. The topmost value is called active, the bottom value is called passive. Both can switch roles.

```
+ increment active value
- decrement active value
* addition : active=active+passive
t multiplication: active=active*passive
= set passive = active value

```

# Answer
> 1 votes
# Actually, 32 bytes

```
╜
╒K
 ⌐
╦L
╦K
╦L⌐
╦Lτ
╠²L
╦L╙
╦L²
kY╤
╒º╦+L

```

All full programs. Try it online!

### Explanation

* is `ln(2)`
* is `pi`
* is `e`
* `L` is `floor`
* `K` is `ceil`
* `τ` is `double`
* `²` is `square`

For the last one:

```
╒º╦+L
╒      ln(2)
 º     convert from radian to degree (39.71440802747729)
  ╦+   + pi (42.85600068106709)
    L  floor

```

# Answer
> 1 votes
# Jelly, 26 bytes (non-competing)

```
00:
01: ‘
02: ‘‘
03: ‘‘‘
04: ‘‘Ḥ
05: ⁵H
06: ⁵H‘
07: ⁴H’
08: ⁴H
09: ⁵’
10: ⁵
42: ⁴Ḥ+⁵

```

Try it online! (paste each one of the snippets in the 'Code' field.)

# Answer
> 1 votes
# Brain-Flak, ~~172~~ 143 bytes

```
(<>)
(())
(()())
(()()())
(()()()())
(()()()()())
((()()()){})
((()()()){}())
((()()()()){})
(((()()())){}{})
((()()()()()){})
(((((()()()){}()){})){}{})

```

Try it online! (copy-paste yourself)

# Answer
> 1 votes
# SmileBASIC, ~~73~~ 71 bytes

```
#NO 'unknown use (maybe dialog box results?)
#UP 'd-pad up
#CHKZ 'used in SPCHK and BGCHK to get the z coordinate
#TRED 'text color red
#LEFT 'd-pad left
#BQLSF 'biquad low shelf filter
#BQHSF 'biquad high shelf filter
#BQPEQ 'biquad peaking equalizer
#CHKI 'used in SPCHK to check definition number
#TBLUE 'text color blue
#TPURPLE 'text color purple
#BQHSF*#BQPEQ '42

```

# Answer
> 1 votes
# tcl, 376

```
$argc
incr i
llength [list {} {}]
llength [list {} {} {}]
llength [list {} {} {} {}]
llength [list {} {} {} {} {}]
llength [list {} {} {} {} {} {}]
llength [list {} {} {} {} {} {} {}]
llength [list {} {} {} {} {} {} {} {}]
llength [list {} {} {} {} {} {} {} {} {}]
llength [list {} {} {} {} {} {} {} {} {} {}]
expr [llength [list {} {} {} {} {} {} {}]]*[llength [list {} {} {} {} {} {}]]

```

To try it, on the first line just prepend `puts`  and in the others wrap them by `puts [` before and `]` after.

demo

# Answer
> 1 votes
# Sinclair ZX81/Timex TX1000/1500 BASIC

After some discussion with Adám below, you have the following on the ZX81\** (0 to 10 inclusive and 42), where explanations may be necessary, see the relevant note in the square brackets:

```
[1] .
[2] NOT .
(PI+PI)/PI
INT PI
INT PI+NOT .
INT (PI+PI)-NOT .
INT (PI+PI)
INT (PI+PI)+NOT .
INT (PI*PI+COS PI)
LEN STR$ PI
INT (PI*PI)+NOT .
[3] INT (PI**PI+PI+PI)

```

Notes:

1. This is a short-hand of 0.0
2. Not zero is 1, this is two keystrokes (so two bytes), which is shorter then PI/PI (three keystrokes)
3. \** is to the power of, so it's the integer value of PI to the value of PI plus PI+PI

To see this in action, you can type it in as follows using `Direct` or `Online` mode in ZX BASIC:

```
PRINT .,NOT .,(PI+PI)/PI,INT PI,INT PI+NOT .,INT (PI+PI)-NOT .,INT (PI+PI),INT (PI+PI)+NOT .,INT (PI*PI+ COS PI),LEN STR$ PI,INT (PI*PI)+NOT .,INT (PI**PI+PI+PI)

```

Here is a more evil listing that I came up with that prints 1 to 10 inclusive (try typing it into a ZX81 emulator - actually don't):

```
1 PRINT LEN STR$ USR VAL (STR$ INT (EXP PI+PI)+STR$ (PI-PI)+STR$ (PI/PI+(PI/PI)))
2 PRINT (PI+PI)/PI
3 PRINT INT PI
4 PRINT INT (SGN PI+PI)
5 PRINT INT PI+(PI/PI)
6 PRINT INT (PI+PI)
7 PRINT INT ((PI+PI)+((PI/PI)))
8 PRINT INT (PI+PI+PI-SGN (PI))
9 PRINT LEN STR$ PI
10 PRINT INT (PI*PI)+PI/PI

```

# Answer
> 1 votes
## Ruby, ~~149~~ 147 bytes

```
$.
-~$.
-~-~$.
-~-~-~$.
-~-~-~-~$.
-~-~-~-~-~$.
-~-~-~$.>>~$.
-~-~-~-~-~-~-~$.
-~$.>>~-~-~$.
-~$.>>~-~-~$.|-~$.
-~-~-~-~-~$.>>~$.
-~-~-~-~-~$.>>~-~-~$.|-~-~$.

```

### Explanation:

`$.`is the number of the last line read from the current input file. Since we are not reading any file, this is initialized with 0.

1 through 5 are just the previous number +1, then I can use shifts for multiplication (negative right shift saves 1 byte) and or for addition (can't use +/- because of priority).

So, for example, 42 is `5>>-3|2`

# Answer
> 1 votes
# Lua 5.3, 146 bytes

Uses a lot of length operators. Version probably doesn't matter but it is dependent on the value of `_VERSION` so I might as well include it for clarity.

```
0. #{}
1. #{_G}
2. #{_G}+#{_G}
3. #type(x)
4. #type{}-#{_G}
5. #type{}
6. #type{}+#{_G}
7. #_VERSION
8. #type(load)
9. #type(load)+#{_G}
10. #_VERSION+#type(x)
42. - -(#type{}-#{_G}..#{_G}+#{_G})

```

Annotated with explainations:

```
0. #{}                 -- {} is an empty table, # is the length operator, length of empty table is 0.
1. #{_G}               -- {_G} is a table containing the global environment (itself a table), so there is one item.
2. #{_G}+#{_G}         -- 1+1
3. #type(x)            -- x is not set and so defaults to nil, type(nil) returns the string "nil", length of "nil" is 3.
4. #type{}-#{_G}       -- 5-1
5. #type{}             -- type of table is "table", length of "table" is 5, brackets not required when only argument is a table literal.
6. #type{}+#{_G}       -- 5+1
7. #_VERSION           -- _VERSION contains the current version as a string ("Lua 5.3"), of length 7.
8. #type(load)         -- type of 'load' is "function", length of "function" is 8.
9. #type(load)+#{_G}   -- 8+1
10. #_VERSION+#type(x) -- 7+3
42. - -(#type{}-#{_G}..#{_G}+#{_G}) -- concatenation operator implicitly converts numerical operands to strings, resulting in "4".."2"=="42". Double negation converts it to a number.

```

# Answer
> 1 votes
# Japt, 22 bytes

```
0:  T       T == 0
1:  v       Implicit input 0; Number.v gives 1 if it's even, 0 otherwise
2:  y       Number.y(other) gives GCD of two numbers; `other` defaults to 2
3:  D-A     A == 10, D == 13; 13-10
4:  Gq      G == 16; 16.sqrt()
5:  Az      Number.z(other) gives this/other rounded towards 0; `other` defaults to 2
6:  Cz      C == 12
7:  Ez      E == 14
8:  Iq      I == 64
9:  AÉ      É is a shortcut for `-1`
10: A       Obviously.
42: H+A     H == 32; 32+10

```

Try it online: , , , , , , , , , , 10, 42

# Answer
> 1 votes
# Husk, 42 bytes

With string and character literals forbidden as well as numbers, all Husk has to work with are sequence builtins: `N` (all natural numbers), `ø` (empty list), and the `İ` family. (And functions which never get evaluated, on account of being wrapped, but that's a bit far from useful.)

```
Lø        Length of the empty list.
¬ø        Negation of the empty list.
←İp       First prime. I wanted to use \. here, but even though there are no digits . is a (deliberate) corner case of numeric literal syntax and not a special constant.
←İπ       First digit of pi.
□←tN      Second natural number, squared.
←İ5       First power of 5. (Power sequences only exist for 2, 3, 5, and 7; the digits are arbitrary labels.)
D←İ3      First power of 3, times 2.
←İ7       First power of 7.
½LΘİ€     Length of the list of Euro denominations with a zero tacked on to the beginning, over 2.
□←İπ      First digit of pi, squared.
←İ⁰       First power of 10.
D→D←İ⁰    First power of 10, times 2, plus 1, times 2.

```

# Answer
> 1 votes
# MathGolf, 20 bytes

```
p   # 0
î   # 1
⌠   # 2
d±  # 3
☻√  # 4
♂½  # 5
B½  # 6
D½  # 7
☻½  # 8
d²  # 9
♂   # 10
J∞  # 42

```

Try it online.

# Explanation:

```
p   # Print the top of the stack (or 0 if there is no input, nor anything on the stack)
î   # 1-indexed loop index (1 by default)
⌠   # + 2 (which becomes 0+2 by default)
d±  # Push -3, and then pop and push its absolute value
☻√  # Push 16, square-rooted
♂½  # Push 10, halved
B½  # Push 12, halved
D½  # Push 14, halved
F½  # Push 16, halved
d²  # Push -3, squared
♂   # Push 10
J∞  # Push 21, doubled

```

Of course there any many alternatives for some.. i.e. `6` can alternatively be `X√`; `τi`; `╟x`; ; ; ; ; ; etc. (Try it online).

# Answer
> 1 votes
# Pyth, 30 bytes

```
Z
hZ
hhZ
l`d
eCN
ePT
elG
sPT
ttT
tT
T
.ON

```

Try it online!

Breakdown: Z = Zero, T = Ten, G = alphabet.

```
Z    // 0: Zero
hZ   // 1: Zero + 1
hhZ  // 2: Zero + 1 + 1
l`d  // 3: length of the representation of ' '
eCN  // 4: The last digit of the ascii code for " (34)
ePT  // 5: Last digit of the prime factorials for 10 [2, 5]
elG  // 6: Last difit of the length of the alphabet
sPT  // 7: Sum of the prime factorials for 10
ttT  // 8: 10 - 1 - 1
tT   // 9: 10 - 1
T    // 10: 10
.ON  // 42: Octal value for the " character

```

# Answer
> 1 votes
# Factor \+ `math.unicode`, 88 bytes

```
f ?1+
e e /
e ⌊
e ⌈
π ⌈
φ e^ ⌊
φ e^ ⌈
e sq ⌊
e sq ⌈
π sq ⌊
π sq ⌈
φ 10^ ⌈

```

Try it online!

## Explanation:

```
f ?1+     ! ?1+: increment the input by 1 or return 0 if input is f
e e /     ! e (2.7182818...) divided by e
e ⌊       ! the floor of e
e ⌈       ! the ceiling of e
π ⌈       ! the ceiling of pi (3.14159...)
φ e^ ⌊    ! the floor of e raised to the phi (1.618033...) power
φ e^ ⌈    ! the ceiling of e raised to the phi power
e sq ⌊    ! the floor of e squared
e sq ⌈    ! the ceiling of e squared
π sq ⌊    ! the floor of pi squared
π sq ⌈    ! the ceiling of pi squared
φ 10^ ⌈   ! the ceiling of 10 raised to the phi power (10^ is a function)

```

# Answer
> 0 votes
# C, 78 bytes

Quite a handful of undefined behaviours.

The implementation is `gcc (GCC) 5.3.1 20151207 (Red Hat 5.3.1-2)`, using this online C sandbox.

```
a-a                //1-1
a                  //1
a+a                //1+1
a+a+a              //1+1+1
++a*a              //2*2
++a+a++            //3+2
++a*a++            //3*2
a+++a+a+a          //1+2+2+2
++a<<a             //2<<2
++a*++a            //3*3
a+++a*++a          //1+3*3
(a=++a*a++)*a+a    //(a=3*2)*a+a

```

`a` defaults to `1` being the first argument of `main`.

Boilerplate example for the last one:

```
#include <stdio.h>
int main(int a)
{
    printf("%d\n",(a=++a*a++)*a+a);
    return 0;
}

```

---

### without undefined behaviors, 88 bytes

```
a-a              //1-1
a                //1
a+a              //1+1
a+a+a            //1+1+1
a<<a+a           //1<<2
a<<a+a|a         //(1<<2)|1
a+a+a<<a         //3<<1
a+a+a<<a|a       //(3<<1)|1
a+a<<a+a         //2<<2
a+a<<a+a|a       //(2<<2)|1
a++;a<<a|a       //(2<<2)|2
a=a+a+a<<a;a*a+a //a=3<<1;a*a+a

```

# Answer
> 0 votes
# Excel VBA, 59 bytes

Enums from the `Excel` object available to VBA. `n` is said to be an uninitialized variable and thus holds the default value of `0` as a `Variant`.

These snippets may be called to the VBE immediate window by prepending with `?`. e.g. `?xlOr`.

Further information on each response is commented to the right

```
00: -n          ''  2 bytes;  Uninitialized var `n` defaults to `0`
01: n^n         ''  3 bytes;  0^0=1
02: xlOr        ''  4 bytes;  Excel.XlAutoFilterOperator.xlOr
03: xlSet       ''  5 bytes;  Excel.XlCubeFieldType.xlSet
04: xlWKS       ''  5 bytes;  Excel.XlFileFormat.xlWKS
05: xlDXF       ''  5 bytes;  Excel.XlPictureConvertorType.xlDXF
06: xlCSV       ''  5 bytes;  Excel.XlFileFormat.xlCSV
07: xlCGM       ''  5 bytes;  Excel.XlPictureConvertorType.xlCGM
08: xlEPS       ''  5 bytes;  Excel.XlPictureConvertorType.xlEPS
09: xlTIF       ''  5 bytes;  Excel.XlPictureConvertorType.xlTIF
10: xlPCX       ''  5 bytes;  Excel.XlPictureConvertorType.xlPCX
42: xlWJ3+xlOr  ''  10 bytes; Excel.XlFileFormat.xlWJ3+Excel.XlAutoFilterOperator.xlOr

```

# Answer
> 0 votes
# Java 8, 300 bytes

My only goal was to get every value using only java.lang.Math and integer casting. Because of that, it's probably not the best answer in terms of golf. I have fun making it, however, and that's what counts :)
If I had more time, I would have gone further and only used the constants `Math.PI` and `Math.E`.

```
(int)(Math.E-Math.E)              // 0
(int)(Math.E/Math.E)              // 1
(int)Math.E                       // 2
(int)Math.PI                      // 3
(int)(Math.E/Math.E+Math.PI)      // 4
(int)(Math.E+Math.E)              // 5
(int)(Math.PI+Math.PI)            // 6
(int)(Math.E+Math.E+(int)Math.E)  // 7
(int)(Math.E+Math.E+Math.E)       // 8
(int)(Math.PI*Math.PI)            // 9
(int)Math.ceil(Math.PI*Math.PI)   // 10
(int)Math.ceil(Math.pow(Math.PI,Math.PI)+Math.E+Math.E) //42

```

TIO code to evaluate all of these at once

# Answer
> 0 votes
# Whispers v2, 224 bytes

```
> e
>> 1-1

> e
>> 1÷1

> e
>> ⌊1⌋

> e
>> ⌈1⌉

> π
>> ⌈1⌉

> π
>> ⌈1⌉
>> ≻2

> π
>> 1+1
>> ⌊2⌋

> e
>> 1²
>> ⌊2⌋

> e
>> 1²
>> ⌈2⌉

> π
>> 1²
>> ⌊2⌋

> π
>> 1²
>> ⌈2⌉

> e
>> ≻1
>> 1*2
>> ⌈3⌉

```

Each snippet is separated by two newlines. In Whispers, digits (`0123456789`) only refer to their numerical value when on a *nilad* line i.e. if the line begins with `>` . These lines simply return the value represented on the line. Used in the snippets are `> e` and `> π` which return \\$e\\$ and \\$\pi\\$.

## How they work

### 0 - 10 bytes

```
> e
>> 1-1

```

Try it online!

Return \\$e - e = 0\\$

### 1 - 11 bytes

```
> e
>> 1÷1

```

Try it online!

Returns \\$e \div e = 1\\$

### 2 - 14 bytes

```
> e
>> ⌊1⌋

```

Try it online!

Returns \\$\lfloor e\rfloor = 2\\$

### 3 - 14 bytes

```
> e
>> ⌈1⌉

```

Try it online!

Returns \\$\lceil e\rceil = 3\\$

### 4 - 15 bytes

```
> π
>> ⌈1⌉

```

Try it online!

Returns \\$\lceil\pi\rceil = 4\\$

### 5 - 23 bytes

```
> π
>> ⌈1⌉
>> ≻2

```

Try it online!

Returns \\$\lceil\pi\rceil+1=5\\$

### 6 - 22 bytes

```
> π
>> 1+1
>> ⌊2⌋

```

Try it online!

Returns \\$\lfloor2\pi\rfloor=6\\$

### 7 - 21 bytes

```
> e
>> 1²
>> ⌊2⌋

```

Try it online!

Returns \\$\lfloor e^2\rfloor = 7\\$

### 8 - 21 bytes

```
> e
>> 1²
>> ⌈2⌉

```

Try it online!

Returns \\$\lceil e^2\rceil = 8\\$

### 9 - 22 bytes

```
> π
>> 1²
>> ⌊2⌋

```

Try it online!

Returns \\$\lfloor\pi^2\rfloor = 9\\$

### 10 - 22 bytes

```
> π
>> 1²
>> ⌈2⌉

```

Try it online!

Returns \\$\lceil\pi^2\rceil = 10\\$

### 42 - 29 bytes

```
> e
>> ≻1
>> 1*2
>> ⌈3⌉

```

Try it online!

Returns \\$\lceil e^{e+1}\rceil = 42\\$

# Answer
> 0 votes
# Python 3

```
len([])
len([len])
len([len,len])
len([len,len,len])
len([len,len,len,len])
len([len,len,len,len,len])
len([len,len,len,len,len,len])
len([len,len,len,len,len,len,len])
len([len,len,len,len,len,len,len,len])
len([len,len,len,len,len,len,len,len,len])
len([len,len,len,len,len,len,len,len,len,len])
len([len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len,len])

```

Just lists and functions. No forbidden literals!

Definitely can be golfed, but I automatically generated these, so I might golf it later.

---
Tags: code-golf, number, restricted-source, generation, multiple-holes
---


title: IPv4 Integer Conversion Function

text:
# Question
Title: IPv4 Integer Conversion Function
Write the shortest function to convert an IP address into it's integer representation and output it as an integer.

To change an IPv4 address to it's integer representation, the following calculation is required:

* Break the IP address into it's four octets.
* `(Octet1 * 16777216) + (Octet2 * 65536) + (Octet3 * 256) + (Octet4)`

**Sample Input**

```
192.168.1.1           10.10.104.36           8.8.8.8

```

**Sample Output**

```
3232235777            168454180              134744072

```

# Answer
## PHP - 21 Characters

```
<?=ip2long($argv[1]);

```
> 11 votes

# Answer
## MySQL - 20 Characters

```
SELECT INET_ATON(s);

```
> 8 votes

# Answer
**C: 79 characters**

```
main(i,a)char**a;{i=i<<8|strtol(a[1],a+1,0);*a[1]++?main(i,a):printf("%u",i);}

```

EDIT: removed C++, would not compile without headers; with GCC, the `printf` and `strtol` function calls trigger built-in functions, hence headers can be skipped. Thx to @ugoren for the tips. This will compile as is without additional options to `gcc`.

EDIT2: `return` is actually redundant :)
> 8 votes

# Answer
# Ruby (no builtins/eval) - 47

```
s=->s{s.split(".").inject(0){|a,b|a<<8|b.to_i}}

```

Test:

```
s["192.168.1.1"]
3232235777

```
> 8 votes

# Answer
## Befunge - 2x11 = 22 characters

So close, Befunge will win one day.

```
>&+~1+#v_.@
^*4*8*8<

```

### Explanation

The biggest distinguishing feature of Befunge is that instead of being a linear set of instructions like most languages; it is a 2d grid of single character instructions, where control can flow in any direction.

```
>      v
^      <

```

These characters change the direction of control when they are hit, this makes the main loop.

```
 &+~1+

```

This inputs a number and pushes it onto the stack (`&`), pops the top two values off the stack, adds them and pushes them back onto the stack (`+`), inputs a single character and places its ascii value on the stack (`~`), then pushes 1 onto the stack and adds them (`1+`).

The interpreter I've been using returns -1 for end of input, some return 0 instead so the `1+` part could be removed for them.

```
      #v_.@

```

The `#` causes the next character to be skipped, then the `_` pops a value off the stack and if it is zero sends control right, otherwise sends it left. If the value was zero `.` pops a value off the stack and outputs it as an integer and `@` stops the program. Otherwise `v` sends control down to the return loop.

```
^*4*8*8<

```

This simply multiplies the top value of the stack by 256 and returns control to the start.
> 7 votes

# Answer
## Golfscript -- 16 chars

```
{[~]2%256base}:f

```

As a standalone program, this is even shorter at 11.

```
~]2%256base

```

Extremely straightforward. Evaluates the input string (`~`) and puts it into an array `[]`. Since the `.`s in the string duplicate the top of the stack, we only take every other term in the array (`2%`). We now have an array which basically represents a base 256 number, so we use a built-in function to do the conversion. (`256base`).
> 7 votes

# Answer
# Ruby (40)

```
q=->x{x.gsub(/(\d+)\.?/){'%02x'%$1}.hex}

```

-\>

```
q["192.168.1.1"]
=> 3232235777

```
> 5 votes

# Answer
## Ruby - 46 chars

```
require"ipaddr"
def f s;IPAddr.new(s).to_i;end

```
> 4 votes

# Answer
# Bash - 46

### Table of content

You will find 4 differently golfed version:

> ```
> echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]                        # 46chr
> set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]                       # 47chr
> v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]     # 65chr
> mapfile -td. i<<<$1;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o  # 68chr
>
> ```

## New version! 2018-11-15 More golfed, 46 char

```
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]

```

### Explanation

* I used `$_` for more golfing.
* Syntax `${1//./ }`will substitute every dots `.` by spaces .
* so `printf`will render something like `192<<(_-=8)|168<<(_-=8)|1<<(_-=8)|1<<(_-=8)|`
* then we will add a `0` after last **OR** `|` and
* preset `_` to **32**. will read construct from left to right, so `$((_-=8))` make `24` at 1st *shift*, `16` on second, and so on.

in action:

```
set -- 192.168.1.1
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
3232235777

```

For fun: trying to get `$_` content, after this:

> ```
> echo $_
> 3232235777
>
> ```
>
> ;-b
>
> ```
> set -- 192.168.1.1
> echo $_ $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0] $_
> 192.168.1.1 3232235777 0
>
> ```
>
> Ok, that's correct *`32 - 4 x 8 = 0`*

In a function:

```
ip2int() {
    echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
}
ip2int 192.168.1.1
3232235777
ip2int 255.255.255.255
4294967295
ip2int 0.0.0.0
0

```

### or into a loop: -\> 60

```
ip2int() {
    for i;do
        echo $[_=32,`printf "%d<<(_-=8)|" ${i//./ }`0]
    done
}

ip2int 192.168.1.1 10.10.104.36 8.8.8.8 1.1.1.1 255.255.255.255 0.0.0.0
3232235777
168454180
134744072
16843009
4294967295
0

```

## bash (v4.1+): 47

***First post***

```
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]

```

Explanation:

* Syntax `${1//./ }`will substitute every dots `.` by spaces .
* `set --` set *positional parameters* (`$@=($1 $2 $3...)`)
* So `set -- ${1//./ }` will split `$1` by dots and set `$1`, `$2`, `$3` and `$4` if string containg `3` dots (and no spaces).

in action:

```
set -- 192.168.1.1
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]
3232235777

```

or in a function:

```
ip2int() {
    set -- ${1//./ }
    echo $[$1<<24|$2<<16|$3<<8|$4]
}
ip2int 192.168.1.1
3232235777
ip2int 0.0.0.0
0

```

### or into a loop: -\> 61

```
for i;do set -- ${i//./ };echo $[$1<<24|$2<<16|$3<<8|$4];done

```

in action:

```
ip2int() {
    for i;do
        set -- ${i//./ }
        echo $[$1<<24|$2<<16|$3<<8|$4]
    done
}

ip2int 192.168.1.1 10.10.104.36 8.8.8.8 1.1.1.1 0.0.0.0
3232235777
168454180
134744072
16843009
0

```

## Another version differently golfed: 65

```
v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]

```

Sample:

```
ip2int() {
    v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]
}

ip2int 255.255.255.255
4294967295
ip2int 10.10.104.36
168454180

```

In a loop (+14): 82

```
ip2int() {
    for i;do
        v=('|%d<<'{24,16,8,0})
        printf -vv "${v[*]}" ${1//./ }
        echo $[0$v]
    done
}

```

*** or a little more ugly: 70\***

```
v=('|%d<<'{24,16,8});printf -vv "${v[*]}" ${1//./ };echo $[0${v%<<2*}]

```

where `printf` give some string like `|192<<24 |168<<16 |1<<8|1<<24 |0<<16 |0<<8` we have to cut at last `<<2...`.

## golfed with `mapfile`, longer: 68

```
ip2int() {
    mapfile -td. i<<<$1;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o
}

```

or with loop: 82

```
ip2int() {
    for a;do
      mapfile -td. i<<<$a;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o
    done
}

```
> 4 votes

# Answer
# AWK in ~47 chars

First-timer here... Um, not sure how to count this, but without the 'echo' it's 47 chars in AWK. (Not exactly bogey golf, but it's in the hole.)

```
echo $addr | /bin/awk -F\. '{print $1*16777216+$2*65536+$3*256+$4}'

```

Full day early for #tbt, too, so I actually met a schedule!!! \*8-)

Banner day.
> 4 votes

# Answer
## Golfscript - 21 chars

```
{'.'/{~}%{\256*+}*}:f

```
> 3 votes

# Answer
## Python 56 45

```
c=lambda x:eval('((('+x.replace('.','<<8)+'))

```
> 3 votes

# Answer
## C++ - lots of chars

```
#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>
uint f(std::string p)
{
        std::vector<std::string> x;
        boost::split(x,p,boost::is_any_of("."));
        uint r=0;
        for (uint i = 0; i < x.size(); i++)
                r=r*256+atoi(x[i].c_str());
        return r;
}

```
> 3 votes

# Answer
## PowerShell ~~66~~ 61

Variation on Joey's answer:

```
filter I{([ipaddress](($_-split'\.')[3..0]-join'.')).address}

PS C:\> '192.168.1.1' | I
3232235777
PS C:\> '10.10.104.36' | I
168454180
PS C:\> '8.8.8.8' | I
134744072

```
> 3 votes

# Answer
# Powershell, ~~47~~ 43 bytes

```
$args-split'\.'|%{$r=([long]$r-shl8)+$_};$r

```

Test script:

```
$f = {

$args-split'\.'|%{$r=([long]$r-shl8)+$_};$r

}

@(
    ,("192.168.1.1",3232235777)
    ,("10.10.104.36",168454180)
    ,("8.8.8.8",134744072)
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: 3232235777
True: 168454180
True: 134744072

```
> 3 votes

# Answer
### Windows PowerShell, 70

Naïve approach:

```
filter I{[int[]]$x=$_-split'\.'
$x[0]*16MB+$x[1]*64KB+$x[2]*256+$x[3]}

```

With using System.Net.IPAddress: **76**

```
filter I{([ipaddress]($_-replace('(.+)\.'*3+'(.+)'),'$4.$3.$2.$1')).address}

```

Test:

```
> '192.168.1.1'|I
3232235777

```
> 2 votes

# Answer
## JavaScript (45 characters)

Requires support for the `.reduce()` Array method introduced in ES5 and arrow functions.

```
f=(x)=>x.split('.').reduce((p,c)=>p<<8|c)>>>0

```
> 2 votes

# Answer
## Befunge-93 - 36 characters

```
&"~"2+::8****&884**:**&884***&++++.@

```
> 2 votes

# Answer
# Perl : DIY ( for oneliners. )(40)

```
$j=3;$i+=($_<<($j--*8))for split/\./,$x;

```

\# Use value in $i

# DIY Function(65):

```
sub atoi{my($i,$j)=(0,3);$i+=($_<<($j--*8))for split'.',shift;$i}

```
> 2 votes

# Answer
## Haskell - 14 chars

```
(.) a=(256*a+)

```

usage in GHCi:

```
Prelude> let (.) a=(256*a+)
Prelude> 192. 168. 0. 1
3232235521

```

The only problem is that you have to put spaces left or right of the dot, otherwise the numbers will be interpreted as floating point.
> 2 votes

# Answer
## C# – 77 chars

```
Func<string,uint>F=s=>s.Split('.').Aggregate(0u,(c,b)=>(c<<8)+uint.Parse(b));

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
'.¡₁β

```

Try it online!
> 2 votes

# Answer
**C# - 120 Characters**

```
float s(string i){var o=i.Split('.').Select(n=>float.Parse(n)).ToList();return 16777216*o[0]+65536*o[1]+256*o[2]+o[3];}

```

My first code golf - be gentle ;)
> 1 votes

# Answer
# D: 84 Characters

```
uint f(S)(S s)
{
    uint n;
    int i = 4;

    foreach(o; s.split("."))
        n += to!uint(o) << 8 * --i;

    return n;
}

```
> 1 votes

# Answer
# Python 3.2 (69)

```
sum((int(j)*4**(4*i)) for i,j in enumerate(input().split('.')[::-1]))

```
> 1 votes

# Answer
# PHP (no builtins/eval) - 54

```
<foreach(explode(".",$argv[1])as$b)$a=@$a<<8|$b;echo$a;

```
> 1 votes

# Answer
## Perl, 14 characters:

```
sub _{unpack'L>',pop}

# Example usage
print _(10.10.104.36) # prints 168454180

```
> 1 votes

# Answer
# Stax, 9 bytes

```
üL▼ü╛tΓi╨

```

Run and debug it
> 1 votes

# Answer
# Perl 6, 16 bytes

```
{:256[m:g/\d+/]}

```

Try it online!
> 1 votes

# Answer
# C (gcc) `-m32` / POSIX, 33 bytes

```
f(a){inet_aton(a,&a);a=ntohl(a);}

```

Try it online!

On a big-endian platform, you could simply define a macro with `-Df=inet_aton` for **13 bytes**.
> 1 votes

# Answer
# Jelly, 6 bytes

```
ṣ”.Vḅ⁹

```

Try it online!

### How it works

```
ṣ”.Vḅ⁹  Main link (monad). Input: string
ṣ”.     Split at dots
   V    Convert to numbers
    ḅ⁹  Convert base 256 to integer

```
> 1 votes

# Answer
# Bash, 27 bytes

```
echo $[${1//./<<32-++i*8|}]

```

Try it online!

At the cost of 1 character, this can avoid depending on the state of `i`:

```
echo $[i=4,${1//./<<--i*8|}]

```

Dramatic improvement on existing `bash` solution (46 characters at time of writing).
> 1 votes

# Answer
# K (ngn/k), 10 bytes

```
256/.'"."\

```

Try it online!

* `"."\` split string input on `.`'s
* `.'` convert each string to its integer
* `256/` convert from base-256
> 1 votes

# Answer
# Powershell - 53

Variation on Ty Auvil's answer, which is a variation on Joey's answer:

`%{([ipaddress]($_.split('.')[3..0]-join'.')).address}`

```
PS C:\> '192.168.1.1' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
3232235777
PS C:\> '10.10.104.36' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
168454180
PS C:\> '8.8.8.8' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
134744072

```

I would have just made a suggestion in the comments, but not enough rep.
> 0 votes

# Answer
**ASM - 98 byte executable (WinXP command shell), about 485 characters**

Assemble using A86. Badly formed IP addresses generate undefined output.

```
    mov si,82h
    mov di,10
    mov bp,l3
    fldz
    push l2
    push l0
    push l0
    push l0
 l0:xor ax,ax
    xor cx,cx
 l1:add ax,cx
    mov [bp+di],ax
    mul di
    mov cx,ax
    lodsb
    sub al,'0'
    jnc l1
    fild w[bp]
    fmulp
    fild w[bp+di]
    faddp
    ret
 l2:fbstp [si]
    mov bx,di
    mov di,bp
 l4:dec bx
    jz l5
    mov al,[si+bx-1]
    aam 16
    add ax,'00'
    xchg al,ah
    stosw
    jmp l4
 l5:mov al,'$'
    stosb
    lea di,[bp-1]
 l6:inc di
    cmp b[di],'0'
    je l6
 l7:cmp b[di],al
    jne l8
    dec di
 l8:mov dx,di
    mov ah,9
    int 21h
    ret
 l3:dw 256

```
> 0 votes

# Answer
## C (91)

Not going to win anyway, so I tried to be a bit creative. Tested on 32-bit GCC 4.4.3.

```
main(a,c,b)char**c,*b;{c=c[1];for(b=&a+1;c=strtok(c,".");c=0)*--b=atoi(c);printf("%u",a);}

```
> 0 votes

# Answer
## Scala 59 chars:

```
def f(i:String)=(0L/:i.split("\\.").map(_.toInt))(_*256+_)

```
> 0 votes

# Answer
## **Perl with builtins (35):**

```
unpack"N",pack"C4",split/\./,shift;

```

## Perl without builtins (42):

```
split/\./,shift;$s+=$_<<@_*8while$_=shift;

```
> 0 votes

# Answer
## Python (No eval) - 67

```
c=lambda x:long(''.join(["%02X"%long(i) for i in x.split('.')]),16)

```
> 0 votes

# Answer
# Mathematica, 53 chars

```
f=FromDigits;f[f/@StringSplit[InputString[],"."],256]

```
> 0 votes

# Answer
# J, 21 bytes

```
[:256&#.[:".;._1'.'&,

```

Try it online!

## explanation

```
[: 256&#. [: ".;._1 '.'&,
[: 256&#.                   NB. assuming a base 256 list,
                            NB. convert the following to decimal:
                    '.'&,   NB. the input with a dot appended
          [: ".;._1         NB. split at dots and converted to ints

```
> 0 votes

# Answer
# Jelly, 13 bytes

```
4Ḷ⁹*U
ṣ”.V×¢S

```

Try it online!

I don't think Jelly has a builtin for this. At least, I couldn't find one.
> 0 votes

# Answer
# APL(NARS), 16 chars, 32 bytes

```
{256⊥⍎¨⍵⊂⍨⍵≠'.'}

```

test

```
  f←{256⊥⍎¨⍵⊂⍨⍵≠'.'}
  f¨'192.168.1.1' '10.10.104.36' '8.8.8.8'
3232235777 168454180 134744072

```
> 0 votes

# Answer
# Java 8, 83 bytes

`i->{long u=0;for(int j=0;j<4;)u+=new Long(i.split("\\.")[j])<<(24-8*j++);return u;}`

Try it online!

Could have saved 10 bytes by moving the initialisation of `u` and `j` "up" a level but I'm not entirely sure that's allowed so I went for the safe version of my solution.
> 0 votes

# Answer
## Burlesque - 11 bytes

```
'.;;ri256ug

'.;;           split by `.`
    ri         read integer
      256ug    undigits base 256

```

Try it online.
> 0 votes

# Answer
# Japt, ~~10~~ 4 bytes

```
nG²o

```

Try it

```
 G       :16
  ²      :Squared
   o     :Range [0,G²)
n        :Convert input string from that base to base-10 integer

```
> 0 votes

# Answer
# Kotlin, 50 bytes

```
{it.split(".").fold(0L){a,v->v.toInt()+(a shl 8)}}

```

Try it online!
> 0 votes

# Answer
# min, 53 bytes

```
"." split 3 :a (int 256 a pow * a 1 - @a int) map sum

```

Takes IP address as string on stack. Leaves the converted number on top of stack.
> 0 votes

# Answer
# Pxem, Filename: 58 bytes + Content: 0 bytes = 58 bytes.

* Filename (escaped): `._\377\001.+.c.c.!.!.!.i.s._\377\001.+.c.!.!.+.i.s._\377\001.+.!.+.i.s._.+.n`
* Content: empty

Problem is that my implementation of Pxem supports literal value up to 255; needed to make greatee values by myself.

## Usage

Via stdin/stdout. Accepts only one input at once.

Try it online!
> 0 votes

# Answer
# Pinecone, 266 bytes

```
u:IntArray:4;s:"".input;k:IntArray:s.len;k.set:0,-1;n:1
i:0|i<s.len|i:i+1@((s.sub:i,i+1)="."?(k.set:n,i;n:n+1))k.set:n,s.len;i:1|i<n+1|i:i+1@(j:s.sub:((k.get:i-1)+1),(k.get:i)u.set:(i-1),(j.Int))print:((u.get:0)*16777216)+((u.get:1)*65536)+((u.get:2)*256)+(u.get:3)

```
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
'./ɠḋ

```

Try it online!

#### Explanation

```
'./ɠḋ  '# Implicit input
'./    '# Split it on "."s
   ɠḋ   # Convert from base-256
        # Implicit output

```
> 0 votes

# Answer
# Python 3.11+ (no `eval`/built-in libraries), 47 bytes

```
c=lambda x:0 .from_bytes(map(int,x.split('.')))

```

As of 3.11, `int.from_bytes` implicitly uses big-endian byte order. `0. from_bytes` is shorter than `int.from_bytes`, and works just fine (since `from_bytes` is a class method, it works the same when called on an instance; the space is needed to avoid `0.` being interpreted as a `float`).

Attempt This Online!
> 0 votes

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


title: Find the fairest partition of a list

text:
# Question
Title: Find the fairest partition of a list
Given a list of positive integers, partition the list into two sublists such that the absolute value of the difference of the sums over the two sublists is minimal.
The output of the program should be the (non-negative) difference of these sums.

## Examples:

```
[1,2,3]       -> 0  # [1,2], [3]
[2,3,5,7,11]  -> 0  # [2,5,7], [3,11]
[13,17,19,23] -> 0  # [13,23], [17,19]
[1,2,3,4]     -> 0  # [1,4], [2,3]
[2,2,2,3,3]   -> 0  # [2,2,2], [3,3]
[1,2,3,4,5]   -> 1  # [1,2,4], [3,5]
[1,2,3,4,5,6] -> 1  # [1,2,3,4], [5,6]
[1,1,2,5]     -> 1  # [1,1,2], [5]
[1,3,9,27]    -> 14 # [1,3,9], [27]

```

## Rules

* The sublists do not need to be contiguous
* Every element of the list has to be in (exactly) one of the two sublists
* The list can contain duplicate elements
* You can assume that the list contains at least 3 elements
* You are allowed to assume that the list is sorted (using any convenient ordering)
* The ordering of two numbers should be the same for all lists
* This is the shortest solution wins

---

related challenge

# Answer
> 11 votes
# Python, 57 bytes

```
f=lambda A,B,*a:min((z:=[abs,f][a>()])(A+B,*a),z(A-B,*a))

```

Attempt This Online!

Takes splatted input. Input must have at least 2 elements.

### How?

Recursively builds up all possible differences by successively adding or subtracting each element (except the first which is allowed to break symmetry).

# Answer
> 10 votes
# 05AB1E, ~~7~~ 5 bytes

```
æOÂαß

```

Attempt this online! or try all testcases

## Explanation

Utilizes the fact that 05AB1E's powerset builtin returns the sets in the same order as looking at the numbers \\$0\\$ \- \\$2^n-1\\$ in binary reversed, so the opposite of each element when reversing is its complement.

```
æ        # all subsets of the input
O        # the sum of each
Â        # Bifurcated, push the reverse without popping
α        # take the absolute difference (vectorizes)
ß        # the minimum of that

```

# Answer
> 7 votes
# K (ngn/k), 16 bytes

```
&//|/-:\+/:/+-:\

```

Try it online!

```
            +-:\    ± each
        +/:/        outer sum
   |/-:\            abs
&//                 min

```

# Answer
> 6 votes
# JavaScript (Node.js), 55 bytes

```
f=([c,...x],y=0)=>c?1/Math.max(1/f(x,y+c),1/f(x,y-c)):y

```

Try it online!

-1B from tsh

# Answer
> 5 votes
# Uiua, 10 bytes

Same idea as loopy walt's Python answer.

```
/↧⌵/(⊂⊃+-)

```

Try it!

```
/↧⌵/(⊂⊃+-)  # Function taking a vector from the stack and leaving a number
   /(    )  # Reduce the vector by ...
     ⊂      # Concatenate the results from ...
      ⊃+-   # both adding and subtracting the new value from all intermediate values.
  ⌵         # Take the Absolute Value of each number
/↧          # Reduce by Minimum

```

# Answer
> 5 votes
# , 56 bytes

```
f=\(x,s=0)`if`(any(x),f(x[-1],c(s,-s)+x[1]),min(abs(s)))

```

Attempt This Online!

A recursive function, partly inspired by @loopywalt’s Python answer so be sure to upvote that one too! Takes an integer vector and returns an integer.

# An alternative non-recursive approach R, ~~60~~ 57 bytes

```
\(x)min(abs((1:max(s<-2^seq(x))%o%(2/s)%/%1%%2*2-1)%*%x))

```

Attempt This Online!

This one avoids recursion, but uses an outer multiplication table and matrix multiplication.

*Thanks to @Giuseppe for saving three bytes!*

# Answer
> 4 votes
# Scala, ~~98~~ 82 bytes

Saved 16 bytes thanks to @corvus\_192

---

Golfed version. Try it online!

```
def?(l:Seq[Int],y:Int=0):Int=l match{case c::x=> ?(x,y+c)min?(x,y-c)case _=>y.abs}

```

Ungolfed version. Try it online!

```
object Main {
  def f(list: List[Int], y: Int = 0): Int = {
    list match {
      case c :: x => math.min(f(x, y + c), f(x, y - c))
      case Nil    => math.abs(y)
    }
  }

  def main(args: Array[String]): Unit = {
    println(f(List(1,2,3)))         // -> 0
    println(f(List(2,3,5,7,11)))    // -> 0
    println(f(List(13,17,19,23)))   // -> 0
    println(f(List(1,2,3,4)))       // -> 0
    println(f(List(1,2,3,4,5)))     // -> 1
    println(f(List(1,2,3,4,5,6)))   // -> 1
    println(f(List(1,1,2,5)))       // -> 1
    println(f(List(1,3,9,27)))      // -> 14
  }
}

```

# Answer
> 4 votes
# Jelly, 7 bytes

```
żNŒp§AṂ

```

Try it online!

A monadic link that takes a list of integers and returns an integer. Works by zipping the original list with its negation, taking the Cartesian project, and finding the minimum absolute sum.

## Alternative 7-byters and a 9-byter:

```
ŒP§ạU$Ṃ
ŒP§ḤạSṂ
LØ+ṗ×⁸§AṂ

```

The first two are variants on @CommandMaster’s 05AB1E answer. The third works similarly to my non-recursive R answer. Note the TIO link above includes all 4 versions.

# Answer
> 3 votes
# Vyxal `g`, 31 bitsv2, 3.875 bytes

```
ṗṠḂε

```

Try it Online!

Bitstring:

```
1001111110100111110010001110010

```

Ports 05ab1e exactly, command for command.

## Explained

```
ṗṠḂε
ṗ     # Powerset, in infinite list friendly order
 Ṡ    # Vectorised sums
  Ḃ   # Bifurcated
   ε  # Absolute differences
# The g flag returns the smallest item.

```

Created with the help of Luminespire.

# Answer
> 3 votes
# Uiua, 18 bytes

```
/↧⌵-⇌.≐(/+▽)⋯⇡ⁿ⧻,2

```

Try it!

```
/↧⌵-⇌.≐(/+▽)⋯⇡ⁿ⧻,2
              ⁿ⧻,2  # 2 to the <length of input> power
             ⇡      # create a range from that number
            ⋯       # binary (vectorizing big-endian)
      ≐(   )        # tribute (apply (...) to each binary list and the input)
          ▽         # keep (forming an element of the power set of the input)
        /+          # sum
     .              # duplicate (the sums)
    ⇌               # reverse
  ⌵-                # absolute difference
/↧                  # minimum

```

# Answer
> 3 votes
# Python, 86 bytes

*-10 bytes by l4m2*
*-4 bytes thanks to tsh*

```
def f(s,l={0}):
 for i in s:l|={i+j for j in l}
 return min(abs(a+a-sum(s))for a in l)

```

First time golfing in Python!

Attempt This Online!

# Answer
> 3 votes
# Nekomata, 5 bytes

```
ŋ∑Aaṁ

```

Attempt This Online!

A port of @att's K (ngn/k) answer.

```
ŋ∑Aaṁ
ŋ       Optionally negate each element of the input
 ∑      Sum
  A     Absolute value
   a    All possible values
    ṁ   Minimum

```

# Answer
> 3 votes
# , 14 13 bytes

```
[:<./(+|@,-)/

```

Try it online!

A port of ovs's Uiua answer thanks to Bubbler. -1 thanks to att.

## , 18 bytes

```
[:<./[:|@,]+//@,.-

```

Try it online!

A port of att's nice K answer.

# Answer
> 2 votes
# Charcoal, ~~24~~ 20 bytes

```
⊞υ⁰Ｆθ≔⁺υ⁺υιυＩ⌊↔⁻Σθ⊗υ

```

Try it online! Link is to verbose version of code. Explanation: Port of @mathscat's Python answer.

```
⊞υ⁰

```

Start with the sum of the empty sublist.

```
Ｆθ

```

Loop over the input list.

```
≔⁺υ⁺υιυ

```

Calculate the sums of the subsets including the current element and any subset of the previous elements and append those to the list of subset sums.

```
Ｉ⌊↔⁻Σθ⊗υ

```

Calculate the minimum difference between each subset and its complement, using the equation \\$ | \sum (U \setminus A) - \sum A | = | \sum U - \sum A - \sum A | = | \sum U - 2 \sum A | \\$.

Previous 24-byte solution:

```
Ｉ⌊↔⁻Σθ⊗ＥＸ²ＬθΣＥθ×λ﹪÷ιＸ²μ²

```

Try it online! Link is to verbose version of code. Explanation:

```
     θ                      Input list
    Σ                       Take the sum
   ⁻                        Vectorised subtract
         ²                  Literal integer `2`
        Ｘ                   Raised to power
           θ                Input list
          Ｌ                 Length
       Ｅ                    Map over implicit range
              θ             Input list
             Ｅ              Map over elements
                λ           Current element
               ×            Multiplied by
                   ι        Outer value
                  ÷         Integer divided by
                     ²      Literal integer `2`
                    Ｘ       Raised to power
                      μ     Inner index
                 ﹪          Modulo
                       ²    Literal integer `2`
            Σ               Take the sum
      ⊗                     Doubled
  ↔                         Vectorised absolute
 ⌊                          Take the minimum
Ｉ                           Cast to string
                            Implicitly print

```

19 bytes using the newer version of Charcoal on ATO:

```
Ｉ⌊↔⁻Σθ⊗ＥＸ²Ｌθ↨¹×θ↨κ²

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
   ⁻Σθ⊗ＥＸ²Ｌθ        As above
               θ    Input list
              ×     Zipped multiply with
                 κ  Current value
                ↨   Converted to base
                  ² Literal integer `2`
            ↨¹      Take the sum
Ｉ⌊↔                 As above

```

(`Sum` doesn't work on empty lists because it needs to know what type of list it's summing.)

# Answer
> 2 votes
# APL+WIN, 46 bytes

Prompts for vector of integers:

```
⌊/|(+/i×m)-+/(i←(b,n)⍴v)×~m←⍉(n⍴2)⊤⍳b←2*n←⍴v←⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# Jelly, 7 bytes

```
ŒṖ§ḅ-AṂ

```

A monadic Link that accepts a list of integers and yields the smallest partition difference.

**Try it online!**

### How?

Creates all partitions then treats every other part as being in the first of the two sets. Calculates the difference by converting the sums of the parts from base one (which takes the negative of every other part-sum).

```
ŒṖ§ḅ-AṂ - Link: list of integers  e.g. [4,5,6]
ŒṖ      - all list partitions          [[[4],[5],[6]],[[4],[5,6]],[[4,5],[6]],[[4,5,6]]]
  §     - sums                         [[4,5,6],[4,11],[9,6],[15]]
   ḅ-   - from base -1                 [5,7,-3,15] i.e. 6-5+4=5 11-4=7 6-9=3 15=15
     A  - absolute values              [5,7,3,15]
      Ṃ - minimum                      3

```

---

Alternatives

```
ŒP§ạṚ$Ṃ - sum every subset absolute difference with its own reverse, minimum
żNŒp§AṂ - zip with negative, take the Cartesian product, get sums, absolute values, minimum

```

# Answer
> 1 votes
# Excel, 106 bytes

```
=LET(
    a,A1#,
    b,ROWS(a),
    c,MOD(INT(SEQUENCE(2^b,,)/2^SEQUENCE(,b,)),2),
    MIN(ABS(MMULT(c,a)-MMULT(ABS(1-c),a)))
)

```

Input is spilled, *vertical* array in cell `A1`.

# Answer
> 0 votes
# C (GCC), 66 bytes

```
A,B;d(a,n)int*a;{for(A=B=0;n--;)A<B?A+=a[n]:(B+=a[n]);a=abs(A-B);}

```

Attempt This Online!

-1 thanks to Arnauld.

A simple greedy algorithm.

The program uses a wide assortment of tricks:

* K&R function declarations
* Assumes that the input is sorted, per challenge specs.
* Global variables assumed zero & permitted to omit the type specifier due to implicit int.
* Implicit int in function declaration
* `~i` will check if `i` is not `-1`.
* Ternary operator replaces an if.
* A return statement is avoided by assuming `-O0` and exploiting the load to `a` writing to `rax`, the return value register on x86.

# Answer
> 0 votes
# Desmos, 86 bytes

```
f(l)=[abs(l.total-2total(mod(floor(2i/{2^{[1...L]}),2)l))fori=[1...2^L]].min
L=l.count

```

Try It On Desmos!

Try It On Desmos! - Prettified

---
Tags: code-golf, set-partitions
---