# Question
Title: Converting a string to lower-case (without built-in to-lower functions!)
The goal of this code-golf is to create a code that lets the user input an ASCII string (contains only printable ASCII characters), and your program outputs the lower-case variant of this string.

**Important: you are NOT allowed to use a built-in function that converts the string (or just one character) to lowercase (such as `ToLower()` in .NET, `strtolower()` in PHP , ...)!** You're allowed to use all other built-in functions, however.

**Another important note:** The input string doesn't contain *only* uppercase characters. The input string is a mix of uppercase characters, lowercase characters, numbers and other ASCII printable characters.

Good luck!

# Answer
### Shell - 10

Translation of @Gowtham's Perl solution using `/bin/tr`.

```
tr A-Z a-z

```

Sample run:

```
% tr A-Z a-z <<<'Hello WORLD! @'
hello world! @

```
> 22 votes

# Answer
# Python 2.7 - 30 (with terrible and unapologetic rule abuse)

```
raw_input().upper().swapcase()

```

As an anonymous edit pointed out, you can do it in **~~27~~ 26 in Python 3**:

```
input().upper().swapcase()

```

I'm flagrantly abusing the rules here, but...

> **Important: you are NOT allowed to use a built-in function that converts the string (or just one character) to lowercase (such as `ToLower()` in .NET, `strtolower()` in PHP , ...)!** You're allowed to use all other built-in functions, however.

This **takes the strings and coverts it to upper case**. Then in a very unrelated method call, it reverses the case of the string - so that any lower case letters become upper case letters... and **swaps any upper case letters to lower case letters**.
> 57 votes

# Answer
**Perl** \- 11 10 characters.

```
y/A-Z/a-z/

```

`y///` is same as `tr///`!

In action:

```
% perl -pe 'y/A-Z/a-z/' <<< 'Hello @ WORLD !'
hello @ world !

```
> 34 votes

# Answer
## Befunge-98 - ~~26 22 21~~ 19

```
~:''-d2*/1-!' *+,#@

```

Relies on the fact that `(c-39)/26` is `1` only for character codes of uppercase ASCII characters (assuming integer division). For each character `c`, print out `c + (((c-39)/26)==1)*' '`.

Sample session:

```
% cfunge lower.b98
hello WORLD!
hello world!
This is a TEST!!11 az AZ @[`{
this is a test!!11 az az @[`{

```
> 10 votes

# Answer
### Python 3, 48

```
input().translate({c:c|32for c in range(65,91)})

```
> 10 votes

# Answer
## Ruby, 18 characters

Nothing really interesting.

```
gets.tr'A-Z','a-z'

```

(run in IRB)

Just for fun: a confusing version:

```
$,=$* *' ';$;=$,.tr'A-Z','a-z';$><<$;

```

Run like this:

```
c:\a\ruby>lowercase.rb Llamas are AMAZING!

```

Output

```
llamas are amazing!

```
> 8 votes

# Answer
## J - 30

```
'@Z'(]+32*1=I.)&.(a.&i.)1!:1]1

```

J is read right-to-left, so to break this down:

1. Prompt user for input: `1!:1]1`
2. Perform algorithm in code-point-space: `&.(a.&i.)`
3. Identify character range for each letter; the characters between codepoints "@" and "Z" are considered uppercase: `1=I.`.
4. For each uppercase codepoint, add 32: `]+32* ...`
5. Note that step (2) creates an implicit step (5): we started out by projecting from character to integer domain, so now that we're finished, we map those integers back onto characters.

Obviously this particular implementation only considers ASCII; but the approach could be extended to at least the basic multilingual plane in Unicode.
> 7 votes

# Answer
**C 64 63 59 55 chars**

```
main(c){while(c=getchar(),~c)putchar(c-65u<27?c+32:c);}

```
> 7 votes

# Answer
**Golfscript - 17**

Program:

```
{..64>\91<*32*+}%

```

Explanation:

1. `{}%` maps the code inside to every character in string.
2. `..` copies the top of the stack (the character) twice.
3. `64>` 1 if character code is greater than 64, else 0.
4. `\` swaps the two items on the stack (gets the second copy of the letter, and stores the result of `64>` in position two).
5. `91<` checks to see if character code is less than 91. Similar to step 3.
6. `*` multiplies the results from steps 3 and 5 together. Only equal to 1, if both steps were true.
7. `32*` multiplies the result of step 6 with 32. Will be 32 if step 6 was 1, else 0.
8. `+` add the result (either 32 or 0) onto the character code.

Example output:

```
echo HelLO @ WorLD | ruby golfscript.rb upper_to_lower.gs
hello @ world

```
> 6 votes

# Answer
# 05AB1E, 3 bytes

```
u.š

```

Port of *@user8777* Python 3 answer.

Try it online.

**Explanation:**

```
u    # Convert the (implicit) input to uppercase
 .š  # Switch the case (upper to lower and vice-versa)
     # (and output the result implicitly)

```

---

But without any case-altering builtins:

# 05AB1E, ~~12~~ ~~11~~ 6 bytes

```
žn2ä`‡

```

-1 byte thanks to *@Emigna*.
-5 bytes thanks to *@TheThonnu*

Try it online.

**Explanation:**

```
žn      # Push builtin string "ABC...XYZabc...xyz"
  2ä    # Split it into two equal-sized parts: ["ABC...XYZ", "abc...xyz"]
    `   # Pop and push the strings separately to the stack
     ‡  # Transliterate all uppercase letters to lowercase ones
        # (after which the result is output implicitly)

```
> 5 votes

# Answer
# Perl: 24 characters

```
s/[A-Z]/chr 32+ord$&/ge

```

Sample run:

```
bash-4.1$ perl -pe 's/[A-Z]/chr 32+ord$&/ge' <<< 'Hello @ WORLD !'
hello @ world !

```
> 4 votes

# Answer
## javascript 80

```
"X".replace(/[A-Z]/g,function($){return String.fromCharCode($.charCodeAt()+32)})

```

(76 if you remove `"X"`)

with `prompt` and `alert` \- **92**

```
alert(prompt().replace(/[A-Z]/g,function($){return String.fromCharCode($.charCodeAt()+32)}))

```

fiddle

thanks to @FireFly @some @C5H8NNaO4 and @minitech
> 3 votes

# Answer
### JavaScript - ~~109~~ 104 (ES6: 95)

Thanks to some for the corrected version.

```
a=prompt();for(b=[i=0];c=a.charCodeAt(i);)b[i++]=String.fromCharCode(c|(c>64&c<91)*32);alert(b.join(""))

```

The following works if the browser supports ES6 function expressions:

```
alert(prompt().split("").map(c=>String.fromCharCode(c.charCodeAt()|(c>"@"&c<"[")*32)).join(""))

```
> 3 votes

# Answer
**DELPHI**

```
const
  UpChars:set of AnsiChar = ['A'..'Z'];
var
  I: Integer;
begin
  SetLength(Result, Length(pString));
  for I := 1 to length(pstring) do
    Result[i] := AnsiChar((Integer(pString[i] in UpChars))*(Ord(pString[i])+32));
  WriteLn(Result);
end;

```
> 3 votes

# Answer
### Perl 18

```
s/[A-Z]/$&|" "/eg

```

Something like:

```
perl -pe 's/[A-Z]/$&|" "/eg'  <<<'are NOT allowed to: ToLower() in .NET, strtolower() in PHP'
are not allowed to: tolower() in .net, strtolower() in php

```

and

```
perl -pe 's/[A-Z]/$&|" "/eg' <<< "The input string Doesn't cOntaIn...( C0D3-@01F. ;-)"
the input string doesn't contain...( c0d3-@01f. ;-)

```

For @FireFly :

```
perl -pe 's/[A-Z]/$&|" "/eg' <<< "Doesn't this translate @ to \` and [\]^_ to {|}~DEL? "
doesn't ... @ to ` and [\]^_ to {|}~del?

```

no.

### More generic: 18 chars anyway:

~~```
s/[A-Z]/$&|" "/eg

```~~
```
s/[A-Z]/$&^" "/eg

```

This wont change anything in state:

```
perl -pe 's/[A-Z]/$&^" "/eg' <<< "Doesn't ... @ to \` and [\]^_ to {|}~DEL? "
doesn't ... @ to ` and [\]^_ to {|}~del?

```

All work fine, but the advantage of changing `|` (or) by `^` (xor) is that the same syntax could be used for `toLower`, `toUpper` or `swapCase`:

toUpper:

```
perl -pe 's/[a-z]/$&^" "/eg' <<< "Doesn't ... @ to \` and [\]^_ to {|}~DEL? "
DOESN'T ... @ TO ` AND [\]^_ TO {|}~DEL?

```

and swapCase **(18+1 = 19 chars)**:

```
perl -pe 's/[a-z]/$&^" "/egi' <<< "Doesn't ... @ to \` and [\]^_ to {|}~DEL? "
dOESN'T ... @ TO ` AND [\]^_ TO {|}~del?

```
> 3 votes

# Answer
# x86-16 machine code, 15 bytes

Assembled:

```
ac3c 417c 063c 5a7f 020c 20aa e2f2 c3

```

Unassembled listing:

```
       _LOOP:
 AC         LODSB            ; load byte from [SI] into AL, advance SI
 3C 41      CMP  AL, 'A'     ; is char less than 'A'?
 7C 06      JL   _STORE      ; if so, do not convert
 3C 5A      CMP  AL, 'Z'     ; is char greater than 'Z'?
 7F 02      JG   _STORE      ; if so, do not convert
 0C 20      OR   AL, 'a'-'A' ; lowercase the char
       _STORE:
 AA         STOSB            ; store char to [DI], advance DI
 E2 F2      LOOP _LOOP       ; continue loop through string
 C3         RET              ; return to caller

```

Callable near function. Input string in `DS:[SI]`, length in `CX`. Output string in `ES:[DI]`.

Output from PC DOS test program:
> 3 votes

# Answer
# K (ngn/k), ~~19~~ 17 bytes

```
{`c$x+32*~"A["'x}

```

Try it online!

Avoids using the `floor` builtin (`_:`).

* `~"A["'` generate a bit mask with 1's in the positions in the input containing uppercase letters
* `32*` multiply by 32, which calculates the offsets between uppercase and lowercase ASCII character codes
* `x+` add the offsets to the input (converting the string input to integers)
* ``c$` convert back to characters
> 3 votes

# Answer
## R

### 71 characters:

```
chartr(paste(LETTERS,collapse=""),paste(letters,collapse=""),scan(,""))

```

### 83 characters:

```
a=as.integer(charToRaw(scan(,"")))
b=a%in%(65:90)
a[b]=a[b]+32
rawToChar(as.raw(a))

```
> 2 votes

# Answer
# Q, 18

.....

```
{x^ssr/[x]..Q`a`A}

```
> 2 votes

# Answer
## PHP (42)

Run from the command line:

```
-R'echo@str_ireplace($a=range(a,z),$a,$argn);'

```

`-R` and the single quotes are not counted.
> 2 votes

# Answer
# Q (16)

.......

```
{x^(.Q.A!.Q.a)x}

```
> 2 votes

# Answer
# Python (33)

If in doubt, use the shell.

```
import os;os.system('tr A-Z a-z')

```

Regrettably, this is still longer than Lego's solution.
> 2 votes

# Answer
## PowerShell: 69 65 64

I've tried a half-dozen ways to get Replace to work the way I want it to without using the long `[regex]::Replace` syntax, but I haven't had any luck. If anyone else has an idea of what might work, please do suggest it.

**Golfed code:**

```
[regex]::Replace((read-host),"[A-Z]",{[char](32+[char]"$args")})

```

> **Changes from original:**
>
> * Rearranged last argument so that `[int]` is no longer needed, per suggestion in comments.

**Explanation:**

`(read-host)` gets the user input.

`[regex]::Replace(`...`)` tells PowerShell to use RegEx matching to perform replacement operations on a string.

`"[A-Z]"` matches all uppercase letters.

`{`...`}` tells PowerShell to use a script to determine the replacement value.

`[char]"$args"` takes the current match and types it as an ASCII character.

`32+` converts the character to an integer, representing the ASCII code, and increases the value by 32 - which would match ASCII code of the corresponding lowercase letter.

`[char](`...`)` takes the resulting value and converts it back to an ASCII character.

Demo of original:

(Current version tested - screenshot not yet posted.)
> 2 votes

# Answer
# k2, 15 bytes

I am *super* late to this one, but I found this cool anyway.

```
{_ci 32+_ic x}'

```

Also:

# Pyth, 10 bytes

Doesn't really count because Pyth was created after this was posted. Still cool.

```
jkmC+32Cdw

```
> 2 votes

# Answer
# PowerShell, ~~53~~ ~~49~~ 43 bytes

*-4 bytes thanks @AdmBorkBork*

*-6 bytes thanks @Veskah*

```
-join($args|%{[char](32*($_-in65..90)+$_)})

```

Try it online!
> 2 votes

# Answer
## Vim, 6 bytes

`gUUg~~`

Or, if allowed,

## Vim, 3 bytes

`guu`
> 2 votes

# Answer
Just for fun, because Java's my language.

# Java - ~~162~~ 175

Fixed for OP's updates.

```
class a{public static void main(String[]a){String b="";for(char c:new java.util.Scanner(
System.in).nextLine().toCharArray())b+=c>64&&c<91?(char)(c+32):c;System.out.print(b);}}

```

**With line breaks and tabs**

```
class a{

    public static void main(String[]a){
        String b="";
        for(char c:new java.util.Scanner(System.in).nextLine().toCharArray())b+=c>64&&c<91?(char)(c+32):c;
        System.out.print(b);
    }

}

```
> 1 votes

# Answer
# Python 3 - 70

Updated for OP's changes.

I'm a Python newbie, so any critique is welcome.

```
print("".join(chr(ord(c)+32) if 64<ord(c)<91 else c for c in input()))

```
> 1 votes

# Answer
# Javascript, 105

```
prompt().split("").map(function(a){c=a.charCodeAt(0);return String.fromCharCode(c|(c-64?32:0))}).join("")

```

 Actually ther was no output form specified, so run it in console Yea, JavaScript really is verbose with charcode \<-\> string
> 1 votes

# Answer
Ruby: 66

```
def l(s)s.bytes.map{|b|(65..90).include?(b)?b+32:b}.pack('c*');end

```
> 1 votes

# Answer
## C# - 108

```
class P{static void Main(string[]a){foreach(var c in a[0])System.Console.Write(
(char)(c>64&&c<91?c+32:c));}}

```

About 70 for just the method body.

Add 5 chars to include a LF/CR in the output:

```
class P{static void Main(string[]a){foreach(var c in a[0]+"\n")System.Console.Write(
(char)(c>64&&c<91?c+32:c));}}

```

A LINQ version would be shorter:

```
class P{static void Main(string[]a){a[0].Any(c=>System.Console.Write(
(char)(c>64&&c<91?32+c:c))is P);}}

```

(103) .. except that it requires `using System.Linq;` (total: 121).
> 1 votes

# Answer
# Haskell - 58

```
p x|(elem x['A'..'Z'])=[x..]!!32|1<2=x
main=interact$map p

```
> 1 votes

# Answer
## Perl, 9 + 1 (for -p flag) = 10

```
$_="\L$_"

```

`\L` was specifically asked about and allowed, because even though it's a built-in, it's not a function.
> 1 votes

# Answer
# , 39 30 bytes

```
(<&91*64&<)`(,:32+])}&.(a.i.])

```

*-9 thanks to xash*

Try it online!

Uses Item Amend `}` to choose which characters need to be lowercased and which passed through unaltered.

It applies this operation "under" conversion to ascii indexes `&.(a.i.])` -- it first converts the string to the indexes of its characters, than applies the item amend transformation, then converts back.

The item amend transformation is defined by the gerund `(<&91*64&<)`(,:32+])`. `(,:32+])` defines the two possibilities: the input unaltered, or the the input shifted 32 places to the right, converting `A` to `a`, etc. `(<&91*64&<)` determines which integers go into which transformation category: If an integer is greater than 64 and less than 91 -- ie, the integers corresponding to `ABCDEFGHIJKLMNOPQRSTUVWXYZ` -- it gets shifted by 32.
> 1 votes

# Answer
# naz, ~~92~~ 90 bytes

```
2x1v8a8m2x2v2d3m5s2x3v1x1f1r3x1v4e3x2v2g1o1f0x1x2f3x3v3l1o1f0x1x3f8a8a8a8a1o1f0x1x4f0a0x1f

```

Works for any null-terminated input string.

Try it online!

**Explanation** (with `0x` instructions removed)

```
2x1v                   # Set variable 1 equal to 0
8a8m2x2v               # Set variable 2 equal to 64 ("@")
2d3m5s2x3v             # Set variable 3 equal to 91 ("[")
1x1f1r3x1v4e3x2v2g1o1f # Function 1
                       # Read a byte of input
                       # Goto function 4 if it equals variable 1
                       # Goto function 2 if it's greater than variable 2
                       # Otherwise, output it and call the function again
1x2f3x3v3l1o1f         # Function 2
                       # Goto function 3 if the register is less than variable 3
                       # Otherwise, output and jump to function 1
1x3f8a8a8a8a1o1f       # Function 3
                       # Add 32 to the register, output, and call function 1
1x4f0a                 # Function 4
                       # Add 0 to the register
1f                     # Call function 1

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
⇧N

```

Try it Online!

This is the same as the 05ab1e answer but shorter because overloads.

## Non-trivial version

```
kAkaĿ

```

Try it Online!

Funnily enough, I've used this before.

```
kAka    # Push "ABC...XYZ" and "abc...xyz"
    Ŀ   # Transliterate input with the above strings

```
> 1 votes

# Answer
# Julia, 28 bytes

```
x->map(c->c+32('@'<c<'['),x)

```

Try it online!
> 1 votes

# Answer
# *Acc!!*, 44 bytes

```
N
Count i while _ {
Write _+_/65*90/_*32
N
}

```

Outputs with a trailing newline. Try it online!

### Explanation

The joke's on you, OP: *Acc!!* doesn't even *have* built-in to-lower functions... \>:^D

`N` reads a byte from stdin into the accumulator; then we loop while that value is nonzero (i.e. we haven't yet reached end-of-input). We want to add 32 to the character code iff the input is an uppercase letter--that is, if its character code is between 65 and 90. Lacking comparison operators, we use int division:

```
Code range | _/65 | 90/_ | (_/65)*(90/_)
-----------|------|------|--------------
32-64      | 0    | >0   | 0
65-90      | 1    | 1    | 1
90-126     | >0   | 0    | 0

```

Now observe that `_/65` will always be either 0 or 1 for all values of `_` in the range we're interested in. So we can drop the parentheses: `_/65*90/_` is equivalent to `(_/65*90)/_`, which is `90/_` if `_` is \>= 65 and `0` otherwise. Thus, our conditional lowercase formula is simply `_+_/65*90/_*32`. We write the corresponding character, read a new one, and loop.
> 1 votes

# Answer
# JavaScript (Node.js), 53 bytes

```
s=>s.replace(/[A-Z]/g,x=>parseInt(x,36).toString(36))

```

Try it online!

From 12Me21's
> 1 votes

# Answer
# Python - ~~96~~ ~~94~~ 82

```
for c in input():print(chr(ord(c)-65+97),end="")if c.isupper()else print(c,end="")

```

Ungolfed version:

```
for char in input():
    print(chr(ord(char) - (ord("A") - ord("a"))), end="") if char.isupper() \
    else print(char, end="")

```
> 0 votes

# Answer
Because I felt like it (I know that I'm a bit late)

# Java - 162

```
class a{public static void main(String[]a){for(char c:(new java.util.Scanner(System.in)).nextLine().toCharArray())System.out.print((char)((c>64&&c<91)?c+32:c));}}

```

expanded:

```
public class a{
    public static void main(String[] a) {
        for (char c : (new java.util.Scanner(System.in)).nextLine().toCharArray()) {
            System.out.print((char) ((c > 64 && c < 91) ? c + 32 : c));
        }
    }
}

```
> 0 votes

# Answer
# Java - 119

```
class a{static{for(char c:(new java.util.Scanner(System.in)).nextLine().toCharArray())System.out.print((char)(c|32));}}

```

Works for every character except `@` which becomes the back-tick (```), and the following (foo:bar for foo becomes bar) :

```
\:|
]:}
^:~
_:

```

Even though this isn't a true solution because it has 5 cases where it doesn't work, I thought it was very interesting. It takes the characters of the input and does a bitwise or with `' '` (`c|32`).

I discovered that `c^32` swaps the case when the input is only letters while solving a project euler problem. I wondered what would happen in I changed the XOR to an OR.
> 0 votes

# Answer
## Game Maker Language, 228

Make script/function `s` with this code, **53** characters:

```
a=argument0;b=string_replace_all(b,string_upper(a),a)

```

Then, use this **175** character code:

```
b=get_string('','')s('a')s('b')s('c')s('d')s('e')s('f')s('g')s('h')s('i')s('j')s('k')s('l')s('m')s('n')s('o')s('p')s('q')s('r')s('s')s('t')s('u')s('v')s('w')s('x')s('y')s('z')

```

The input (stored in variable `b`), is now lowercase.
> 0 votes

# Answer
# JavaScript 124

The closest I got was 124 characters...

```
b=prompt();a=[];for(c=b.length;c--;)a[c]="@"b[c]?String.fromCharCode(b[c].charCodeAt(0)+32):b[c];alert(a.join(""))

```

@Firefly, nice work with using the "map" command... I've yet to master it...
> 0 votes

# Answer
# Powershell - 81 characters

## Program:

```
param($s);[char[]]$s|%{if($_-lt90-and$_-gt64){$n+=[char](+$_+32)}else{$n+=$_}};$n

```

## Example Usage:

```
.\lower.ps1 -s "TEST!"

```

## Output:

```
test!

```

## How it works:

It just adds 32 to the decimal value of the ASCII character, which is the lowercase version.
It only does this if it is within 64-90, which is all capital letters.
> 0 votes

# Answer
### Delphi XE3 (153 chars)

```
uses System.SysUtils;var u:string;i:int8;begin readln(u);for i:=1to Length(u)do if CharInSet(u[i],['A'..'Z'])then u[i]:=Chr(Ord(u[i])+32);writeln(u);end.

```

Not a winner but fun to do :)

### with indent

```
uses
  System.SysUtils;
var
  u:string;
  i:int8;
begin
  readln(u);
  for i:=1to Length(u)do
    if CharInSet(u[i],['A'..'Z'])then
      u[i]:=Chr(Ord(u[i])+32);
    writeln(u);
end.

```
> 0 votes

# Answer
## J 35

```
echo(+32*64&<*.95&>)&.(a.&i.)1!:1]3

```

Using the magical under `&.`. This looks up the ascii code, then adds 32 * the boolean `inRange` , where `inRange` is `x>64 and x<91`. The under operation automatically applies the inverse lookup afterwards, resulting in the wanted lowercase.

In action:

```
   echo(+32*64&<*.91&>)&.(a.&i.)1!:1]3
Hello World AZ!
hello world az!

```
> 0 votes

# Answer
## Python 3, 78 bytes

```
t=input()
for c in t:
 x=ord(c)
 if 64<x<91:t=t.replace(c,chr(x+32))
print(t)

```
> 0 votes

# Answer
# Japt, ~~7~~ 5 bytes

```
;dBíC

```

Try it here
> 0 votes

# Answer
# 37 bytes

```
{$[x in .Q.A;x:(.Q.A!.Q.a)[x];x]}each

```

# Explanation

```
$[x in .Q.A          // If the character is in the capitals list
  x:(.Q.A!.Q.a)[x]   // Create a key mapping between upper and lower case letters,
                     // and set x to it's pair
  x]}                // else, just return the character
  each               // apply to each character in string passed in

```

# Example

```
q){$[x in .Q.A;x:(.Q.A!.Q.a)[x];x]}each "LoWersWFSfdgSA"
"lowerswfsfdgsa"

```
> 0 votes

# Answer
# JavaScript, 58 bytes

```
s=>s.replace(/[A-Z]/g,x=>(x.charCodeAt()-55).toString(36))

```
> 0 votes

# Answer
# Forth (gforth), 55 bytes

```
: f 0 do dup i + c@ dup 65 91 within 32 * - emit loop ;

```

Try it online!

### Explanation

Iterates through the string, for each character:

* Gets the ascii value of the character
* If between 65 and 90 (inclusive) add 32, else leave as is
* Print the char corresponding to that value

### Code Explanation

```
: f                   \ start new word definition
  0 do                \ start counted loop from 0 to string-length - 1
    dup i +           \ duplicate the string address and add the loop index
    c@                \ get the ascii char value at that address
    dup 65 91 within  \ check if value is between 65 and 90 (-1 = true, 0 = false)
    32 * -            \ multiply result by 32 and subtract from original number
    emit              \ output value
  loop                \ end loop
;                     \ end word definition

```
> 0 votes

# Answer
# \>\<\>, 17 bytes

```
i::" @["{)${(**+o

```

Try it online!
> 0 votes

# Answer
# JavaScript(ES6), 92/90 bytes

```
prompt().split('').map(x=>String.fromCharCode((y=x.charCodeAt(),y>64&y<91)?y+32:y)).join('')

```

```
l=a=>a.split('').map(x=>String.fromCharCode((y=x.charCodeAt(),y>64&y<91)?y+32:y)).join('')

```

Turn the input string into a char array, turn all uppercase letters into lowercase, and turn it back into a string.(Difference between uppercase letter and lowercase letter('a'-'A') is 32, 64 is '@', 91 is '\['.)

If using alerts is required, that increases the characters by 7, which means it's 99 bytes.
> 0 votes

# Answer
# FALSE, 29 bytes

```
[^$1_=~][$$64>\91>~&[32+]?,]#

```

Try it online!
> 0 votes

# Answer
# ///, 113 bytes

```
/~/\/\///Q/q~W/w~E/e~R/r~T/t~Y/y~U/u~I/i~O/o~P/p~A/a~S/s~D/d~F/f~G/g~H/h~J/j~K/k~L/l~Z/z~X/x~C/c~V/v~B/b~N/n~M/m/

```

Try it online!

Simply replaces all the uppercase characters with lowercase. Because there's no other way to take input in ///, it is hardcoded:

```
/~/\/\///Q/q~W/w~E/e~R/r~T/t~Y/y~U/u~I/i~O/o~P/p~A/a~S/s~D/d~F/f~G/g~H/h~J/j~K/k~L/l~Z/z~X/x~C/c~V/v~B/b~N/n~M/m/INPUT

```
> 0 votes

# Answer
# batch 112 bytes

**lower.bat**

```
@Set "s=%~1"&@for %%c in (a b c d e f g h i j k l m n o p q r s t u v w x y z)do @Set "s=!s:%%c=%%c!"
@Echo(!s!

```

*Notes:*

* requires cmd.exe's codepage to be `430` or `850`, to change codepage, use: `CHCP 430` or `CHCP 850`
* Must be started in the directory containing **`lower.bat`** using:
`Echo(Lower "String to convert"|CMD /V:On`
> 0 votes

# Answer
# C (gcc), ~~61~~ 59 bytes

*-2 thanks to @ceilingcat*

```
main(i){while(i=getchar()-10)putchar(i+(i>54&i<81?42:10));}

```

Try it online!

Ungolfed:

```
int main(i){
    while((i=getchar()) != '\n') {
        if(i>64&i<91){ // uppercase ASCII range is 65-92
            putchar(i+32); // lowercase ASCII range is 97-122
        } else {
            putchar(i);
        }
    }
}

```
> 0 votes

# Answer
# mmo (MMIX executable), 112 bytes (28 tetras)

(jxd)

```
00000000: 98090100 98010001 00000100 e0002000  Ƭµ¢¡Ƭ¢¡¢¡¡¢¡ṭ¡ ¡
00000010: e3ff0140 00000300 58ff0002 00000000  ẉ”¢@¡¡¤¡X”¡£¡¡¡¡
00000020: 83010000 31ff0140 7502ff20 31ff015b  ³¢¡¡1”¢@u£” 1”¢[
00000030: 7002ff02 c0010102 a3010000 e3ff0140  p£”£Ċ¢¢£ɲ¢¡¡ẉ”¢@
00000040: 00000601 f1fffff3 00000000 20000000  ¡¡©¢ȯ””ṙ¡¡¡¡ ¡¡¡
00000050: 98020008 00000001 980a00ff 00000000  Ƭ£¡®¡¡¡¢Ƭ½¡”¡¡¡¡
00000060: 00000100 980b0000 00000000 980c0001  ¡¡¢¡Ƭ¿¡¡¡¡¡¡Ƭ€¡¢

```

Disassembly and explanation:

```
98090100 lop_pre 1,0                (mmo v1, 0 tetras)
98010001 lop_loc 0,1                (start loading at next tetra)
00000100 256                        (which is 256)
E0002000    SETH $0,#2000           (set $0 to address of data segment)
E3FF0140 0H SETL $255,2F            (set $255 to address of handle)
00000300    TRAP 0,Fread,StdIn      (read in one character)
58FF0002    PBNN $0,1F              (skip next instr if not EOF)
00000000    TRAP 0,Halt,0           (quit)
83010000 1H LDBU $1,$0,0            (read that byte in)
31FF0140    CMP  $255,$1,'@'        (compare with '@')
7502FF20    ZSP  $2,$255,#20        (if greater, then set $2 to 0x20)
31FF015B    CMP  $255,$1,'['        (compare with '[')
7002FF02    ZSN  $2,$255,$2         (unless less, clear $2)
C0010102    OR   $1,$1,$2           (or in $2)
A3010000    STBU $1,$0,0            (store it back)
E3FF0140    SETL $255,2F            (set $255 to address of handle)
00000601    TRAP 0,Fwrite,StdOut    (write that byte out)
F1FFFFF3    JMP  0B                 (loop back)
00000000                            (padding for alignment)
20000000 2H OCTA Data_Segment,1     (the handle)
98020008 lop_skip 8                 (slightly cheaper than two zero tetras)
00000001                            (end of handle)
980A00FF lop_post 255               (postamble, rG = 255)
00000000
00000100                            (start execution at location 256)
980B0000 lop_stab                   (begin symbol table)
00000000                            (no symbols)
980C0001 lop_end 1                  (symtab is one tetra long)

```
> 0 votes

# Answer
# MATLAB/Octave, 29 bytes

```
@(x)char(x+32*(x>64).*(x<91))

```

Try it online!
Output to standard output variable `Ans` and written to command window.
> 0 votes

# Answer
# Thunno 2, 2 bytes

```
RP

```

Attempt This Online! Port of user8777's Python answer.

## Thunno 2, 4 bytes

```
kAẠṆ

```

Attempt This Online! No uppercase/swap-case built-ins here.

## Thunno 2, 12 bytes

```
ıDkAsƇ?C32+C

```

Attempt This Online! No uppercase/swap-case/transliterate built-ins here.

#### Explanation

```
RP  # Implicit input
R   # Convert to uppercase
 P  # Swap the case of each character
    # Implicit output

```

```
kAẠṆ  # Implicit input
   Ṇ  # Transliterate the input
kA    # (from) the uppercase alphabet
  Ạ   # (to) the lowercase alphabet
      # Implicit output

```

```
ıDkAsƇ?C32+C  # Implicit input
ı             # Map over the input string:
 D            #  Duplicate it
    sƇ        #  Pop one copy, and check if it's in
  kA          #  the uppercase alphabet
      ?       #  If it is:
       C      #   Convert to codepoint
        32+   #   Add 32
           C  #   And convert to character
              #  Otherwise, the character stays on top
              # Implicit output, joined

```
> 0 votes

# Answer
# Itr, 17 bytes

`#µ»ä26¹64+=S32*+«`

Reads string (surrounded by quotes) from standard input, prints the result to standard output

online interpreter

# Explanation

<pre><code>#             ; read the string from standard input
 µ»   «       ; apply to each element
              ; implicitly print the result

ä             ; duplicate the character
 26¹64+       ; push the range from 65 to 90 ('A' through 'Z')
       =      ; vectorized equality check (of character and range)
        S     ; sum up the vector (1 if the char is in range, 0 otherwise)
         32*+ ; multiply by 32 and add to the character
```

> 0 votes

# Answer
`bash`: 11 characters?

```
$ i="This is A STRING"
$ echo ${i,,}
this is a string

```
> -1 votes

---
Tags: code-golf, printable-ascii
---


# Question
Title: Generate a pair of integers from a non-negative one
You should write a program or function which takes a non-negative integer `N` as input and outputs or returns two integers (negative, zero or positive) `X` and `Y`.

Integers are meant in the mathematical sense as there are infinitely many of them.

The implemented function has to be bijective. This means that for every `N` it has to output a different `X` `Y` pair and every `X` `Y` pair should be outputted for some input `N` i.e. all of the following pairs should be outputted for some `N`:

```
                 ...
    ┌─────┬─────┬────┬────┬────┐
    │-2 -2│-2 -1│-2 0│-2 1│-2 2│
    ├─────┼─────┼────┼────┼────┤
    │-1 -2│-1 -1│-1 0│-1 1│-1 2│
    ├─────┼─────┼────┼────┼────┤
... │0 -2 │0 -1 │0 0 │0 1 │0 2 │ ...
    ├─────┼─────┼────┼────┼────┤
    │1 -2 │1 -1 │1 0 │1 1 │1 2 │
    ├─────┼─────┼────┼────┼────┤
    │2 -2 │2 -1 │2 0 │2 1 │2 2 │
    └─────┴─────┴────┴────┴────┘
                 ...

```

Note that `U V` and `V U` are different pairs if `U!=V`.

## Details

* If your language doesn't support arbitrarily large integers that's fine but your algorithm should work with an arbitrarily large integer data-type. Your code should still support input values for at least `2^31-1`.
* If you choose to print or return the output as string no leading `0`'s or `+` signs are allowed. Otherwise your language's standard integer representation is fine.

## Example

**If** the task would be to make a bijective function taking a non-negative integer `N` and output **one** integer `X` a solution could be the function

`if (input mod 2 == 0) return N/2 else return -(N+1)/2`,

implemented in some language. This function returns `X = 0 -1 1 -2 2...` for `N = 0 1 2 3 4...`.

# Answer
# Pyth, 15

```
u,-HyeGhGjQ2,ZZ

```

Try it online.

```
u             reduce
                lambda G,H:    [implicit]
  ,-HyeGhG         (H-2*G[-1],G[0])
  jQ2           base(input(),2)
  ,ZZ           (0,0)
              print result     [implicit]

```

A Python translation:

```
g=lambda Z,n:(n-2*Z[1],Z[0])
print reduce(g,binlist(input()),(0,0))

```

or iteratively:

```
(x,y)=(0,0)
for b in binlist(input()):
    (x,y)=(b-2*y,x)
print (x,y)

```

where `binlist` converts a number to a list of digits like `binlist(4) = [1,0,0]`.

So, how does this work? It interprets the binary digits of the number \\$n\\$ as two interleaved numbers in base negative two like in my Python solution.

The binary number $$n=\dots b\_5 b\_4 b\_3 b\_2 b\_1 b\_0 $$ corresponds to the pair $$ (x,y) = (b\_0 - 2 b\_2 + 4 b\_4 - 8 b\_6 + \cdots, b\_1 - 2 b\_3 + 4 b\_5 - 8 b\_7 + \cdots).$$

If we hadn't yet processed the last digit \\$b\_0\\$ of \\$n\\$, we'd have all indices higher by $1$, $$n'=\dots b\_5 b\_4 b\_3 b\_2 b\_1 $$ corresponding to the pair $$ (x',y') = (b\_1 - 2 b\_3 + 4 b\_5 - 8 b\_7 + \cdots, b\_2 - 2 b\_4 + 4 b\_6 - 8 b\_8 + \cdots).$$

We can then express the new values once \\$b\_0\\$ is read in terms of the old values

$$(x,y) = (b\_0 - 2y', x').$$

So, by repeatedly performing the transformation \\$(x,y) \to (b - 2y, x)\\$ on each successive bit \\$b\\$ of \\$n\\$, we build the point \\$(x,y)\\$ that comes from extracting its digits.
> 14 votes

# Answer
# CJam, ~~24~~ ~~22~~ 21 bytes

My brain has trouble understanding the math other solutions are using. But my brain definitely understands binary, so here's a soultion based on bit manipulation!

```
li4b2fmd2/z{)(\2b^}%p

```

Try it online.

### Explanation

This approach treats the input as two interleaved binary values, one for each output number. All but the least significant bit of each encode a magnitude, and the least significant bit signals whether or not to take the bitwise complement of this magnitude. In this implementation, the odd-positioned bits correspond to the first output number (and the even-positioned bits correspond to the second) and an LSB of `0` signals to take the complement.

For example, given an input of `73`, uninterleaving its binary representation of `1001001b` produces `0 1|0` (odd-positioned bits) and `1 0 0|1` (even-positioned bits). The first value has a magnitude of `01b = 1` and should be complemented for a final value of `~1 = -2`, and the second value has a magnitude of `100b = 4` and should not be complemented.

### Informal demonstration of correctness

I made a testing program that places each input from zero to a user-specified number minus one in its output location on a 2D grid. You can try it online as well. Here's an output of this program showing how the algorithm maps `0-99`:

```
      -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8

-8                      92 84 86 94
-7                      88 80 82 90
-6                      76 68 70 78
-5                   96 72 64 66 74 98
-4                60 52 28 20 22 30 54 62
-3                56 48 24 16 18 26 50 58
-2                44 36 12  4  6 14 38 46
-1                40 32  8  0  2 10 34 42
 0                41 33  9  1  3 11 35 43
 1                45 37 13  5  7 15 39 47
 2                57 49 25 17 19 27 51 59
 3                61 53 29 21 23 31 55 63
 4                   97 73 65 67 75 99
 5                      77 69 71 79
 6                      89 81 83 91
 7                      93 85 87 95
 8

```

The fill pattern looks a bit weird, but it is in fact bijective! With each successive power of 4, it fills a square with double the previous side length. For example, here's how the algorithm maps `0-15`:

```
      -2 -1  0  1  2

-2    12  4  6 14
-1     8  0  2 10
 0     9  1  3 11
 1    13  5  7 15
 2

```

This makes up the 4x4 square in the middle of the 8x8 square of `0-63`:

```
      -4 -3 -2 -1  0  1  2  3  4

-4    60 52 28 20 22 30 54 62
-3    56 48 24 16 18 26 50 58
-2    44 36 12  4  6 14 38 46
-1    40 32  8  0  2 10 34 42
 0    41 33  9  1  3 11 35 43
 1    45 37 13  5  7 15 39 47
 2    57 49 25 17 19 27 51 59
 3    61 53 29 21 23 31 55 63
 4

```

Which makes up the 8x8 square in the middle of the 16x16 square of `0-255`:

```
         -8  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7   8

 -8     252 244 220 212 124 116  92  84  86  94 118 126 214 222 246 254
 -7     248 240 216 208 120 112  88  80  82  90 114 122 210 218 242 250
 -6     236 228 204 196 108 100  76  68  70  78 102 110 198 206 230 238
 -5     232 224 200 192 104  96  72  64  66  74  98 106 194 202 226 234
 -4     188 180 156 148  60  52  28  20  22  30  54  62 150 158 182 190
 -3     184 176 152 144  56  48  24  16  18  26  50  58 146 154 178 186
 -2     172 164 140 132  44  36  12   4   6  14  38  46 134 142 166 174
 -1     168 160 136 128  40  32   8   0   2  10  34  42 130 138 162 170
  0     169 161 137 129  41  33   9   1   3  11  35  43 131 139 163 171
  1     173 165 141 133  45  37  13   5   7  15  39  47 135 143 167 175
  2     185 177 153 145  57  49  25  17  19  27  51  59 147 155 179 187
  3     189 181 157 149  61  53  29  21  23  31  55  63 151 159 183 191
  4     233 225 201 193 105  97  73  65  67  75  99 107 195 203 227 235
  5     237 229 205 197 109 101  77  69  71  79 103 111 199 207 231 239
  6     249 241 217 209 121 113  89  81  83  91 115 123 211 219 243 251
  7     253 245 221 213 125 117  93  85  87  95 119 127 215 223 247 255
  8

```
> 31 votes

# Answer
## Python 2, 49

Edit: Improved to 49 by using better one-step recursion for base -2.

```
def f(n):x,y=n and f(n/2)or(0,0);return n%2-2*y,x

```

Here's a Pyth version using `reduce`.

Edit: Improved to 52 by switching to base -2 from balanced ternary.

**Python 2, 52**

```
h=lambda n:n and n%2-2*h(n/4)
lambda n:(h(n),h(n/2))

```

---

**Python 2, 54**

```
h=lambda n:n and-~n%3-1+3*h(n/9)
lambda n:(h(n),h(n/3))

```

This uses digit interleaving like Runer112's solution, but with balanced ternary rather than signed binary. Python doesn't have built-in base conversion, so the code implements it recursively.

The helper function `h` (with `3` in place of the `9`) takes a natural number and converts it from ternary to balanced ternary with the digit substitutions

```
0 -> 0
1 -> +1
2 -> -1

```

So, for example, 19, which is 201 in base, becomes (-1)(0)(+1) in balanced ternary, which is (-1)\*3^2 +(0)\*3^1+(+1)\*3^0 = -8.

Balanced ternary suffices to encode every integer, and so gives a mapping from natural numbers to integers.

To map to pairs of integers, we interleave the digits in `n`. To do so, we have `h` look at every other digit by doing `n/9` as the recursive step rather than `n/3`. Then, for one coordinate, we shift `n` by floor-dividing by `3`.

Here are the first 81 outputs, which cover the region \[-4,4\]^2.

```
0 (0, 0)
1 (1, 0)
2 (-1, 0)
3 (0, 1)
4 (1, 1)
5 (-1, 1)
6 (0, -1)
7 (1, -1)
8 (-1, -1)
9 (3, 0)
10 (4, 0)
11 (2, 0)
12 (3, 1)
13 (4, 1)
14 (2, 1)
15 (3, -1)
16 (4, -1)
17 (2, -1)
18 (-3, 0)
19 (-2, 0)
20 (-4, 0)
21 (-3, 1)
22 (-2, 1)
23 (-4, 1)
24 (-3, -1)
25 (-2, -1)
26 (-4, -1)
27 (0, 3)
28 (1, 3)
29 (-1, 3)
30 (0, 4)
31 (1, 4)
32 (-1, 4)
33 (0, 2)
34 (1, 2)
35 (-1, 2)
36 (3, 3)
37 (4, 3)
38 (2, 3)
39 (3, 4)
40 (4, 4)
41 (2, 4)
42 (3, 2)
43 (4, 2)
44 (2, 2)
45 (-3, 3)
46 (-2, 3)
47 (-4, 3)
48 (-3, 4)
49 (-2, 4)
50 (-4, 4)
51 (-3, 2)
52 (-2, 2)
53 (-4, 2)
54 (0, -3)
55 (1, -3)
56 (-1, -3)
57 (0, -2)
58 (1, -2)
59 (-1, -2)
60 (0, -4)
61 (1, -4)
62 (-1, -4)
63 (3, -3)
64 (4, -3)
65 (2, -3)
66 (3, -2)
67 (4, -2)
68 (2, -2)
69 (3, -4)
70 (4, -4)
71 (2, -4)
72 (-3, -3)
73 (-2, -3)
74 (-4, -3)
75 (-3, -2)
76 (-2, -2)
77 (-4, -2)
78 (-3, -4)
79 (-2, -4)
80 (-4, -4)

```

An alternative coding with quarter-imaginary turned out longer, though it is very pretty.

**Python 2, 63**

```
h=lambda n:n and n%4+2j*h(n/4)
lambda n:(h(n).real,h(n).imag/2)

```

In a language with less clunky handling of complex conversion, this would probably be a better approach. If we could output complex numbers, we could do:

**Python 2, 38**

```
f=lambda n:n and n%2+n/2%2*1j-2*f(n/4)

```
> 12 votes

# Answer
## Python 2, 98 bytes

Let's start out with a simple approach:

```
def f(N):
 x=a=0;b=2
 while N:x+=1j**b;b+=a<1;a=a or b/2;N-=1;a-=1
 return int(x.real),int(x.imag)

```

It just forms a rectangular spiral `N` units long on a 2d grid, starting from the origin, and returns the coordinates of the last point.

The function is bijective since:

* Each point can be covered, given a long enough spiral
* Each point will only be intersected by the spiral once

The spiral looks something like this (except starting at 0 rather than 1):
> 11 votes

# Answer
# dc, 49

```
[1+2~2*1-*n]sm?dsa8*1+v1-2/dd1+*2/lar-dlmx32P-lmx

```

This starts off by arranging the non-negative integers on a grid thus:

```
..|
4 | 14
3 |  9 13
2 |  5  8 12
1 |  2  4  7 11
0 |  0  1  3  6 10
Y +-----------------
  X  0  1  2  3  4 ...

```

Note that how the grid positions are filled diagonally with increasing N. Notice the Y=0 line contains the triangular number sequence, given by `N = X(X+1)/2`. This is a quadratic equation which is solved using the normal formula, using just the +ve root, so that we can determine X from N when Y=0. Next is some simple arithmetic shuffling to give unique {X,Y} for every N.

This provides the required bijective quality, but X and Y are only non-negative, but the question requires all possible integers. So X and Y are mapped using `((t+1)/2)*((t+1)~2*2-1)` to give all possible integers.

`dc` has arbitrary precision numbers, so input range to `2^31-1` is no problem. Note also that default precision is 0 decimal digits, and the `sqrt()` and `/` round down which is the behavior needed here.

### Output:

```
$ for i in {0..10}; do dc biject.dc <<< $i; echo; done
0 0
0 -1
-1 0
0 1
-1 -1
1 0
0 -2
-1 1
1 -1
-2 0
0 2
$

```
> 8 votes

# Answer
# Matlab, 54 bytes

```
n=input('')+1;[i,j]=find(spiral(2*n)==n);disp([i,j]-n)

```

The key here is `spiral`, this creates a spiral matrix of an arbitrary size.

```
spiral(3)

```

returns

```
ans =

 7     8     9
 6     1     2
 5     4     3

```

In Matlab, this works for integers, but you will get memory issues way before that, (well, I am assuming you as the command `spiral` creates a full matrix first, that has size of about \\$4n^2\\$. At around \\$n \simeq 10^4\\$ this matrix takes up more than 1GB of space. So with 1TB of RAM you will get to around \\$n \simeq 10^5\\$, and about \\$2.9\cdot 10^{11}\\$ GB of RAM will get you to \\$n=2^{32}\\$.
> 5 votes

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

```
-2/+2 2\0,4\

```

Attempt This Online! (ATO because the original ngn/k page isn't working at the time of posting)

Uses bit halving followed by base -2. `0,` is necessary to get `0 0` for input `0`.

```
-2/+2 2\0,4\
          4\    convert to base 4
        0,      prepend a 0
    2 2\        convert each to base 2, forcing two bits per a base-4 digit
                (base conversion happens column-wise, so the result here is
                 a two-row matrix)
   +            transpose
-2/             evaluate each column in base -2

```
> 5 votes

# Answer
# K (ngn/k), ~~72~~ ~~68~~ ~~66~~ ~~62~~ 53 bytes

```
{(-|:)/[0<d;0,d:m*x-1+s*s-1]+(m:*/s#-1)*2#-2!s:-_-%x}

```

Try it online!

-4 : Squeezed out a few bytes
-2 : A couple more
-4 : Oh yeah, we’re golfing…
-9 : Forgot ngn/k has sqrt
> 4 votes

# Answer
# , 11 bytes

```
_1j1+.@#.#:

```

Attempt This Online!

Uses complex base `-1 + i` to generate a Gaussian integer from the binary representation of the given nonnegative integer.

```
_1j1+.@#.#:
         #:  Convert to binary
_1j1   #.    Evaluate the binary sequence as base -1 + i
    +.@      Take apart its real and imaginary parts

```

If outputting a complex number were allowed, it would be 8 bytes (delete `+.@`).

I couldn't find a complete proof that this conversion is bijective, but this challenge mentions it, and I think the following argument is enough to prove it:

> Given a Gaussian integer, the lowest bit of base `-1 + i` representation is determined by `(real+imag)%2`. Subtract it and divide by `-1 + i`, and you always get another Gaussian integer with smaller magnitude (at least until it becomes small enough, at which point the proof can be done individually). This conversion algorithm is deterministic and finite, and defines an inverse of conversion from binary to Gaussian using base `-1 + i`.
> 3 votes

# Answer
# Haskell, ~~78~~ 74 bytes

```
(concat[[(x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)]|i<-[0..],x<-[0..i]]!!)

```

Test run:

```
*Main> mapM_ (print . (concat[[(x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)]|i<-[0..],x<-[0..i]]!!) ) [0..20]
(0,0)
(0,-1)
(-1,-1)
(-1,0)
(0,1)
(0,-2)
(-1,-2)
(-1,1)
(1,0)
(1,-1)
(-2,-1)
(-2,0)
(0,2)
(0,-3)
(-1,-3)
(-1,2)
(1,1)
(1,-2)
(-2,-2)
(-2,1)
(2,0)

```

How it works: list all pairs in the first quadrant in the following order

```
  |
 2| #4
  |
 1| #2  #5
  |
 0| #1  #3  #6
  +---------------
     0   1   2   3

```

mirror each point into the other quadrants to make a list of 4 element lists. Concatenate all into a single list and take the `n`th element.

Edit: function doesn't need a name, reordered math. expressions.
> 2 votes

# Answer
# 05AB1E, 35 bytes

```
>©DÝʒo®sÖ}àsÅÉʒ®sÖ}à<2÷‚εDÈi2÷ë>2÷(

```

Try it online! or as Test suite

## Explanation

Consider

$$\begin{align\*} f: \mathbb{N} &\longrightarrow \mathbb{N} \times \mathbb{N} \\ n&\longmapsto (x,y)\\, , \end{align\*} $$ where \\$x\\$ is the largest number so that \\$2^x\\$ divides \\$n+1\\$, and where \\$2y+1\\$ is the largest odd number which divides \\$n+1\\$. The inverse of \\$f\\$ is the well-known bijection \\$f^{-1}(x,y) = 2^x(2y+1)-1\\$.

Then consider $$\begin{align\*} g: \mathbb{N} \times \mathbb{N} &\longrightarrow \mathbb{Z} \times \mathbb{Z} \\ (m,n)&\longmapsto (h(m),h(n))\\, , \end{align\*} $$ where $$\begin{align\*} h: \mathbb{N} &\longrightarrow \mathbb{Z} \\ n&\longmapsto \begin{cases}\frac n2, & n \text{ even}\\ -\frac{n+1}2, & n \text{ odd}\end{cases}\\, . \end{align\*} $$ Since \\$f\\$, \\$g\\$ and \\$h\\$ all are bijections, the composition \\$g\circ f:\mathbb{N} \longrightarrow \mathbb{Z} \times \mathbb{Z}\\$ is a bijection.

The program simply computes \\$g\circ f\\$.

```
>©DÝʒo®sÖ}àsÅÉʒ®sÖ}à<2÷‚εDÈi2÷ë>2÷( # Full program

                                    # Implicit input: Integer n
>©                                  # Compute n+1 and save it to the register
  DÝ                                # Duplicate n+1 and push the list [0,...,n+1]
    ʒo®sÖ}                          # Only keep those numbers x so that 2^x divides n+1
          à                         # Get maximum element in the list.
           sÅÉ                      # Swap so that n+1 is on top and push [1,3,5,...,n+1]
              ʒ®sÖ}                 # Only keep those numbers z which divides n+1
                   à<2÷             # Compute y = (z-1)/2
                       ‚            # Push the pair [x,y]
                        ε           # Apply the function h to x (and y):
                           i        # if...
                         DÈ         # x is even
                            2÷      # then compute x/2
                              ë>2÷( # else compute -(x+1)/2
                                    # Implicit output: [h(x),h(y)]

```
> 2 votes

# Answer
# JavaScript, 166 168 bytes/characters

New approach using a rectangular spiral like others are using.

```
function f(n){return b=Math,k=b.ceil((b.sqrt(n)-1)/2),t=2*k+1,m=b.pow(t,2),t+=4,m-t>n?(m-=t,m-t>n?(m-=t,m-t>n?[k,k-(m-n-t)]:[-k+(m-n),k]):[-k,-k+(m-n)]):[k-(m-n),-k]}

```

I used this answer on Math.SE, translated it to JS and compressed it using UglifyJS.

This approach does not use any loops nor does it create the spiral in any way.

Because the spiral's coordinates cover all integers the function is bijective in the sense of \\$f:\mathbb{N}^0\rightarrow \mathbb{Z}^2\\$.

**Update:** Saved 2 characters by storing `Math` in `b`.

**Update 2:** Replaced `t-=1` with `t+=4` to fix the issue that caused \\$f(0)=f(8)\\$. This does not generate a spiral anymore but works for all non-negative integers \\$\mathbb{N}^0\\$ (all natural numbers including \\$0\\$).
> 1 votes

# Answer
# Haskell, 50 bytes

```
(0!).succ
l!n=(last$(!).succ:[(,)|odd n])l$div n 2

```

Try it online or try it with its inverse!

## Ungolfed

```
ntoN2 n = 0 ! (n + 1)

xCounter ! remainingNum
  | odd remainingNum = (xCounter, div remainingNum 2)
  | otherwise        = (xCounter + 1) ! div remainingNum 2

```

## Explanation

This uses the fact that each \\$(x,y) \in \mathbb{N}^2\\$ can be 1-to-1 mapped to \\$2^x \cdot (2\cdot y + 1) - 1 \in \mathbb{N}\\$. The above operator `(!)` computes \\$x\\$ by dividing the input as long as it's even, keeping track with the zero-initialized variable `l` (`xCounter`). Once we reached the even number an integer division computes `y`.

Note that the actual function `f` (`ntoN2`) increments the input before starting with the procedure.
> 1 votes

# Answer
# Vyxal, 5 bytes

```
Þn:Ẋi

```

Try it Online!

```
Þn    # All integers
  :Ẋ  # Cartesian product with self
    i # Index input into that

```
> 1 votes

# Answer
# JavaScript, ~~77~~ 70 bytes

```
Z=x=>(x&1n?x:-x)/2n
f=(x,y=1n)=>++x&1n?[Z(++x/2n),Z(y)]:f(x/2n-1n,++y)

```

Takes a BigInt as Input.

Attempt This Online!

First few values:

```
f(0n)=[0n,0n]
f(1n)=[0n,-1n]
f(2n)=[-1n,0n]
f(3n)=[0n,1n]
f(4n)=[1n,0n]
f(5n)=[-1n,-1n]
...

```

Explanation:

Uses more or less the same algorithm as Wislaw's solution:

`Z` is the standard bijection from the positive integers to the integers.

`f` computes positive integers `k` and `m` with `x+1=2^(k-1)*(2m-1)` (which is a bijection \\$\mathbb{N} \to \mathbb{N}\_{\>0} \times \mathbb{N}\_{\>0}\\$ by the uniqueness of prime factorizations) and then outputs the pair `Z(m),Z(k)`

---

# JavaScript, 65 bytes

bijection \\$\mathbb{N}\_{\>0} \to \mathbb{Z} \times \mathbb{Z}\\$

```
Z=x=>(x&1n?x:-x)/2n
f=(x,y=1n)=>x&1n?[Z(++x/2n),Z(y)]:f(x/2n,++y)

```

Attempt This Online!
> 1 votes

# Answer
# Scala, 79 bytes

Port of @ბიმო's Haskell answer in Scala.

---

Golfed version. Try it online!

```
n=>for{i<-0 to n;x<-0 to i}yield Seq((x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x))

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val result = for {
      i <- 0 to 20
      x <- 0 to i
    } yield List((x, i - x), (x, x - 1 - i), (-1 - x, x - 1 - i), (-1 - x, i - x))

    result.flatten.zipWithIndex.take(21).foreach {
      case (tuple, index) => println(s"$index: $tuple")
    }
  }
}

```
> 1 votes

# Answer
# JavaScript (Node.js), 48 bytes

```
f=(x,y)=>x&1?f(x/2,-~y):[x/2,y].map(t=>t/2^-t%2)

```

Attempt This Online!
> 1 votes

# Answer
# Mathematica, 46

```
SortBy[Tuples[Range[2#]-#,2],Norm][[#]]&[#+1]&

```

Sort the vectors their norm, then take the `n`th one.
> 0 votes

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


title: Which Day of Christmas is it?

text:
# Question
Title: Which Day of Christmas is it?
# Preface

In the well known carol, The Twelve Days of Christmas, the narrator is presented with several gifts each day. The song is *cumulative* \- in each verse, a new gift is added, with a quantity one higher than the gift before it. One Partridge, Two Turtle Doves, Three French Hens, and so on.

At any given verse, **N**, we can calculate the cumulative sum of presents so far in the song by finding the **N**th tetrahedral number, which gives the results:

```
Verse 1: 1
Verse 2: 4
Verse 3: 10
Verse 4: 20
Verse 5: 35
Verse 6: 56
Verse 7: 84
Verse 8: 120
Verse 9: 165
Verse 10: 220
Verse 11: 286
Verse 12: 364

```

For example, after verse 4, we've had **4\*(1 partridge)**, **3\*(2 turtle doves)**, **2\*(3 French hens)** and **1\*(4 calling birds)**. By summing these, we get `4(1) + 3(2) + 2(3) + 1(4) = 20`.

# The Challenge

Your task is to write a program or function which, given a positive integer representing the number of presents **364 ≥ p ≥ 1**, determines which day (verse) of Christmas it is.

For example, if **p = 286**, we are on the 11th day of Christmas. However, if **p = 287**, then the next load of presents has begun, meaning it is the 12th day.

Mathematically, this is finding the next tetrahedral number, and returning its position in the whole sequence of tetrahedral numbers.

**Rules:**

* This is , so the shortest solution (in bytes) wins.
* Standard golfing loopholes apply.
* When it comes to days, your program must be 1-indexed.
* Your submission must be a full program or a function - but not a snippet.

# Test Cases

```
1   ->  1
5   ->  3
75  ->  7
100 ->  8
220 ->  10
221 ->  11
364 ->  12

```

# Answer
# Jelly, ~~7~~ 6 bytes

-1 byte thanks to Dennis (use vectorised minimum, `«`, and first index, `i`)

```
R+\⁺«i

```

**TryItOnline**

### How?

Not all that efficient - calculates the 1st through to nth tetrahedral numbers in order in a list and returns the 1-based index of the first that is equal to or greater.

```
R+\⁺«i - main link: n
R      - range                          [1,2,3,4,...,n]
 +\    - cumulative reduce by addition  [1,3,6,10,...,sum([1,2,3,4,...n])] i.e. triangle numbers
   ⁺   - duplicate previous link - another cumulative reduce by addition
                                        [1,4,10,20,...,nth tetrahedral]
    «  - min(that, n)                   [1,4,10,20,...,n,n,n]
     i - first index of n (e.g. if n=12:[1,4,10,12,12,12,12,12,12,12,12,12] -> 4)

```

---

Previous 7 byters using lowered range `[0,1,2,3,...,n-1]` and counting tetrahedrals less than n:
`Ḷ+\⁺<µS`,
`Ḷ+\⁺<ḅ1`,
`Ḷ+\⁺<ċ1`, and
`Ḷ+\⁺<¹S`
> 7 votes

# Answer
# Python, 27 bytes

```
lambda n:int((n*6)**.33359)

```

Try it online!

A direct formula with some curve-fitting, same as the original one found by Level River St.

The shifted equation `i**3-i==n*6` is close to `i**3==n*6` for large `i`. It solves to `i=(n*6)**(1/3)`. Taking the floor the rounds down as needed, compensating for the off-by-one.

But, there are 6 inputs on boundaries where the error takes it below an integer it should be above. All of these can be fixed by slightly increasing the exponent without introducing further errors.

---

## Python, 38 bytes

```
f=lambda n,i=1:i**3-i<n*6and-~f(n,i+1)

```

The formula `n=i*(i+1)*(i+2)/6` for tetrahedral numbers can be more nicely written in `i+1` as `n*6=(i+1)**3-(i+1)`. So, we find the lowest `i` for which `i**3-i<n*6`. Each time we increment `i` starting from 1, the recursive calls adds `1` to the output. Starting from `i=1` rather than `i=0` compensates for the shift.
> 19 votes

# Answer
# , 12 bytes

```
2>.@-~3!inv]

```

There might be a golfier way to do this, but this is a lovely opportunity to use J's built-in function inversion.

Try it online!

### How it works

```
2>.@-~3!inv]  Monadic verb. Argument: n

           ]  Right argument; yield n.
      3       Yield 3.
       !inv   Apply the inverse of the ! verb to n and 3. This yields a real number.
              x!y computes Π(y)/(Π(y-x)Π(x)), where Π is the extnsion of the
              factorial function to the real numbers. When x and y are non-negative
              integers, this equals yCx, the x-combinations of a set of order y.
 >.@-~        Combine the ceil verb (>.) atop (@) the subtraction verb (-) with
              swapped arguments (~).
2             Call it the combined verbs on the previous result and 2.

```
> 10 votes

# Answer
# Python, 22 bytes

```
lambda n:n**.3335//.55

```

Heavily inspired by @xnor's Python answer.

Try it online!
> 9 votes

# Answer
# Jelly, 7 bytes

```
R‘c3<¹S

```

Try it online!

### How it works

```
R‘c3<¹S  Main link. Argument: n

R        Range; yield [1, ..., n].
 ‘       Increment; yield [2, ..., n+1].
  c3     Combinations; yield [C(2,3), ..., C(n+1,3)].
    <¹   Yield [C(2,3) < n, ..., C(n+1,3) < n].
      S  Sum; count the non-negative values of k for which C(k+2,3) < n.

```
> 7 votes

# Answer
## JavaScript (ES6), 33 bytes

```
n=>(F=k=>k<n?F(k+3*k/i++):i)(i=1)

```

Based on the recursive formula:

```
a(1) = 1
a(i) = (i + 3) * a(i - 1) / i

```

The second expression can also be written as ...

```
a(i) = a(i - 1) + 3 * a(i - 1) / i

```

... which is the one that we are using here.

`a(i - 1)` is actually stored in the `k` variable and passed to the next iteration until `k >= n`.

### Test cases

```
let f =

n=>(F=k=>k<n?F(k+3*k/i++):i)(i=1)

console.log(f(1));   // ->  1
console.log(f(5));   // ->  3
console.log(f(75));  // ->  7
console.log(f(100)); // ->  8
console.log(f(220)); // ->  10
console.log(f(221)); // ->  11
console.log(f(364)); // ->  12
```
> 6 votes

# Answer
# Ruby, 26 bytes

Edit: alternate version, still 26 bytes

```
->n{(n**0.3333*1.82).to_i}

```

Original version

```
->n{((n*6)**0.33355).to_i}

```

Uses the fact that `T(x) = x(x+1)(x+2)/6 = ((x+1)**3-(x+1))/6` which is very close to `(x+1)**3/6`.

The function simply multiplies by 6, finds a slightly tweaked version of the cube root (yes 5 decimal places are required) and returns the result truncated to an integer.

**Test program and output**

```
f=->n{((n*6)**0.33355).to_i}
[1,4,10,20,35,56,84,120,165,220,286,364].map{|i|p [i,f[i],f[i+1]]}

[1, 1, 2]
[4, 2, 3]
[10, 3, 4]
[20, 4, 5]
[35, 5, 6]
[56, 6, 7]
[84, 7, 8]
[120, 8, 9]
[165, 9, 10]
[220, 10, 11]
[286, 11, 12]
[364, 12, 13]

```
> 6 votes

# Answer
# JavaScript, ~~36~~ 33 bytes

*-3 bytes thanks to Luke (making the function curried)*

```
n=>f=i=>n<=i/6*-~i*(i+2)?i:f(-~i)

```

This is an unnamed lambda function which can be assigned to `func` and called with `func(220)()`, as described in this meta post. My original, non-curried function looks like this:

```
f=(n,i)=>n<=-~i*i/6*(i+2)?i:f(n,-~i)

```

This answer uses the fact that **x**th tetrahedral number can be found with the following function:

\\$f(x) = \frac{x}6(x+1)(x+2)\\$

The function works by recursively increasing `i`, and finding `tetrahedral(i)`, until it's larger than or equal to `n` (the number of presents given).

When called with one argument as expected, `i = undefined`, and therefore is not larger than `n`. This means `f(n,-~i)` is executed, and `-~undefined` evaluates to `1`, which sets off the recursion.

---

## Test Snippet:

```
func = n=>f=i=>n<=i/6*-~i*(i+2)?i:f(-~i)

var tests = [1, 5, 75, 100, 220, 221, 364];
tests.forEach(n => console.log(n + ' => ' + func(n)()));
```
> 5 votes

# Answer
# MATL, ~~12~~ 11 bytes

```
`G@H+IXn>}@

```

Try it online!

### Explanation

```
`       % Do...while
  G     %   Push input, n
  @     %   Push iteration index (1-based), say m
  H     %   Push 2
  +     %   Add
  I     %   Push 3
  Xn    %   Binomial coefficient with inputs m+2, 3
  >     %   Is n greater than the binomial coefficient? If so: next iteration
}       %   Finally (execute after last iteration, before exiting the loop)
  @     %   Push last iteration index. This is the desired result
        % End (implicit)
        % Display (implicit)

```
> 3 votes

# Answer
# 05AB1E, 10 bytes

```
XµNÌ3c¹‹_½

```

Try it online!

**Explanation**

```
Xµ          # loop until counter equals 1
  NÌ3c      # binomial_coefficient(iteration_index+2,3)
      ¹     # push input
       ‹_   # not less than
         ½  # if true, increment counter
            # output last iteration index

```
> 2 votes

# Answer
## Pyke, 11 bytes

```
#3RL+B6f)lt

```

Try it here!

```
#3RL+B6f)   -  while rtn <= input as i:
 3RL+       -     i+j for j in range(3)
     B      -    product(^)
      6f    -   ^/6
         lt - len(^)-1

```
> 2 votes

# Answer
# Japt, 12 bytes

```
1n@*6§X³-X}a

```

Test it online! or Verify all test cases at once

### How it works

```
1n@*6§X³-X}a  // Implicit: U = input integer
  @       }a  // Find the smallest non-negative integer X which satisfies this condition:
      X³-X    //   (X ^ 3) - X
     §        //   is greater than or equal to
   *6         //   U * 6.
1n            // Subtract 1 from the result.
              // Implicit: output result of last expression

```

This is a simplification of the tetrahedral formula several other answers are using:

```
f(x) = (x)(x + 1)(x + 2)/6

```

By substituting `x - 1` for `x`, we can simplify this considerably:

```
f(x) = (x - 1)(x)(x + 1) / 6
f(x) = (x - 1)(x + 1)(x) / 6
f(x) = (x^2 - 1)(x) / 6
f(x) = (x^3 - x) / 6

```

Therefore, the correct result is one less than the smallest integer `x` such that `(x^3 - x) / 6` is greater than or equal to the input.

13-byte solution, inspired by @xnor's answer:

```
p.3335 /.55 f

```

A few more solutions @ETHproductions and I played around with

```
J+@*6§X³-X}a
@*6§X³-X}a -1
@§X/6*°X*°X}a
_³-V /6¨U}a -1
§(°V nV³ /6?´V:ß
§(°VV³-V /6?´V:ß

```

Test it here.
> 2 votes

# Answer
# Mathematica, 26 bytes

```
(0//.i_/;i+6#>i^3:>i+1)-1&

```

Unnamed function taking a nonnegative integer argument and returning a nonnegative integer (yeah, it works for day `0` too). We want to find the smallest integer `i` for which the input `#` is at most `i(i+1)(i+2)/6`, which is the formula for the number of gifts given on the first `i` days. Through mild algebraic trickery, the inequality `# ≤ i(i+1)(i+2)/6` is equivalent to `(i+1) + 6# ≤ (i+1)^3`. So the structure `0//.i_/;i+6#>i^3:>i+1` starts with a `0` and keeps adding `1` as long as the test `i+6#>i^3` is satisfied; then `(...)-1&` subtracts `1` at the end (rather than spend bytes with parentheses inside the inequality).

If we let the 12 Days of Christmas continue, we can handle about 65536 days before the built-in recursion limit for `//.` halts the process ... that's about 4.7 * 10^13 days, or about ten times the age of the universe thus far....
> 2 votes

# Answer
# , 9 bytes

```
I.~3!2+i.

```

Try it online!

This is more inefficient than using the inverse of factorial but happens to be shorter.

For example, if the input integer is *n* = 5, make the range `[2, n+1]`.

```
2 3 4 5 6 choose 3
0 1 4 10 20

```

These are the first 5 tetrahedral numbers. The next step is to determine which interval (day) *n* belongs to. There are *n*+1 = 6 intervals.

```
0 (-∞, 0]
1 (0, 1]
2 (1, 4]
3 (4, 10]
4 (10, 20]
5 (20, ∞)

```

Then *n* = 5 belongs to interval 3 which is `(4, 10]` and the result is 3.

## Explanation

```
I.~3!2+i.  Input: integer n
       i.  Range [0, n)
     2+    Add 2 to each
   3!      Combinations nCr with r = 3
I.~        Interval index of n

```
> 2 votes

# Answer
# Python, 43 bytes

```
f=lambda n,i=0:n*6>-~i*i*(i+2)and-~f(n,i+1)

```

Saved 5 bytes thanks to @FlipTack and another 3 thanks to @xnor!
> 2 votes

# Answer
# APL (Dyalog Classic), 8 bytes

```
+\⍣2∘⍳⍳⊢

```

My first time using APL, thanks to H.PWiz for shortening it into a train

Essentially a port of the Jelly answer

# Explanation

```
+\⍣2∘⍳⍳⊢
    ∘⍳    Numbers from 1 to input inclusive
+\        Cumulative reduce with addition, gets triangular numbers
  ⍣2      Repeat (does it again) to get the tetrahedral numbers
      ⍳⊢  Index of the input in that list

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~48~~ 46 bytes

```
f=lambda x,i=1:f(x,i+1)if(i+3)*i+2<x/i*6else i

```
> 1 votes

# Answer
# SmileBASIC, 43 bytes

```
INPUT X
WHILE X>P
I=I+1
R=R+I
P=P+R
WEND?I

```

`I` is the day, `R` is the `i`th triangular number, and `P` is the `i`th tetrahedral number (number of presents).

I think a similar answer in another language, perhaps: `x=>{while(x>p)p+=r+=++i;return i}` could be pretty good.
> 1 votes

# Answer
# Mathematica, ~~31~~ 25 bytes

```
Floor@Root[x^3-x-6#+6,1]&

```
> 1 votes

# Answer
# Haskell, ~~21~~ 23 bytes

```
floor.(**(1/3)).(*6.03)

```

Edit: As xnor pointed out, the original solution (`floor.(/0.82).(**0.4)`) didn't work between the days of christmas
> 1 votes

# Answer
# Itr, 11 bytes

`#äµS¹µS>S1+`

online interpreter

# Explanation

```
#            ; read a number `n`  from standard input
 ä           ; duplicate that number
  µ          ; apply for all integers in the range [1,...,n]
   S         ; replace each element `k` of the range with the sum from 1 to `k`
    ¹        ; push all no-empty prefixes of that list
     µS      ; sum up the elements, this will give the list of the first `n` tetrahedral numbers
       >     ; vectorized comparison
        S    ; sum up, this will count the number of triangle numbers that are smaller than `n`
         1+  ; offset by one to get the right number

```
> 1 votes

# Answer
## Batch, 69 bytes

```
@set/an=d=t=0
:l
@set/at+=d+=n+=1
@if %t% lss %1 goto l
@echo %n%

```

Manually calculates tetrahedronal numbers.
> 0 votes

# Answer
**Pyth 11 bytes**

```
/^Q.3335.55

```

Try it online!

pretty much just translated Dennis' answer into Pyth
> 0 votes

# Answer
**R, 19 characters**

```
floor((n*6)^.33359)

```

based on xnor's answer in `Python`.
> 0 votes

# Answer
## QBIC, 19 bytes

This steals @xnor 's formula:

```
:?int((a*6)^.33359)

```

I tried dialing down the resolution to .3336 to save a byte, but that fails on the final testcase.
> 0 votes

# Answer
# Bash + bc, 44 bytes

```
bc -l <<< "f=e(.33359*l($1*6));scale=0;f/1"

```
> 0 votes

# Answer
# Husk, 6 bytes

```
V≥¹∫∫ḣ

```

Try it online! or Verify all test cases

## Explanation

```
V≥¹∫∫ḣ
     ḣ range 1..n
   ∫∫  cumulative sum, twice
V      index of first element that is
 ≥¹    greater than or equal to the input

```
> 0 votes

---
Tags: code-golf, math, arithmetic, number-theory
---


# Question
Title: Repeating occupied pattern in Hilbert's hotel
Imagine a countable infinite amount of empty rooms. When an infinite amount of guests come, they occupy the 1st, 3rd, 5th...(all odd) empty rooms. Therefore there's always an infinite amount of empty rooms, and occupied guests needn't move when new guests come.

```
- - - - - - - - - - - - - - - - -
1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1
1 2 1 - 1 2 1 - 1 2 1 - 1 2 1 - 1

```

Same group of guests would leave together, so if group 1 leave, it results in

```
- 2 - - - 2 - - - 2 - - - 2 - - -

```

Notice that some rooms turn empty, so if another group of infinite guests come, it results in

```
3 2 - 3 - 2 3 - 3 2 - 3 - 2 3 - 3

```

Now room 1,2,4,6,7,... are occupied while 3,5,8,... are empty.

# Input

Given a list of moves(aka. some group join or some group leave). All join requests are labeled 1,2,3,... in order.

You can also choose to not read the joining label or not read join/leave value.

# Output

The shortest repeating pattern of occupied/empty.

# Test cases

```
[]            => [0]
[+1]          => [1,0]
[+1,+2]       => [1,1,1,0]
[+1,+2,-1]    => [0,1,0,0]
[+1,+2,-1,+3] => [1,1,0,1,0,1,1,0]
[+1,-1]       => [0]

```

Shortest code wins

# Answer
# JavaScript (ES6), 100 bytes

Returns a comma-separated binary string.

```
a=>/(.*?)(,\1)*$/.exec(a.reduce((b,x)=>[...b,...b].map(q=v=>x<0|v?v+x&&v:q^=x),[0]).map(x=>+!!x))[1]

```

Try it online!

99 bytes if we use `NaN` for unoccupied

### Commented

```
a =>                 // a[] = input array
/(.*?)(,\1)*$/       // a regular expression that looks for the shortest
                     // prefix which, when repeated a whole number of
                     // times with a leading comma, allows to reach the
                     // end of the string
.exec(               // apply this to:
  a.reduce((b, x) => //   for each element x in a[],
                     //   using the array b[] as the accumulator:
    [...b, ...b]     //     append b[] to itself
    .map(q =         //     initialize q to a NaN'ish value
      v =>           //     for each element v in the resulting array:
      x < 0 | v ?    //       if x is negative or v is not 0:
        v + x && v   //         append 0 if v = -x, or v otherwise
      :              //       else:
        q ^= x       //         toggle q between 0 and x and append that
    ),               //     end of map()
    [0]              //     initialize the accumulator to [0]
  )                  //   end of reduce()
  .map(x => +!!x)    //   update each value to either 0 or 1
                     //   implicit coercion to a string
)[1]                 // end of exec(); return the prefix

```
> 5 votes

# Answer
# Jelly,  ~~28~~  24 bytes

```
N;`⁹¬Tm2Ʋ¦A¬ẹ¦ʋƒ0ṠŒṖEƇḢḢ

```

A full program\* that accepts the register list and prints a Jelly representation of the pattern list.

<sup>* Only a full program to handle specifically `[] => [0]` for which the monadic Link would yield the integer `0`</sup>

**Try it online!**

Replacing `ŒṖ` with `sJ$` will be faster if you want to try slightly longer inputs.

### How?

The idea is to process the *moves* in turn maintaining a prefix that starts at `[0]` and doubles in length at each *move* either occupying every other empty room with a copy of *move* or removing all occurrences of the negative of *move*. Once this is done we can then find the shortest prefix that repeats to give the same.

Actually, the implementation is a little more convoluted - rather than the "either or" above, we process negated values of the *moves*, always add these to every other unoccupied room, take absolute values and then always remove all occurrences of the negated *move* from all rooms. This saves some precious bytes.

```
N;`⁹¬Tm2Ʋ¦A¬ẹ¦ʋƒ0ṠŒṖEƇḢḢ - Main Link: list of moves, Moves
N                        - negate {Moves} (vectorises)
               ƒ0        - start with 0 and reduce {that} by:
              ʋ          -   last four links as a dyad - f(Rooms, -Move)
 ;`                      -     {Rooms} concatenate {Rooms} -> R2
         ¦               -     sparse application...
        Ʋ                -     ...to indices: last four links as a monad - f(R2):
    ¬                    -       logical NOT {R2}
     T                   -       truthy indices of {that} -> I
       2                 -       two
      m                  -       {I} modulo-slice {2
                                   -> indices of every other empty room
   ⁹                     -     ...apply: set to chain's right argument = -Move
          A              -     absolute value {that} (vectorises)
             ¦           -     sparse application...
            ẹ            -     ...to indices: indices of {-Move}
           ¬             -     ...apply: logical NOT
                 Ṡ       - signs {that} -> occupied or not indicators
                  ŒṖ     - partitions of {that}
                     Ƈ   - keep those {patitions} for which:
                    E    -   all equal? -> repetitive partitions
                      Ḣ  - head {that} -> shortest repetitive partition
                       Ḣ - head {that} -> shortest possible prefix

```
> 5 votes

# Answer
# Python 3, 223 202 bytes

Oh boy. Cool challenge, cant wait to see what everyone can do!

slowly chipping away I guess...

```
def f(g,h=[0]):
 for q in g:
  if[q]<h:h=[w*(w-q)for w in h];continue
  h=h+h;p=1
  for i,w in enumerate(h):
   if w<1:h[i]=p*q;p=1-p
 while h==h[:len(h)//2]*2:h=h[:len(h)//2]
 return[1-(i<1)for i in h]

```

Try it online!

# Python 3.8 (pre-release), 215 195 bytes

stealing Ajax1234's walrus operator while loop o7

```
def f(g,h=[0]):
 for q in g:
  if[q]<h:h=[w*(w-q)for w in h];continue
  h=h+h;p=1
  for i,w in enumerate(h):
   if w<1:h[i]=p*q;p=1-p
 while h==(k:=h[:len(h)//2])*2:h=k
 return[1-(i<1)for i in h]

```

Try it online!
> 2 votes

# Answer
# Charcoal, 59 bytes

```
⊞υ⁰Ｆθ¿‹ι⁰ＵＭυ∧⁺ικκ«≔⁺υυυＦΦ⌕Ａυ⁰﹪λ²§≔υκι»≔⭆υ¬¬ιηＷ⁼η×²÷η²≔÷η²ηη

```

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

```
⊞υ⁰

```

Start with one empty room.

```
Ｆθ

```

Loop over the input values.

```
¿‹ι⁰

```

If it is negative, then...

```
ＵＭυ∧⁺ικκ«

```

Discard those values whose sum is zero, otherwise:

```
≔⁺υυυ

```

Duplicate the list.

```
ＦΦ⌕Ａυ⁰﹪λ²

```

Loop over alternate indices of the empty rooms. (Filtering is golfier than slicing alternate indices.)

```
§≔υκι

```

Fill the room at this index.

```
»≔⭆υ¬¬ιη

```

Convert the rooms to a binary string of occupancy.

```
Ｗ⁼η×²÷η²

```

While the string equals half of itself repeated twice, ...

```
≔÷η²η

```

... halve the length of the string.

```
η

```

Output the final string.
> 1 votes

# Answer
# Python3, 227 bytes

```
def f(m):
 h=[0]*(2**sum(i>0for i in m))
 for i in m:
  if i<0:h=[[0,l][l!=-i]for l in h]
  else:
   k=1
   for j,a in enumerate(h):h[j]=[a,i][k%2 and 0==a];k+=a==0
 while h==(k:=h[:len(h)//2])*2:h=k
 return[int(i>0)for i in h]

```

Try it online!
> 1 votes

---
Tags: code-golf, sequence
---


title: Find the percentage

text:
# Question
Title: Find the percentage
We haven't had any nice, easy challenges in a while, so here we go.

Given a list of integers each greater than \\$0\\$ and an index as input, output the percentage of the item at the given index of the total sum of the list.

Output should be whatever the natural representation for floats/integers is in your language (unary, decimal, Church numerals etc.). If you choose to round the output in any way, it must have at minimum 2 decimal places (when reasonable. \\$1.2\\$ doesn't *need* to be rounded, but \\$1.20\\$ is also perfectly acceptable).

Indexes can be either 1-indexed or 0-indexed, and will always be within the bounds of the array.

This is , so the shortest code in bytes wins!

## Examples

Using 1-indexed and rounded to 2 d.p

```
list, index                    =>         output
[1, 2, 3, 4, 5], 5             => 5 / 15    => 33.33
[7, 3, 19], 1                  => 7 / 29    => 24.14
[1, 1, 1, 1, 1, 1, 1, 1, 1], 6 => 1 / 9     => 11.11
[20, 176, 194, 2017, 3], 1     => 20 / 2410 => 0.83
[712], 1                       => 712 / 712 => 100

```

Or, as three lists:

```
[[1, 2, 3, 4, 5], [7, 3, 19], [1, 1, 1, 1, 1, 1, 1, 1, 1], [20, 176, 194, 2017, 3], [712]]
[5, 1, 6, 1, 1]
[33.33, 24.14, 11.11, 0.83, 100]

```

# Answer
> 7 votes
# Python 3, 26 bytes

```
lambda i,a:a[i]/sum(a)*100

```

An unnamed function accepting an integer (0-indexed index) and a list which returns the percentage.

**Try it online!**

# Answer
> 6 votes
# APL (Dyalog Unicode), 9 bytesSBCS

Anonymous tacit infix function. Takes index as left argument and list as right argument.

```
100×⌷÷1⊥⊢

```

Try it online!

`100` one hundred

`×` times

the indexed element

`÷` divided by

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

the right argument

# Answer
> 6 votes
# C# (Visual C# Interactive Compiler), 22 bytes

```
x=>y=>x[y]*100/x.Sum()

```

Try it online!

# Answer
> 5 votes
# Jelly, 7 bytes

```
ị÷S}ȷ2×

```

A dyadic Link accepting an integer, one-based index on the left and a list of numbers on the right which yields the percentage.

**Try it online!**

### How?

```
ị÷S}ȷ2× - Link: integer, i; list, L
ị       - (i) index into (L)
   }    - use right argument:
  S     -   sum (L)
 ÷      - divide
    ȷ2  - literal 10^2 = 100
      × - multiply

```

# Answer
> 5 votes
# 05AB1E, 6 bytes

```
è²O/т*

```

A full program taking the index then the list. Uses 0-indexing.

**Try it online!**

### How?

```
è²O/т*
è      - index (input 1) into (input 2)
 ²     - push 2nd input
  O    - sum
   /   - divide
    т  - push 100
     * - multiply
       - print top of stack

```

# Answer
> 5 votes
# Java (JDK), 47 bytes

```
a->i->1e2*a[i]/java.util.Arrays.stream(a).sum()

```

Try it online!

# Answer
> 4 votes
# , 10 bytes

```
100*{%1#.]

```

Try it online!

0-indexed

# Answer
> 4 votes
# 28 bytes

```
function(n,l)100*l[n]/sum(l)

```

Try it online!

# Answer
> 4 votes
# C (gcc), 64 bytes

0-indexed. The only fun bit was the realization that `1e2` is a `double`, saving a byte over `100.`!

```
float f(v,n,t)int*v;{n=v[n];for(t=0;*v;t+=*v++);return n*1e2/t;}

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 30 bytes

Takes input as `(array)(index)`, where *index* is 0-based.

```
a=>n=>a[n]*100/eval(a.join`+`)

```

Try it online!

# Answer
> 3 votes
# Haskell,  ~~20~~  18 bytes

```
i?a=a!!i/sum a*100

```

A dyadic operator (`?`) taking the (0-indexed) index on the left and a list on the right which yields the percentage.

**Try it online!**

# Answer
> 3 votes
# PHP (7.4), 35 bytes

```
fn($l,$i)=>100/array_sum($l)*$l[$i]

```

Try it online!

Input index is 0-based.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 15 bytes

```
100##[[]]/Tr@#&

```

Try it online!

Input as `list, index`

# Answer
> 3 votes
# MATL, 9 bytes

```
)1Gs/100*

```

Try it online!

### Explanation

```
          implicitly take two inputs
)         get the entry within the first input at the index specified by the second
 1G       push the first input onto the stack again
   s      compute the sum
    /     divide first entry of the stack by this number (the sum)
     100* multiply by 100

```

Try it online!

# Answer
> 3 votes
# K (oK), ~~15~~ 14 bytes

-1 byte thanks to ngn!

```
{100*x[y]%+/x}

```

Try it online!

0-indexed

# Answer
> 2 votes
# TI-Basic, 12 bytes (12 tokens)

```
Prompt X
Ans(X)<sub>E</sub>2/sum(Ans

```

1-indexed

Takes the list in `Ans` and prompts the user for the index

Example run

Explanation:

```
Prompt X         # Prompt the user for the index
Ans(X)<sub>E</sub>2/sum(Ans
Ans(X)           # The value at the Xth index in the list
      <sub>E</sub>2         # times 100
        /sum(Ans # Divided by the sum of the list
                 # The result of the last expression in a program is implicitly returned

```

# Answer
> 2 votes
# Red, ~~31~~ 29 bytes

-2 bytes thanks to ErikF

```
func[b i][1e2 * b/:i / sum b]

```

Try it online!

# Answer
> 2 votes
# Zsh, ~~32~~ 30 bytes

***-1** thanks to @ErikF, using `1e2` instead of `100.`.*

```
<<<$[1e2*$@[`<&0`]/(${@/#/+})]

```

~~Try it online!~~ Try it online!

Accepts the list as arguments and the index on stdin.

```
<<<$[1e2*$@[`<&0`]/(${@/#/+})]  # $[ arithmetic ]
   $[       `<&0`            ]  # capture stdin
   $[    $@[     ]           ]  # index into the arguments
   $[1e2*$@[`<&0`]           ]  # multiply by 100.0 (casts to float)
   $[              (${@/#/+})]  # prepend each element with + and add
   $[             /          ]  # divide
<<<                              # print to stdout

```

Alternate **30 byte** solution

# Answer
> 2 votes
# MathGolf, ~~7~~ 6 bytes

```
§\Σ/♀*

```

0-based indexing.

Try it online.

**Explanation:**

```
§       # Index the (implicit) second input-integer into the first (implicit) input-list
 \      # Swap so the first (implicit) input-list is at the top of the stack
  Σ     # Take the sum of that input-list
   /    # Divide the earlier indexed number by this sum
    ♀*  # Multiply it by 100
        # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 2 votes
# Factor, 46 bytes

```
: f ( i l -- n ) dup [ nth ] dip sum / 1e2 * ;

```

Try it online!

0-indexed

# Answer
> 2 votes
# PowerShell, 34 bytes

```
param($l,$n)$l|%{$i+=$_};$l[$n]/$i

```

Try it online!

Shame parameters are so dang expensive in Powershell.

# Answer
> 2 votes
# Go, 79 bytes

```
func f(a[]float64,i int)float64{s:=0.
for _,v:=range a{s+=v}
return a[i]/s*100}

```

This has a nice amount of accuracy. It takes a Go slice and uses `range` to calculate the sum.

Try it online!

# Answer
> 2 votes
# Scratch 3.0 ~~24~~ 23 blocks/~~239~~ 228 bytes

*Alternatively in SB syntax*

```
when gf clicked
set[s v]to(0
ask()and wait
repeat until<(answer)=(
add(answer)to[m v
ask()and wait
end
set[n v]to(item(length of(n))of(m
repeat(length of((m)-(1
change[s v]by(item(1)of[m v
delete (1)of[m v
end
say(((n)/(s))*(100

```

*Saved 11 bytes thanks to @JoKing*

Try it on scratch

## Answer History

*Alternatively in SB syntax*

```
when gf clicked
set[s v]to(0
ask()and wait
repeat until<(answer)=(
add(answer)to[m v
ask()and wait
end
set[n v]to(item(length of(n))of(m
delete(n)of[m v
repeat(length of(m
change[s v]by(item(1)of[m v
delete (1)of[m v
end
say(((n)/(s))*(100

```

Try it on scratch

Input is in the form of:

```
item1
item2
...
itemN
index

```

I really should stop doing this to myself. But it *is* very fun!

# Answer
> 2 votes
# Pyth, 13 bytes

```
c*100@hQeQshQ

```

Try it online!

First time using Pyth so theres probably some pretty big optimizations here, but I dont know where they are...

0-index, takes input as `list, index`

# Answer
> 2 votes
# Snap!, 79 bytes (scratchblocks syntax)

```
((L)(i))::hat
report((combine(L)using((()+()@addInput)@addInput::grey ring))/(i

```

This is a "custom block" (function), and it takes a "list" (array) as the first argument and the idnex as the second argument.

Wow, having to manually mark hats/grey rings/grey ring inputs really makes short Snap! code in scratchblocks look relatively ugly.

# Answer
> 2 votes
# CJam, ~~14~~ 12 bytes

*-2 bytes thanks to @luis-mendo*

```
_@=\:+d/1e2*

```

Try it online!

0-indexed. Takes input as `index [list]`

# Explanation

```
code         | explanation
-------------|------------
_@=\:+d/1e2* | whole program
 @=          | get the item at the index
_  \:+       | sum the array
      d      | convert to a *d*ouble
       /     | divide
        1e2* | multiply by 100

```

# Answer
> 2 votes
# Erlang 41 bytes

```
f(X,N)->lists:nth(N,X)/lists:sum(X)*100.

```

# Answer
> 1 votes
# Perl 5 `-ap -MList::Util=Sum`, 19 bytes

```
$_=100*$F[<>]/sum@F

```

Try it online!

Take the list, space separated on the first line, the index (0-based) on the second.

# Answer
> 1 votes
# Japt, 8 bytes

```
gV
*L/Vx

```

Try it

# Answer
> 1 votes
# Retina 0.8.2, 102 bytes

```
\d+
$*
^(1)+((?<-1>.(1+))+)
$3$2
,

\G1
10000$*
;(1+)\1
$1;$1$1
r`.*(\2)*;(1+)
$#1
+`^..?$
0$&
..$
.$&

```

Try it online! Link includes test cases. Takes input as `index;list,...`. Explanation:

```
\d+
$*

```

Convert to unary.

```
^(1)+((?<-1>.(1+))+)
$3$2

```

Index into the list.

```
,

```

Sum the list.

```
\G1
10000$*
;(1+)\1
$1;$1$1
r`.*(\2)*;(1+)
$#1

```

Multiply the desired value by 10000 and divide by the sum with rounding by adding on half of the sum first.

```
+`^..?$
0$&

```

Ensure that the result has at least three digits.

```
..$
.$&

```

Insert a decimal point at the second last position.

# Answer
> 1 votes
# Bash, ~~77~~ ~~75~~ ~~73~~ ~~72~~ ~~80~~ ~~76~~ 75 bytes

```
a=($@)
((b=10000*${a[$1]}/(${@/%/+}-$1),b<10))
echo $[b/100].${?/1}$[b%100]

```

Try it online!

*+8 bytes thanks to GammaFunction, who found a bug with large numbers*

*-5 bytes thanks to GammaFunction, who golfed his original bug fix*

# Answer
> 1 votes
# Ruby, ~~25~~ ~~23~~ 21 bytes

```
->a,i{1e2*a[i]/a.sum}

```

Try it online!

# Answer
> 1 votes
# AWK, ~~43~~ 40 bytes

```
{s+=a[NR]=$1}END{print 100*a[$1]/(s-$1)}

```

Try it online!

*-3 bytes thanks to CowsQuack*

Takes the index as the last line of input

# Answer
> 1 votes
# Racket, 81 43 bytes

Accepts a list and index. Outputs rationals (default for division in Racket). Big thanks to Galen Ivanov for finding the `apply` function. Still learning as I go :) .

```
(λ(l i)(*(/(list-ref l i)(apply + l))100))

```

Try it online!

# Answer
> 1 votes
# Perl 6, 21 bytes

```
{100*@^a[$^b]/@a.sum}

```

Try it online!

The simple solution, since I can't use curried parameters with the `$b` parameter being indexed. A funner solution that doesn't have to handle two parameters by using the `rotate` function instead:

```
{100*.[0]/.sum}o&rotate

```

Try it online!

But it is unfortunately two bytes longer

# Answer
> 1 votes
# Octave, 21 bytes

```
@(a,n)a(n)/sum(a)*100

```

Try it online!

# Answer
> 1 votes
# Icon, 53 bytes

```
procedure f(L,i)
s:=0;s+:=!L&\z
return 1e2*L[i]/s
end

```

Try it online!

The only interesting thing here is finding the sum. Icon was one of the first languages to have generators. `!` generates all the values of the list `L` that are accumulated to `s`. Normally we need to write `every s+:=!L`, but I used backtracking with `&\z`, which checks if the non-existent `z` variable is `non-null`, which is not, and extracts the next value from the list until exhaustion.

# Answer
> 1 votes
## Batch, 111 bytes

```
@shift
@set s=%*
@call set/as=%s: =+%-%0,s=(%%%0*10000+s/2)/s,h=s%%%%10,t=s/10%%%%10,s/=100
@echo %s%.%t%%h%

```

Takes input as index and list as command-line arguments. Note: Only works for index values from `1` to `9` due to limitations of Batch; a 0-indexed version could be written which would be able to index the first 10 elements. Explanation:

```
@shift

```

Shift the index to `%0` and the list to `%1`...`%9` (or less). Note however that Batch's `shift` does not affect `%*`.

```
@set s=%*

```

Get all of the parameters, space separated.

```
@call set/as=%s: =+%-%0,s=(%%%0*10000+s/2)/s,h=s%%%%10,t=s/10%%%%10,s/=100

```

Change the spaces to `+`s and evaluate arithmetically, thus taking the sum, but subtract the index. Then index into the list, multiply by 10000, add half of the sum, and divide by the sum. Finally perform divmod by 10 twice to generate the decimal places. (The `%` arithmetic operator has special meaning in Batch and normally needs to be doubled but the `call` then requires a further doubling.)

```
@echo %s%.%t%%h%

```

Output the result and the decimal places.

# Answer
> 1 votes
# Swift, 60 bytes

```
{(n:[Int],i)->Float in
1e2*Float(n[i])/Float(n.reduce(0,+))}

```

Try it online!

I picked Swift to participate and bumped into its type sensitivity !

# Answer
> 1 votes
# T-SQL 2008, 41 bytes

To find the row number equal to the index:

A division of index and row number multiplied with division of row number and index, if both results are 1, index and row are the same because both are above 0 and integer division round down. This saves 1 byte compared to using IIF

> a - value
>
> b - row number

Using table variable as input. 1-indexed

```
SELECT max(b/@*(@/b)*a*100)/sum(a)FROM @x

```

**Try it online**

# Answer
> 1 votes
# Julia 1.0, 21 bytes

```
f(l,i)=100l[i]/sum(l)

```

Try it online!

# Answer
> 1 votes
# Stax, 7 bytes

```
â└╡Æå'W

```

Run and debug it at staxlang.xyz!

0-indexed. Requires at least one item in the input list to be of the form `N.0` rather than simply `N`. Replacing `/` in the unpacked version with `:_` gets around this restriction at the cost of one byte.

### Unpacked (8 bytes) and explanation:

```
@AJ*x|+/    Index atop the stack, with the list beneath
@           Element at index...
 AJ*        Times 100
    x|+     Sum of list
       /    Divide

```

# Answer
> 1 votes
# k4, 14 bytes

```
{%+/x%100*x y}

```

can save 1 byte from @Galen Ivanov's solution (in oK) as `%` is inverse operation in k4 as opposed to square root

# Answer
> 1 votes
# Clojure, 40 bytes

```
(fn[a b](* 1e2(/(nth a b)(apply + a))))

```

Try it online!

It's nice to know about the 1e2 trick. :-)

# Answer
> 1 votes
# Arturo, 23 bytes

```
$[a,i][100*a\[i]//∑a]

```

Try it

# Answer
> 1 votes
# PowerShell Core, 39 bytes

```
param($a,$i)$a[$i]/($a-join'+'|iex)*1e2

```

Try it online!

Uses 0 indexed input and doesn't do rounding

# Answer
> 1 votes
# Pyt, 10 bytes

```
Đ←⦋⇹Ʃᵮ/2ᴇ*

```

Try it online!

Zero-based indexing. Takes the array, then the index

```
Đ                 implicit input; Đuplicate
 ←                get input
  ⦋               get element at index
   ⇹              swap top two items on stack
    Ʃ             get Ʃum
     ᵮ            cast to ᵮloat
      /           divide
       2ᴇ*        multiply by 100; implicit print

```

# Answer
> 1 votes
# Itr, 11 bytes

`#ä#@áS/100*`

zero-indexed, outputs a fraction

online Interpreter

7 bytes to output the proportion as a fraction:

`#ä#@áS/`

# Explanation

```
#           ; read the first input
 ä          ; duplicate it
  #         ; read the second input
   @        ; get the element at that index in the first input
    á       ; swap the two elements
     S      ; sum up the array
      /     ; divide the element by the sum
       100* ; convert the result to percent
            ; implicit output

```

---

# Itr, 14 bytes

`#ä#@áS/0e100**`

outputs the result as a float

# Answer
> 1 votes
# Rust, 36 bytes

```
|v,i|v[i]*100./v.iter().sum::<f32>()

```

0-indexed, assuming integers cast to floats before the function call

Rust Playground

# Answer
> 0 votes
# Canvas, 8 bytes

```
＠；∑÷ＡＡ××

```

Try it here!

Uses 1-indexing.

The last half just multiplies by 100, so 4 bytes can be saved if percentage over interval \[0,1\] is allowed as opposed to percentage over interval \[0,100\].

---

Explanation of example run: list = `[1, 2, 3, 4, 5]`, index = `5`.

```
Stack Visualization                 | Executed Instruction | Explanation
------------------------------------+----------------------+-----------------------------------------------------------------------------
..., [1,2,3,4,5], 5, [1,2,3,4,5]    | (program start)      | Canvas starts with the stack populated with the inputs repeating infinitely
..., [1,2,3,4,5], 5                 | ＠, get item         | ＠NA gets the Nth item of A
..., 5, [1,2,3,4,5]                 | ；, swap two ToS     | Swaps the position of the two top items in the stack
..., 5, 15                          | ∑, sum               | Sums all items in an array
..., 0.33333333333333333333         | ÷, divide            | Divides the two top items in the stack
..., 0.33333333333333333333, 10     | Ａ, push 10          | Pushes 10 to the stack
..., 0.33333333333333333333, 10, 10 | Ａ, push 10          | "                    "
..., 0.33333333333333333333, 100    | ×, multiply          | Multiplies the two top items in the stack
..., 33.333333333333333333          | ×, multiply          | "                                       "
...                                 | (end of program)     | Pop and print ToS

```

# Answer
> 0 votes
# Forth (gforth), 61 bytes

```
: f 8 * over + f@ 0e swap 0 do dup f@ f+ 8 + loop f/ 1e2 f* ;

```

Try it online!

It's way too painful to work with arrays in Forth...

A function that takes three items (array length, array start address, index; rightmost being the top) from the main stack, and gives the answer on the FP stack. The array contains floating-point values.

### How it works

```
: f ( len addr idx -- F: ans )
  8 * over + ( len addr addr[idx] ) \ compute the address for the item
  f@ 0e ( len addr F:x F:sum )      \ fetch the float at addr[idx] and push 0 on FP stack
  swap 0 do ( addr F:x F:sum )      \ repeat len times..
    dup f@ f+                       \   fetch the float at addr, add it to the sum
    8 +                             \   increment the addr by one cell
  loop                              \ end loop
  f/ 1e2 f*                         \ compute x / sum * 100
;

```

# Answer
> 0 votes
# Vyxal, 6 bytes

```
₌i∑/₁*

```

Try it Online!

Another 6 byter joins the fray. Takes index then list. 0-indexed

## Explained

```
₌i∑/₁*
₌i∑     # Push list[index], sum(list)
   /    # ^ / ^
    ₁*  # times 100

```

# Answer
> 0 votes
# Thunno, \\$ 9 \log\_{256}(96) \approx \\$ 7.41 bytes

```
AHz1S/Z2*

```

Attempt This Online!

Uses 1-indexing. Change `AH` to `AI` for 0-indexing.

#### Explanation

```
AHz1S/Z2*  # Implicit input
AH         # Index into the list
  z1S      # Sum the list
     /     # Divide
      Z2*  # Multiply by 10**2

```

# Answer
> 0 votes
# Thunno 2, 6 bytes

```
i$S/ɦ×

```

Try it online!

0-indexed. Change `i` to `İ` for 1-indexing.

#### Explanation

```
i$S/ɦ×  # Implicit input
i       # Index in
 $      # Push the first input again
  S     # Take the sum
   /    # Divide
    ɦ×  # Multiply by 100
        # Implicit output

```

---
Tags: code-golf, math, array, arithmetic
---