# Question
Title: Interleave numbers from 1 to n, with the same numbers reversed
### A simple one:

Take a positive integer **n** less than 1000, and output the integers from **1** to **n** interleaved with the integers from **n** to **1**. You must concatenate the numbers so that they appear without any delimiters between them.

### Test cases:

```
n = 1
11

n = 4
14233241

n = 26
12622532442352262172081991810171116121513141413151216111710189198207216225234243252261

n = 100
110029939849759669579489399210911190128913881487158616851784188319822081218022792378247725762675277428732972307131703269336834673566366537643863396240614160425943584457455646554754485349525051515052495348544755465645574458435942604161406239633864376536663567346833693270317130722973287427752676257724782379228021812082198318841785168615871488138912901191109299389479569659749839921001

```

This is so the shortest submission in bytes in each language wins. Explanations are encouraged.

# Answer
## JavaScript (ES6), 30 bytes

```
f=(n,k=1)=>n?f(n-1,k+1)+n+k:''

```

### How?

This is pretty straightforward but it's worth noting that the string is built from tail to head. An empty string at the beginning is appended last and allows the coercion of the final result to a string to happen.

Below is the detail of the recursion for `f(4)`:

```
f(4) =                                            // initial call
f(4, 1) =                                         // applying the default value to k
f(3, 2) + 4 + 1 =                                 // recursive call #1
(f(2, 3) + 3 + 2) + 4 + 1 =                       // recursive call #2
((f(1, 4) + 2 + 3) + 3 + 2) + 4 + 1 =             // recursive call #3
(((f(0, 5) + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 =   // recursive call #4
((('' + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 =        // n = 0 --> end of recursion
'' + 1 + 4 + 2 + 3 + 3 + 2 + 4 + 1 =              // final sum
'14233241'                                        // final result

```

### Test cases

```
f=(n,k=1)=>n?f(n-1,k+1)+n+k:''

console.log(f(1))
console.log(f(4))
console.log(f(26))
console.log(f(100))
```
> 19 votes

# Answer
# Python 2, 46 bytes

```
lambda n:''.join(`x+1`+`n-x`for x in range(n))

```

Thanks to ovs for 4 bytes

Try it online!

Explanation:

```
lambda n:''.join(`x+1`+`n-x`for x in range(n))
lambda n:                                      # anonymous lambda taking one parameter n
                 `x+1`+`n-x`                   # `x` is repr(x) which is equivalent to str(x) for integers less than INT_MAX
                            for x in range(n)  # integers x in [0, n)

```
> 11 votes

# Answer
# Bash, 25 bytes

```
printf %s`seq $1 -1 1|nl`

```

Try it online!

Prints decreasing sequence, number lines increasing and printf joins lines

~~Space delimited, 20 bytes : seq $1 -1 1|nl|xargs~~
> 10 votes

# Answer
-5 thanks to Ørjan Johansen

# Haskell, 33 bytes

```
f n=do a<-[1..n];[a,n-a+1]>>=show

```

Try it online!
> 8 votes

# Answer
# R, 35 bytes

```
n=scan();cat(rbind(1:n,n:1),sep="")

```

Try it online

`rbind(1:n,n:1)` creates a 2 row matrix with 1 to n in the first row and n to 1 in the second. The `cat` function collapses this matrix, reading down each column.
> 7 votes

# Answer
# 05AB1E, ~~6~~ 5 bytes

Saved a byte using the new interleave built-in as suggested by *rev*

```
LÂ.ιJ

```

Try it online!

**Explanation**

```
L        # range [1 ... input]
 Â       # create a reversed copy
  .ι     # interleave the lists
    J    # join

```
> 6 votes

# Answer
## CJam, 10 bytes

```
ri,:)_W%]z

```

Try it online!

### Explanation

```
ri   e# Read input and convert to integer N.
,    e# Turn into range [0 1 ... N-1].
:)   e# Increment to get [1 2 ... N].
_W%  e# Duplicate and reverse the copy.
]    e# Wrap both in an array to get [[1 2 ... N] [N ... 2 1]]
z    e# Transpose to get [[1 N] [2 N-1] ... [N-1 2] [N 1]]
     e# This list is printed implicitly at the end of the program,
     e# but without any of the array structure (so it's essentially flattened,
     e# each number is converted to a string and then all the strings
     e# are joined together and printed).

```
> 4 votes

# Answer
# Ruby, 29 bytes

```
->n{n.times{|x|$><<x+1<<n-x}}

```

## Explanation:

```
->n{n.times{|x|                # x in range [0..n-1]
               $><<            # output on console
                   x+1<<n-x}}  # x+1, then n-x

```

Try it online!
> 4 votes

# Answer
# Pyth, 7 bytes

```
jksC_BS

```

Try it online: Demonstration

### Explanation:

```
jksC_BSQ   implicit Q (=input number) at the end
      SQ   create the range [1, ..., Q]
    _B     bifurcate by inversion, this gives [[1, ..., Q], [Q, ..., 1]]
  sC       zip and flatten result
jk         join to a string

```
> 4 votes

# Answer
## Haskell, ~~65~~ ~~48~~ 47 bytes

1 byte saved thanks to Laikoni:

```
f n=show=<<(\(l,r)->[l,r])=<<zip[1..][n,n-1..1]

```

---

6 bytes saved thanks to nimi:

```
f n=show=<<(\(l,r)->[l,r])=<<zip[1..n][n,n-1..1]

```

---

Previous answer and explanation:

```
f n=concatMap show$concatMap(\(l,r)->[l,r])(zip[1..n][n,n-1..1])

```

There's already a better Haskell answer here, but I'm new to both Haskell and code golfing, so I may as well post it :)

This function zips the list \[1..n\] with its reverse, resulting in a list of tuples.

```
[(1,n),(2,n-1),(3,n-2)..(n,1)]

```

Then it uses `concatMap` to map a lambda to this list of tuples that results in a list of lists...

```
[[1,n],[2,n-1],[3,n-2]..[n,1]]

```

...and concatenates it.

```
[1,n,2,n-1,3,n-2..n,1]

```

Then a final `concatMap` maps `show` to the list and concatenates it into a single string.

`f 26
"12622532442352262172081991810171116121513141413151216111710189198207216225234243252261"`
> 4 votes

# Answer
# Whitespace, 71 bytes

```

```

Try it online!

## Explanation

```
sssn  ; push 0 - seed the stack with 0 (this will be our 1->n counter, a)
sns   ; dup
tntt  ; getnum - read n (stored on the heap)
sns   ; dup
ttt   ; retr - pull n onto the stack (this will be our n->1 counter, b)
nssn  ; label 'loop'
snt   ; swap - bring a to the top
ssstn ; push 1
tsss  ; add - increment a
sns   ; dup
tnst  ; putnum - output a as a number
snt   ; swap - bring b to the top
sns   ; dup
tnst  ; putnum - output b as a number
ssstn ; push 1
tsst  ; sub - decrement b
sns   ; dup
ntstn ; jez 'exit' if b is 0
nsnn  ; jmp 'loop'

```

The first couple of instructions are needed to set up the stack correctly, Whitespace's input commands write to the heap so we need to copy b (the input value) back onto the stack. We start with a = 0 since it is shorter to declare 0 instead of 1 (saves a byte) and we only need to reorder the increment instruction to cope. After that we just loop and increment a, output a, output b, decrement b, until b reaches 0 (checked after the decrement).
> 4 votes

# Answer
# Aceto, ~~25~~ 22 bytes

```
)&
pX`=
(pl0
id@z
r}Z)

```

### Explanation:

We read an integer and put it on two stacks.

```
id
r}

```

On one, we call range\_up (`Z`), on the other range\_down (`z`), then we set a catch mark to be able to return to this place later:

```
  @z
  Z)

```

We then check if the current stack is empty and exit if so:

```
 X`=
  l0

```

Otherwise, we print from both stacks and jump back to the catch mark:

```
)&
p
(p

```
> 3 votes

# Answer
# Röda, ~~21~~ 19 bytes

```
{seq 1,_<>seq _1,1}

```

Try it online!

This is an anonymous function that takes input from the stream.

### Explanation

```
{seq 1,_<>seq _1,1}               Anonymous function, takes integer n from the stream
        <>                        Interleave
 seq 1,_                            the range 1 .. n with
          seq _1,1                  the range n .. 1

```
> 3 votes

# Answer
# Octave, 29 bytes

```
@(n)printf("%d",[1:n;n:-1:1])

```

Try it online!
> 3 votes

# Answer
**Scala, 43 bytes**

It's not the best but it's my first code golf.

```
n=>1.to(n).foldLeft("")((s,x)=>s+x+(n-x+1))

```
> 3 votes

# Answer
# Perl 6, 20 bytes

```
{[~] 1..*Z~($_...1)}

```

Test it

With an input of 100000 this takes roughly 10 seconds, including compilation and printing the output.

## Expanded:

```
{                # bare block lambda with implicit parameter ｢$_｣

  [~]            # reduce using concatenation operator ｢&infix:«~»｣
                 # (shorter than ｢join '',｣)

    1 .. *       # Range from 1 to infinity

    Z~           # zip using concatenation operator

    ( $_ ... 1 ) # deduced sequence starting at the input
                 # going down to 1
}

```

The `Z~` needs the `~` because otherwise it generates a list of lists which will stringify with spaces.

There is no need to limit the Range starting at 1, because `Z` stops when any of the input lists run out.
This saves two bytes (a space would be needed after `$_`)
> 3 votes

# Answer
# Java 61 bytes

```
(int n)->{for(int i=0;i<n;System.out.print(i+1+""+(n-i++)));}

```
> 3 votes

# Answer
# Jelly, 5 bytes

```
RṚĖVV

```

Try it online!

### How it works

```
RṚĖVV  Main link. Argument: n

R      Range; yield [1, ..., n].
 Ṛ     Reverse; yield [n, ..., 1].
  Ė    Enumerate; yield [[1, n], ..., [n, 1]].
   V   Eval; convert each flat array to a string, interpret it as a Jelly program,
       and yield the output. This concatenates the integers in each pair, yielding
       a flat array of integers
    V  Repeat the previous step, concatenating the intgegers from before.

```
> 3 votes

# Answer
# Clojure, 61 bytes

```
#(let[a(range 1(+ 1 %))](apply str(interleave a(reverse a))))

```

Literally does what is asked. I believe it can be outgolfed by a less trivial solution.

See it online
> 2 votes

# Answer
# PHP, 36 35 29 bytes

```
for(;$argn;)echo++$i,$argn--;

```

Saved one byte thanks to Jörg Hülsermann.
Saved six bytes thanks to Christoph.
> 2 votes

# Answer
# Brachylog, ~~10~~ 9 bytes

```
⟦₁g↔ᶻczcc

```

Try it online!

### Explanation

```
⟦₁           [1, …, Input]
  g↔ᶻc       [[1, …, Input],[Input, …, 1]]
      z      Zip
       cc    Concatenate twice

```
> 2 votes

# Answer
# R, 41 bytes

```
pryr::f(for(i in 1:x){cat(i);cat(x-i+1)})

```

`pryr::f()` creates a function that takes one input. Loops over `1:x` and prints each element of `1:x` along with each element of `x:1`. Prints to STDOUT.
> 2 votes

# Answer
# MATL, ~~13~~ ~~11~~ 9 bytes

*2 bytes saved thanks to @Luis*

```
:tPv1eVXz

```

Try it at **MATL Online**

**Explanation**

```
        % Implicitly grab input as a number, N
:       % Create an array from 1..N
tP      % Create a reversed copy
v       % Vertically concatenate the two
1e      % Reshape it into a row vector
V       % Convert to a string
Xz      % Remove whitespace and implicitly display

```
> 2 votes

# Answer
# , 20 bytes

```
ywo1@"ñykPjñkògJ

```

Try it online!

Explain:

```
yw                    ' Copy the input number (for looping later)
  o1                 ' Insert a 1 under the input (on a newline)
     @"               ' [Copy register] number of times
       ñ      ñ       ' Do the thing inside of this loop
        ykP           ' Copy the current line and line above it, and paste above both
           j        ' decrement the current (top) number, and increment the one below
               k      ' Go to the top line
                ògJ   ' recursively join all of the lines

```
> 2 votes

# Answer
# Cubix, 17 bytes

```
....1I>sO)su.@?(O

```

Try it online!

cubified:

```
    . .
    . .
1 I > s O ) s u
. @ ? ( O . . .
    . .
    . .

```

Pushes `1`, reads in the input (`I`), then enters the loop which swaps the top of the stack, outputs it, increments, swaps, outputs the top of the stack, decrements, and stops if the top of the stack is 0.
> 2 votes

# Answer
# Common Lisp, ~~63~~ 54 bytes

```
(lambda(n)(dotimes(i n)(format t"~a~a"(1+ i)(- n i))))

```

Try it online!
> 2 votes

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

```
{,//$r,'|r:1+!x}

```

Try it online!
> 2 votes

# Answer
# MathGolf, 5 bytes

```
{îkï-

```

Try it online!

### Explanation:

```
{      Run a for loop over implicit input
 î     Push 1 based index of loop
  k    Push inputted number
   ï-  Subtract 0 based index of loop
       Implicitly output all this joined together

```
> 2 votes

# Answer
# Forth (gforth), 41 bytes

```
: f 1+ dup 1 do i 1 .r 1- dup 1 .r loop ;

```

Try it online!

### Explanation

Loops from 1 to n and outputs the index as well as n-index in a right-aligned space of size 1 (forces no space after output)

### Code Explanation

```
: f               \ start new word definition
  1+ dup 1        \ set up arguments to loop from 1 to n
  do              \ start loop
    i 1 .r        \ output the index in a right-aligned space of size 1
    1- dup        \ subtract 1 from current value of n and duplicate
    1 .r          \ output new n in right-aligned space of size 1
  loop            \ end loop
;                 \ end word definition

```
> 2 votes

# Answer
# Mouse-2002, 32 30 bytes

-2 moved conditional to start of loop `(z.^ ... )` instead of `(... z.0>^)`

```
?n:n.z:(z.^a.1+a:a.!z.!z.1-z:)

```

Try it online!

**Explanation:**

```
?n:                                 ~ get input and store in n
   n.z:                             ~ copy n into z
       (z.^                         ~ stop if z equals 0
           a.1+a:                   ~ add 1 to a
                 a.!                ~ print a
                    z.!             ~ print z
                       z.1-z:)      ~ substract 1 from z

```
> 2 votes

# Answer
# Vyxal, ~~5~~ 4 bytes

```
ɾḂYṅ

```

Try it Online!

### Explained

```
ɾḂYṅ
ɾ     # range of [1,input+1]
 Ḃ    # dupe and reverse
   Y  # interleave
    ṅ # join with no spaces

```
> 2 votes

# Answer
# tinylisp 2, ~~46~~ 32 bytes

```
(\(N)(} ,(m u({ ,(z(1to N)(to1 N

```

An anonymous function that takes an integer and returns a string. Try it at Replit. Example session:

```
tl2> (\(N)(} ,(m u({ ,(z(1to N)(to1 N
(() (N) (} , (m u ({ , (z (1to N) (to1 N))))))
tl2> (def interleave-numbers _)
interleave-numbers
tl2> (interleave-numbers 4)
"14233241"

```

### Explanation

```
(\(N)(} ,(m u({ ,(z(1to N)(to1 N))))))
(\                                   ) ; Lambda function
  (N)                                  ; that takes an integer N:
                 (z              )     ;  Zip together these two lists:
                   (1to N)             ;   Numbers from 1 to N
                          (to1 N)      ;   Numbers from N to 1
             ({ ,                 )    ;  Right fold on list/string concatenation
         (m u                      )   ;  Map unparse (convert to string) to each number
     (} ,                           )  ;  Left fold on list/string concatenation

```

The reason for the different folds is that right fold is more efficient, but by default it starts with an empty list, which when concatenating strings would make the result a list of charcodes instead of a string. Left-folding strings, by contrast, results in a string.
> 2 votes

# Answer
# Actually, 9 bytes

```
R;R@Z♂iεj

```

Try it online!, or run all test cases

Explanation:

```
R;R@Z♂iεj
R          range(1, n+1)
 ;R        duplicate and reverse
   @Z      swap and zip
     ♂i    make 1D
       εj  join with empty string

```
> 1 votes

# Answer
## QBIC, 18 bytes

```
[:|Z=Z+!a$+!b-a+1$

```

Explanation

```
[:|       FOR a = 1 to n
Z=Z+      Add to Z$
!b$+      a cast of the loop counter as string
!b-a+1$   and a cast of (n+1) minus the loop counter to string
          Z$ is printed implicitly at the end of QBIC

```
> 1 votes

# Answer
# Mathematica, ~~36~~ 32 bytes

```
Row@Riffle[x=Range@#,Reverse@x]&

```

*thanks Martin*
> 1 votes

# Answer
# CJam, ~~13~~ 12 bytes

*1 byte removed thanks to Martin Ender*

```
ri:X{_)X@-}%

```

Try it online!

### Explanation

```
ri               e# Read integer n
  :X             e# Copy n into variable X
     {     }%    e# Map over the array [0 1 2 ... n-1]
      _          e# Duplicate
       )         e# Add 1
        X        e# Push n
         @       e# Rotate
          -      e# Subtract

```
> 1 votes

# Answer
# AWK, ~~34~~ 30 bytes

`~~{for(i=1;i<=$1;i++)printf i$1-i+1}~~`

```
{for(;i<$1;i++)printf i+1$1-i}

```

Try it online!
> 1 votes

# Answer
## Perl 5, 28 bytes

**27 bytes code + 1 byte for `-a`.**

```
map{print$_,"@F"+1-$_}1..$_

```

Try it online!
> 1 votes

# Answer
# Braingolf v0.7, 18 bytes

```
VR.MUvU&,R{vMR}>&_

```

Try it online!

### Explanation:

```
VR.MUvU&,R{vMR}>&_  Implicit input of n to stack
VR                  Create new stack then return to main
  .M                Duplicate n and move duplicate to new stack
    U               Replace stack with 1-n, where n is last item on stack
     vU             Replace 2nd stack with 1-n
       &,           Reverse second stack
         R          Return to main
          {   }     Map loop, runs for each item in the stack
           vMR      Move to next stack, move last item to main stack
               >    Cleanup after loop
                &_  Print all items in stack with no delimiter

```
> 1 votes

# Answer
# Japt `-P`, 11 8 bytes

*Saved 2 byte thanks to @Shaggy*

```
õ í1õU)c

```

Try it online!

## Explanation:

```
õ í1õU)c
õ              Range [1...Input]
  í            Pair with:
   1õU           Range [Input...1]
      )c       Flatten
-P             Join into a string

```
> 1 votes

# Answer
# Powershell, 37 bytes

```
param($n)-join(1..$n|%{$_,($n-$_+1)})

```
> 1 votes

# Answer
# Jelly, 6 bytes

```
RżU$FV

```

Try it online!

Explanation:

```
         Example: n = 6
R        Create a range from 1 to n             [1, 2, 3, 4, 5, 6]
  U$     and a reversed copy of that same range [6, 5, 4, 3, 2, 1]
 ż       and interleave them                    [ [1, 6], [2, 5, ... ]
    F    Flatten the list                       [1, 6, 2, 5, 3, 4 ...]
     V   And Eval: Jelly code consisting of only numbers would simply print those numbers,

```
> 1 votes

# Answer
# Retina, 20 bytes

```
.+
$*__
\B
$.`$.'
_

```

Try it online! Includes test cases. Explanation: Each pair of numbers sums to `n+1`, so we convert `n` to unary and add 1. Then, we match between each pair of `_`s, counting the number of `_`s to the left and right. This generates the pairs of numbers. Finally we delete the `_`s now that they've served their purpose.
> 1 votes

# Answer
# \>\<\>, ~~16~~ 12+3 = ~~19~~ 15 bytes

```
l:n}:n1-:?!;

```

Input is expected on the stack, so +3 bytes for the `-v` flag.

Thanks to @TealPelican for pointing out a very clever way to save 4 bytes by using the size of the stack itself - on the first iteration it'll be 1, then 2, then 3... That way, the first number in each pair manages itself, no manual incrementing required!

Previous version:

```
1:n1+$:n1-:?!;$!

```

Try it online!
> 1 votes

# Answer
# Perl 5, ~~25~~ 21 + 1 = ~~26~~ 22 bytes

Takes input from stdin, without a trailing newline.

Runs with the `-n` flag:

```
print++$x.$_--while$_

```

4 bytes saved thanks to Dada.
> 1 votes

# Answer
# C (gcc), 43 bytes

```
a;f(n){for(a=1;n;a++)printf("%d%d",a,n--);}

```

Try it online!
> 1 votes

# Answer
# Python 3, 51 bytes

```
lambda n:''.join("%d%d"%(x+1,n-x)for x in range(n))

```

Try it online!

Port of Mego's Python 2 answer.
> 1 votes

# Answer
# Japt `-mP`, ~~8~~ 6 bytes

```
°Us+N´

```

Try it

```
           :For each U in the range [0,input)
°U         : Prefix increment U
  s        : Convert to a string
   +       : Append
    N´     :  Postfix decrement the (singleton) array of inputs
           :Implicitly join and output

```
> 1 votes

# Answer
# C# (.NET Core), 53 bytes

```
a=>{for(int i=0;++i<=a;)Console.Write(i+""+(a-i+1));}

```

Try it online!

Uses an Action delegate to pull in the input and not require a return.

Ungolfed:

```
a => {
    for(int i = 0; ++i <= a;)           // initialize i and increment until a
        Console.Write(i + "" + (a - i + 1));    // output i and "inverse" of i
                                                    // empty string required to set as string
                                                    // parentheses required because C# is dumb and can't figure out what a minus sign is supposed to do without them
}

```
> 1 votes

# Answer
# Kotlin, ~~52~~ 50 bytes

```
fun g(e:Int)=(1..e).forEach{print("$it${e-it+1}")}

```

Try it online

Older version, the one above also prints it, the one below produces a string.

```
fun y(n:Int)=(1..n).joinToString(""){"$it${n-it+1}"}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 10 bytes<sup>SBCS</sup>

```
(∊⍪,⌽)⍕¨∘⍳

```

Try it online!

Explanation:

```
(∊⍪,⌽)⍕¨∘⍳  ⍝ Monadic function train
       ⍕¨∘⍳  ⍝ Generate integers from 1 to input, convert each to string
             ⍝ Call this vector "X"
  ⍪          ⍝ "Table" X, making a single-column matrix
   ,⌽       ⍝ Reverse X and concatenate it with the above table
             ⍝ This results in a two-column matrix with integers from
             ⍝ 1 to N and N to 1 side-by-side
 ∊           ⍝ "Enlist" the above - left-to-right, top-to-bottom,
             ⍝ recursively concatenate all items in the matrix

```
> 1 votes

# Answer
# Zsh, 32 bytes

```
repeat $1 printf $[++i]$[$1+1-i]

```

Try it online!

I like trying to beat Bash+coreutils with pure zsh, but sadly that is not the case here.

---

Cooler, but one byte longer (**33 bytes**):

```
a=({$1..1})
<<<${(j::)${(n)a}:^a}

```

Try it online!
> 1 votes

# Answer
# Pyt, 5 bytes

```
řĐ↔Žǰ

```

Try it online!

```
ř          implicit input (n); push [1,2,...,n]
 Đ         duplicate top of stack
  ↔        flip the array at the top of the stack
   Ž       interleave the two arrays
    ǰ      join the contents of the array to create a string; implicit print

```
> 1 votes

# Answer
# Ly, 12 bytes

```
Rsrp[ul,s`u]

```

Try it online!

This one generates the `1..N` series on the stack, and it generates the `N..1` numbers by manipulating an accumulator on the backup cell.

```
R             - Generate range of 0..N (where N is from STDIN)
 s            - Save the upper limit to the backup cell
  rp          - Reverse the stack, delete the "0"
    [      ]  - While the stack isn't empty
     u        - Print next number in the range
      l,s     - Load backup cell, decrement and save
         `u   - Increment and print

```
> 1 votes

# Answer
# Go, 90 bytes

```
import."fmt"
func f(n int)(o string){for i:=1;i<=n;i++{o+=Sprintf("%d%d",i,n-i+1)};return}

```

Attempt This Online!
> 1 votes

# Answer
# Julia 1.0, ~~33~~ 22 bytes

```
~x=join([1:x x:-1:1]')

```

Try it online!

1. The forward and reverse sequences are collected from ranges.
2. This method of interleaving arrays in Julia can be adapted for code golf.
3. ~~The `print` command is vectorized with the "dot" operator so that no delimiters are shown.~~

* -9 bytes thanks to MarcMush: avoid reshaping the array
* -2 bytes thanks to MarcMush: replace `print.` with `join`
> 1 votes

# Answer
# , 18 bytes

```
[:;],.&<&":&>:&i.-

```

Try it online!
> 1 votes

# Answer
# Pip, 10 bytes

-2 bytes thanks to DLosc!

```
Y\,ayWVRVy

```

Try It Online!

---

# Pip, 12 bytes

```
(Y++,a)WVRVy

```

How?

```
(Y++,a)WVRVy  : One arg(integer n)
     a        : First arg
    ,         : Inclusive range from 1
  ++          : Increment
 Y            : Yank
         RV   : Alias for unary reverse
           y  : Yanked range
       WV     : Weave two iterables together, alternating their items

```

Try It Online!
> 1 votes

# Answer
## Clojure, 52 bytes

```
#(apply str(mapcat(fn[i][(inc i)(- % i)])(range %)))

```

Concatenates pair-wise integers (head and tail of the seq).
> 0 votes

# Answer
**Python 2.7, 39 bytes**

```
x=''.join(`i+1`+`n-i`for i in range(n))

```
> 0 votes

# Answer
## Pyke, 9 bytes

```
SD_],sm`s

```

Try it here!
> 0 votes

# Answer
## Mathematica, 52 bytes

As a traditional function:

```
f[x_] := StringJoin[ToString /@ Riffle[Range[x], Reverse[Range[x]]]]

```

As an anonymous function

```
(x = Range[#]; StringJoin[ToString /@ Riffle[x, Reverse[x]]]) &

```

As a code block that accepts the input in the variable n

```
x = Range[n]; StringJoin[ToString /@ Riffle[x, Reverse[x]]]

```

The code is pretty simple -- generate the list of integers with Range\[\], interleave this list (using Riffle\[\]) with a copy of the list that has been reversed, then convert all the integers to strings and concatenate them with StringJoin\[\].

Could have done it in 30 bytes if we were allowed to leave the answer in the form of a list (thus, {1,4,2,3,3,2,4,1} rather than "14233241"). Also, in the hypothetical Mthmtca with short command names it would have been something like 21 bytes.

Performance is tolerable for n \<= 1,000,000. I didn't test past that.
> 0 votes

# Answer
## R, 43 39 37 bytes

This is an anonymous function.

```
function(n)cat(rbind(1:n,n:1),sep="")

```

It's 35 bytes if I use `pryr::f()` like in the other answer:

```
pryr::f(cat(rbind(1:n,n:1),sep=""))

```

but needs to be installed (Enter `install.packages("pryr")` in the R console).
> 0 votes

# Answer
## Python 2, 67 bytes

A simple one, just for the collection :)

```
n=input()+1
i=1
s=""
while i<n:
    s+=`i`+`n-i`
    i+=1
print s

```
> 0 votes

# Answer
# Hexagony, 15 bytes

```
{?\"!\{$.(.@).!

```

Embiggened:

```
   { ? \
  " ! \ {
 $ . ( . @
  ) . ! .
   . . .

```

Try it online!
> 0 votes

# Answer
## LOGO, 48 bytes

```
to f :n
for[i 1 :n][(type :i :n+1-:i)]show "
end

```

Define a function `f` that when invoke with parameter = number `n`, print the result string.
> 0 votes

# Answer
# braingasm, 9 bytes

```
;[>+:<:-]

```

Simple: Read a number from stdin to the current cell; While the current cell is not zero, go to next cell (initially 0), increase it, output its value, go back, output that value and decrease it.
> 0 votes

# Answer
# Java 8, ~~53~~ 52 bytes

```
n->{for(int i=1;n>0;System.out.print(n--+""+i++));};

```

Try it online!
-1 bytes thanks to Sara J!
> 0 votes

# Answer
# Kotlin, 44 bytes

```
{n->(1..n).joinToString(""){"$it${n-it+1}"}}

{n->                                          // n is Int input
    (1..n)                                    // range from 1 to end
          .joinToString("")                   // join items with no separator
                           {                  // transform by
                            "$it${n-it+1}"    // current number and number from end of range
                                          }}

```

Lambda that takes an `Int` and returns a `String`.

Try it online!
> 0 votes

# Answer
# dc, 17 bytes

```
[znddn1-d0<M]dsMx

```

Try it online!
> 0 votes

# Answer
# APL(NARS), 13 chars, 26 bytes

```
{∊k,¨⌽k←⍕¨⍳⍵}

```

How to use & test:

```
  f←{∊k,¨⌽k←⍕¨⍳⍵}
  f 1
11
  f 26
12622532442352262172081991810171116121513141413151216111710189198207216225234243252261

```
> 0 votes

# Answer
# Ink, 47 bytes

```
=f(n)
~temp i=n
-(l)
~i--
{n-i}{1+i}{i:->l}->->

```

Try it online!
> 0 votes

# Answer
# Stax, 5 bytes

```
çK^↑Ñ

```

Run and debug it
> 0 votes

# Answer
# Arturo, 36 bytes

```
$[n][""loop 1..n'x->~"|n-x-1||x|"++]

```

Try it

```
$[n][             ; a function taking an argument n
  ""              ; place an empty string on the stack
  loop 1..n'x->   ; foreach x in 1 to n...
    ~"|n-x-1||x|" ; interpolate x and n-x-1 into a string
    ++            ; append it to the string on the stack
]                 ; end function

```
> 0 votes

# Answer
# Thunno `J`, \\$ 10 \log\_{256}(96) \approx \\$ 8.23 bytes

```
R1+DrsZZ.J

```

#### Explanation

```
R1+DrsZZ.J  # Implicit input                  STACK (example for n=10)
R1+         # range(0, n) + 1                 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   Dr       # Duplicate and reverse           [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
     sZZ    # Swap and zip together           [[1, 10], [2, 9], [3, 8], [4, 7], [5, 6], [6, 5], [7, 4], [8, 3], [9, 2], [10, 1]]
        .J  # Join each inner list            ['110', '29', '38', '47', '56', '65', '74', '83', '92', '101']
            # J flag joins the final list     '1102938475665748392101'
            # Implicit output

```

#### Screenshot
> 0 votes

# Answer
# Fig, \\$6\log\_{256}(96)\approx\\$ 4.939 bytes

```
OYax$a

```

Try it online!

```
OYax$a
 Y     # Interleave
  ax   # [1, n]
    $a # With [1, n] reversed
O      # Join

```
> 0 votes

# Answer
# Thunno 2 `J`, 3 bytes

```
RḲI

```

Attempt This Online!

#### Explanation

```
RḲI  # Implicit input       ->  4
R    # Range: push [1..n]   ->  [1,2,3,4]
 Ḳ   # Bifurcate this list  ->  [1,2,3,4]  [4,3,2,1]
  I  # Interleave           ->  [1,4,2,3,3,2,4,1]
     # Join and output      ->  "14233241"

```
> 0 votes

---
Tags: code-golf, string, number, integer
---


# Question
Title: Count the number of ones in an unsigned 16-bit integer
Write some statement(s) which will count the number of ones in an unsigned sixteen-bit integer.

For example, if the input is `1337`, then the result is `6` because `1337` as a sixteen bit binary number is `0000010100111001`, which contains six ones.

# Answer
> 39 votes
# 80386 Machine Code, 4 bytes

```
F3 0F B8 C1

```

which takes the integer in `cx` and outputs the count in `ax`, and is equivalent to:

```
popcnt ax, cx     ; F3 0F B8 C1

```

And here is an **~~11~~ 10** byte solution not using POPCNT:

```
31 C0 D1 E9 10 E0 85 C9 75 F8

```

which is equivalent to:

```
xor ax, ax        ; 31 C0   Set ax to 0
shr cx, 1         ; D1 E9   Shift cx to the right by 1 (cx >> 1)
adc al, ah        ; 10 E0   al += (ah = 0) + (cf = rightmost bit before shifting)
test cx, cx       ; 85 C9   Check if cx == 0
jnz $-6           ; 75 F8   Jump up to shr cx, 1 if not

```

# Answer
> 15 votes
# Python 2, 17 bytes

```
bin(s).count('1')

```

The `bin` built-in returns the integer converted to a binary string. We then count the `1` digits:

```
>>> s=1337
>>> bin(s)
'0b10100111001'
>>> bin(s).count('1')
6

```

# Answer
> 12 votes
## J (5 characters)

J has no explicit types. This does the right thing for all integers.

```
+/@#:

```
* `+/` the sum
* `@` of
* `#:` the base two representation

# Answer
> 11 votes
# C,21

```
for(n=0;x;n++)x&=x-1;

```

you said "write some statements" (not "a function") so I've assumed the number is supplied in `x` and the number of 1's is returned in `n`. If I don't have to initialize `n` I can save 3 bytes.

This is an adaptation of the famous expression `x&x-1` for testing if something is a power of 2 (false if it is, true if it isn't.)

Here it is in action on the number 1337 from the question. Note that subtracting 1 flips the least significant 1 bit and all zeroes to the right.

```
0000010100111001 & 0000010100111000 = 0000010100111000
0000010100111000 & 0000010100110111 = 0000010100110000
0000010100110000 & 0000010100101111 = 0000010100100000
0000010100100000 & 0000010100011111 = 0000010100000000
0000010100000000 & 0000010011111111 = 0000010000000000
0000010000000000 & 0000001111111111 = 0000000000000000

```

EDIT: for completeness, here's the naive algorithm, which is one byte longer (and quite a bit slower.)

```
for(n=0;x;x/=2)n+=x&1;

```

# Answer
> 8 votes
## Jelly, 2 bytes

```
BS

```

Jelly is a new language written by @Dennis, with J-like syntax.

```
         implicit: function of command-line arguments
B        Binary digits as list
 S       Sum

```

Try it here.

# Answer
> 4 votes
# Pyth, 4 bytes

```
sjQ2

```

The program takes the number whose hamming weight is to be found on STDIN.

# Answer
> 4 votes
# Julia, ~~29~~ ~~27~~ 19 bytes

```
n->sum(digits(n,2))

```

This creates an anonymous function that accepts a single argument, `n`. To use it, assign it to something like `f=n->...` and call it like `f(1337)`.

The `digits()` function, when called with 2 arguments, returns an array of the digits of the input in the given base. So `digits(n, 2)` returns the binary digits of `n`. Take the sum of the array and you have the number of ones in the binary representation of `n`.

# Answer
> 4 votes
# R, 24 bytes

```
sum(intToBits(scan())>0)

```

`scan()` reads input from stdin.

`intToBits()` takes an integer and returns a vector of type `raw` containing the zeroes and ones of the binary representation of the input.

`intToBits(scan())>0` returns a logical vector where each element is `TRUE` if the corresponding binary vector element is a 1 (since all elements are 0 or 1 and 1 \> 0), otherwise `FALSE`.

In R, you can sum a logical vector to get the number of `TRUE` elements, so summing the vector of logicals as above gets us what we want.

Note that `sum()` can't handle `raw` input directly, hence the workaround using logicals.

# Answer
> 4 votes
# APL (Dyalog Extended), ~~8~~ 3 bytes

```
+/⊤

```

Try it online!

-5 from Adám.

```
  ⊤ convert to base 2
+/  sum

```

# Answer
> 4 votes
# Rust, 15 bytes

```
u16::count_ones

```

Try it online!

Rust is better than C because `count_ones` is shorter than `__builtin__popcount` :)

Every built-in integer type (unsigned or signed, 8/16/32/64/128 bits) supports this method. Since the challenge specifically asks for unsigned 16 bit integers, we use `u16` here. Also, while the method is usually called in the form of `some_number.count_ones()`, `u16::count_ones(some_number)` is also a valid syntax for calling the same function.

# Answer
> 4 votes
# Vyxal, 2 bytes

```
b∑

```

Try it Online!

# Vyxal `s`, 1 byte

```
b

```

Try it Online!

# Answer
> 3 votes
# CJam, 6 bytes

```
ri2b:+

ri         "Read the input and convert it to integer";
  2b       "Convert the integer into base 2 format";
    :+     "Sum the digits of base 2 form";

```

Try it online here

# Answer
> 3 votes
# Joe, 4 bytes

```
/+Ba

```

This is an anonymous function. `Ba` gives the binary representation of a number and `/+` sums it.

```
   (/+Ba)13
3
   (/+Ba)500
6

```

# Answer
> 3 votes
# Mathematica, ~~22~~ 18 bytes

*Thanks to alephalpha for reminding me of `DigitCount`.*

```
DigitCount[#,2,1]&

```

# Answer
> 3 votes
# ES6 (~~34~~ ~~22~~ 21 bytes):

This is a simple recursive function that can be shortened a bit more. It simply takes a bit and runs itself again:

```
B=n=>n&&(1&n)+B(n>>1)

```

Try it on http://www.es6fiddle.net/imt5ilve/ (you need the `var` because of `'use strict';`).

I can't believe I've beaten Fish!!!

The old one:

```
n=>n.toString(2).split(1).length-1

```

---

# ES5 (39 bytes):

Both functions can be easily adapted to ES5:

```
function B(n){return n?(1&n)+B(n>>1):0}

//ungolfed:

function B(number)
{
    if( number > 0 )
    {
        //arguments.callee points to the function itself
        return (number & 1) + arguments.callee( number >> 1 );
    }
    else
    {
        return 0;
    }
}

```

Old one:

```
function(n){return n.toString(2).split(1).length-1}

```

---

@user1455003 gave me a really great idea, that 'triggered' the smallest one:

```
function B(n,x){for(x=0;n;n>>=1)x+=n&1;return x}

```

I've adapted it to ES6 and made it recursive to shorten a lot!

# Answer
> 3 votes
# Forth, ~~48~~ 49 bytes

```
: c ?dup if dup 1- and recurse 1+ then ;
0 1337 c

```

If an actual function is needed then the second line becomes

```
: c 0 swap c ;

```

and you call it by "1337 c". Forth's relatively verbose control words make this a tough one (actually, they make a lot of these tough).

Edit: My previous version did not handle negative numbers correctly.

# Answer
> 3 votes
# Ruby, 18 bytes

`n.to_s(2).count'1'`

# Answer
> 3 votes
# Python, ~~72~~ 26 bytes

Thanks to mathcat for ~~-12~~ ~~-27~~ -36 bytes through various simplifications!

```
lambda a:bin(a).count('1')

```

Well, you said *statements*...

# Answer
> 2 votes
# \>\<\> (Fish), 24 bytes + 2 = 26

```
0$11.>~n;
2,:?!^:2%:{+}-

```

The program just does repeated mod 2, subtract and divide until the input number becomes zero, then prints the sum of the mod 2s.

Test with the `-v` flag, e.g.

```
py -3 fish.py ones.fish -v 1337

```

# Answer
> 2 votes
# PHP (38 bytes):

This uses the same aproach as my ES6 answer

```
<?=count(split(1,decbin($_GET[n])))-1;

```

This is a full code, you only need to put it in a file and access it over the browser, with the parameter `n=<number>`.

# PHP \<4.2 (32 bytes):

This is a little shorter:

```
<?=count(split(1,decbin($n)))-1;

```

This only works reliably on PHP\<4.2 because the directive `register_globals` was set to `Off` by default from PHP4.2 up to PHP5.4 (which was removed by then).

If you create a `php.ini` file with `register_globals=On`, this will work.

To use the code, access the file using a browser, with either POST or GET.

# @ViniciusMonteiro's suggestion (38/45 bytes):

He gave 2 really good suggestions that have a very interesting use of the function `array_sum`:

38 bytes:

```
<?=array_sum(str_split(decbin(1337)));

```

45 bytes:

```
<?=array_sum(preg_split('//', decbin(1337)));

```

This is a really great idea and can be shortened a bit more, to be 36 bytes long:

```
<?=array_sum(split(1,decbin(1337)));

```

# Answer
> 2 votes
# C#, 45 bytes

```
Convert.ToString((ushort)15,2).Sum(b=>b-48);

```

https://dotnetfiddle.net/kJDgOY

# Answer
> 2 votes
# Japt, 3 bytes (non-competitive)

```
¢¬x

```

Try it here.

# Answer
> 2 votes
# beeswax, ~~31~~ 27 bytes

Non-competing answer. Beeswax is newer than this challenge.

This solution uses Brian Kherigan’s way of counting set bits from the “Bit Twiddling Hacks” website.

it just runs through a loop, incrementing the bit count, while iterating through `number=number&(number-1)` until `number = 0`. The solution only goes through the loop as often as there are bits set.

I could shave off 4 bytes by rearranging a few instructions. Both source code and explanation got updated:

```
pT_
>"p~0+M~p
d~0~@P@&<
{@<

```

Explanation:

```
pT_            generate IP, input Integer, redirect
>"             if top lstack value > 0 jump next instruction,
               otherwise continue at next instruction
  p            redirect if top lstack value=0 (see below)
   ~           flip top and 2nd lstack values
    0+         set top lstack value to 0, set top=top+2nd
      M        decrement top lstack value
       ~       flip top and 2nd lstack values
        p      redirect to lower left
        <      redirect to left
       &       top=top&2nd
      @        flip top and 3rd lstack values
    @P         increment top lstack value, flip top and 3rd values
 ~0~           flip top and 2nd values, set top=0, flip top and 2nd again
d              redirect to upper left
>"p~0+M.....   loop back

  p            if top lstack = 0 at " instruction (see above), redirect
  0            set lstack top to zero (irrelevant instruction)
  <            redirect to the left
 @             flip top and 3rd lstack values
{              output top lstack value as integer (bitcount)

```

Clone my GitHub repository containing the beeswax interpreter, language spec and examples.

# Answer
> 2 votes
# 05AB1E, 3 bytes

```
bSO

```

Try it online!

# Answer
> 2 votes
# Factor, 9 bytes

```
bit-count

```

Try it online!

# Answer
> 2 votes
# Python 3.10+, 13 bytes

```
int.bit_count
```

Attempt This Online!

# Answer
> 2 votes
# K (ngn/k), ~~10~~ 7 bytes

```
{+/2\x}

```

Try it online!

*Thanks @coltim for -3 bytes by suggesting me that I can just take the sum instead of the count of `1`s*

Cast the integer into base 2, then sum.

# Answer
> 2 votes
# BitCycle, 5 bytes

```
?+
 !

```

Online Interpreter

Kind of cheaty, as it inputs in binary and outputs in unary. These are the only two I/O formats this language really can handle, but it's also pretty trivial.

---

Explanation:

`?` Take input

`+` Send all 0 bits up (deleting them) and all 1 bits down.

`!` Output all bits that arrive here.

# Answer
> 1 votes
# Java, 17 bytes

Works for `byte`, `short`, `char`, and `int`. Use as a lambda.

```
Integer::bitCount

```

Test here

Without using built-ins:

**42 bytes**

```
s->{int c=0;for(;s!=0;c++)s&=s-1;return c}

```

Test here

# Answer
> 1 votes
# Clip, 6

2 ways:

```
cb2nx1

```

This is a straightforward translation of the requirement: the count of ones in the base-2 representation of number.

```
r+`b2n

```

Another method, which takes the sum of the digits of the base-2 representation.

# Answer
> 1 votes
# Octave, 18

```
sum(dec2bin(s)-48)

```

Example:

```
octave:1> s=1337
s =  1337
octave:2> sum(dec2bin(s)-48)
ans =  6

```

# Answer
> 1 votes
# GML (Game Maker Language), 21 bytes

```
for(n=0;x;n/=2)n+=x&1

```

# Answer
> 1 votes
## C# 38 bytes

```
Convert.ToString(X,2).Count(C=>C==49);

```

# Answer
> 1 votes
# Clojure, 42 bytes

```
#(count(filter #{\1}(Long/toString % 2)))

```

Reading right to left, convert to a binary string, convert to a sequence of characters, filter on `1`s and count how many you have.

**EDITED** With help from Sieg

# Answer
> 1 votes
# Perl, 21

```
$r=grep$v&1<<$_,0..15

```

# Answer
> 1 votes
# PowerShell (51 bytes)

```
"$([char[]][convert]::ToString($s,2)|%{"+$_"})"|iex

```

---

Explanation:
`[convert]::ToString($s,2)` produces a binary string representation from `$s`.
`[char[]]` casts it as a char array and allows us to enumerate each char.
`|%{"+$_"}` prepends each character with a + sign
`"$()"` implicitly calls `.ToString()` on the resulting sub expression
`|iex` sums the piped string (ie. "+1 +0 +1 +1 +0 +1 +0 +0" = 4)

# Answer
> 1 votes
# Haskell 42 chars

```
t 0=[]
t n=t(quot n 2)++[rem n 2]
f=sum.t

```

declares the function `f :: Integer -> Integer`
use from the interactive interpreter as `f <number>` or add the line `main=print$f <number>` to the end of the file.

# Answer
> 1 votes
# Matlab, 13 bytes

`de2bi` creates a vector of zeros and ones representing the binary number, and `sum` just returns the sum of all the entries.

```
sum(de2bi(n))

```

# Answer
> 1 votes
# , 4 chars / 11 bytes (non-competitive)

```
⨭⟦ïⓑ

```

`Try it here (Firefox only).`

# Explanation

Converts input to binary, splits along chars, and gets sum of resulting array.

# Answer
> 1 votes
# Pyt, 1 byte

Hooray for built-ins.

```
Ħ

```

Try it online!

Non-built-in:

# Pyt, 3 bytes

```
ɓƖŚ

```

Try it online!

Explanation:

```
      Implicit input
ɓ     Convert to binary string
Ɩ     Cast as integer
Ś     Sum of digits
      Implicit output

```

# Answer
> 1 votes
# Brachylog, 2 bytes

```
ḃ+

```

Try it online!

Just about exactly the Jelly answer.

# Answer
> 1 votes
# \>\<\>, 18 bytes

```
0$:2%:{+}-2,:@?!n!

```

Try it online!

# Answer
> 1 votes
# MathGolf, 2 bytes

```
âΣ

```

Try it online!

## Explanation

```
â    convert to binary
 Σ   sum(list), digit sum(int)

```

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

```
+/2\

```

Try it online!

Convert to base 2, sum up.

# Answer
> 1 votes
# JavaScript, 19 bytes

```
f=n=>n&&n%2+f(n>>1)

```

Try it online!

Nice and simple

# Answer
> 1 votes
# Desmos, ~~40~~ 38 bytes

```
f(x)=floor(mod(x/2^{[0...x]},2)).total

```

Try it on Desmos!

*-2 bytes thanks to emanresu A*

# Answer
> 1 votes
# Zsh, 27 bytes

```
a=${$(([##2]$1))//0};<<<$#a

```

Try it online! ~~30b~~ ~~35b~~

* `$(([##2]$1))` convert input `$1` to binary
* `${ ... //0}` remove `0`s
* `<<<$#a` print length of string `$a`

# Answer
> 0 votes
# K5, 9 bytes

```
+/(16#2)\

```

I used k5's "unpack" overload for `\` to split the number into base 2 digits. You can try it online here using oK.

# Answer
> 0 votes
# Go, 24

This is an adaptation of the C solution by @steveverrill

```
n:=0;for;x>0;n++{x&=x-1}

```

We need to explicitly declare `n` outside the loop to keep it in scope.

Go requires curly braces as well, and the check in the `for` loop must be a boolean expression.

http://play.golang.org/p/Z\_iuGL5nZ5

# Answer
> 0 votes
# WDC 65816, 8 bytes

Assuming 8-bit XY (`P.x = 1`), the following 8 bytes of object code produce the popcnt of A in X within 145 cycles:

```
A2 00 4A 90 01 E8 D0 FA

```

This works on a 65816 whether A is 8-bit (`P.m = 1`) or 16-bit (`P.m = 0`), and it has also been tested in a virtual 6502 with 8-bit values. With 16-bit XY on a 65816 (`P.x = 0`), one more byte is needed: replace `A2 00` with `A2 00 00`.

Assembly source:

```
  ldx #0       ; A2 00, or A2 00 00 in 16-bit XY mode
loop:
  lsr a        ; 4A    Copy bit 0 of A to carry and shift A right by 1
  bcc zerobit  ; 90 01 If carry is 1, add 1 to X
  inx          ; E8
zerobit:
  bne loop     ; D0 FA If the last ALU result was nonzero, keep counting

```

The `bne` instruction branches on the zero flag, which changes whenever an instruction writes to register A, X, or Y. For a 1 bit, `inx` is the last instruction to write to A, X, or Y, and X is nonzero if there are 1 to 255 bits (only 16 are possible!), so the loop continues. For a 0 bit, `lsr a` is the last instruction to write to A, X, or Y, and A is nonzero only if there are more bits to count.

# Answer
> 0 votes
perl (35 characters)

```
$b=sprintf("%b",$d);$c=()=$b=~/1/g;

```

# Answer
> 0 votes
# Clip, 22 chars (25 for full program, or 27 for working with zero)

```
[Fy?!%lyWOO])Fmy#WilyW

```

Prefix this with `F<some value>` to get the answer for that value. Or, for a full program to read from stdin, prefix the code with `Fnx`. In a previous answer, I golfed a way in Clip to check if something's a power of two. I always return one in that case. Otherwise, increment the result of applying this function (recursively) to `2^(floor(log2(<function parameter>)))`.

To make this work with zero (returning 0), use (28 chars):

```
[Fy?!yZ]?!%lyWOO])Fmy#WilyW

```

# Answer
> 0 votes
# Bash, 63 51 47 bytes

```
[ $1 = 0 ]&&echo 0||echo $[$1%2+`$0 $[$1/2]`]

```

The shorter the code, the clearer the meaning :).

---

### 51:

```
[ $1 -ne 0 ]&&echo $[($1&1)+$($0 $[$1/2])]||echo 0

```

Recursive script instead of script with recursing function.

---

The "`negative-cond || instruction`" idiom instead of boring "`if cond; then instruction; fi` " is our friend here.

Note that echo should return 0 (true), so `**[ $1 -ne 0 ]** && echo $[$[$1&1]+$(n $[$1/2])]`

has the logical value of `[ $1 -ne 0 ]` alone.

# Answer
> 0 votes
# Perl 6: 17

The first thing that comes to mind is

```
[+] 1337.base(2).comb; # returns 6

```

---

Although this doesn't have any arbitrary limits ( the only limits are how much memory you have, and how long you are willing to wait )

```
[+] ( uint64.Range.max * 2 + 1 ).base(2).comb; # returns 65

# 340282366920938463463374607431768211455
my $uint128-max = :2( 1 x 128 );
[+] $uint128-max.base(2).comb; # returns 128

my $uint8192-max = :2( 1 x 8192 ); # 2467 digit Int
[+] $uint8192-max.base(2).comb; # returns 8192 (takes about a second currently)

```

Without making it into a Callable the shortest way to write this is to put the Int into the *"default"* variable `$_`. ( `.method` is always short for `$_.method` )

```
$_ = 1337;
[+] .base(2).comb;

```

```
given 1337 { # Perl6's with/switch statement
  [+] .base(2).comb
}

```

```
[+] .base(2).comb given 1337; # ditto

```

```
if 1337 -> $_ { # pointy block
  [+] .base(2).comb
}

```

If you want to create a Callable you could just put it into a Block.

```
my $code-ref = {[+] .base(2).comb};
# if it is called with an argument it places it in $_
# if called without an argument uses the $_ from an outer scope

```

If you really want to call it as a normal subroutine:

```
my &f={[+] .base(2).comb}; # sub f($_){[+] .base(2).comb}

say f 1337; # 6

$_ = 1337;
say f; # 6

```

---

Based on your requirements I'd guess that the answer you are looking for is:

```
[+] .base(2).comb

```

This assumes that the value is already in `$_`. It would most likely be the last statement in a subroutine, the right side of an assignment, or an argument to a subroutine or method. ( Otherwise it calculates the result only to throw it away, unless the compiler notices that the result is unused )

---

In case you were wondering `[+] 1, 2, 3` can be considered short for `(1,2,3).reduce(&[+])`.
Where `&[+]` is short for `&infix:< + >` the collection of multi subs available in the current scope that are responsible for the numerical infix addition operator `+`.

# Answer
> 0 votes
## ActionScript 3, 17 bytes

```
for(;x;n++)x&=x-1

```

This is a copy of steveverrill answer, how ever by using AS3, I don't have to put `;` at the end of the line, so I save 1 byte.

Also I assume that `x` and `n` been initialize already.

# Answer
> 0 votes
# , 7 bytes

```
H2b~]+o
```

Explanation:

```
H        Push input into array
  2b~    Push all the bits of the binary form to the array
     ]+o Add them all up and output the array

```

# Answer
> 0 votes
# TeaScript, 9 bytes (non-competitive)

```
x÷f»l¦1)n

```

Try it here.

# Answer
> 0 votes
## Seriously, 6 bytes (non-competitive)

This one is fun and neat, and given the number of non-competitive entries it has attracted, I might as well add a Seriously answer.

```
'12,¡c

```

Try it online

Explanation:

```
'12,¡c
   ,     get input
  2 ¡    convert to binary string
'1   c   count the occurrences of "1"
         (implicit print at EOF)

```

# Answer
> 0 votes
# Candy, 15 bytes

I would have thought this would do a bit better, but the lack of an operator to convert numbers to a base 2 string seems to have hurt it. Maybe in a future version of Candy to pull an int from the stack and push 1's and 0's. That would make this one kind of boring, just `XS?`.

```
(~A2%h2/LD{)|=Z

```

The long form is:

```
while   # stack not empty
  peekA
  pushA
  digit2
  mod       # get low bit
  popAddZ   # Z = Z + low bit
  digit2
  div
  floor     # integer div 2
  dupl
  if        # if the top of stack is non-zero
endwhile    # NOTE that the endwhile is in an if-then clause
  else
    popA
    pushZ   # NOTE the lack of an endif.
            #  braces and parens are calculated as the
            #  program counter advances over them

```

# Answer
> 0 votes
**C# 45**

```
int o=Convert.ToString(n,2).Count(x=>x=='1');

```

where **o** holds the amount of ones and where **n** is the number.

Alternative and faster **C# 6.0 88 bytes**

```
int o=b(n,16).Count(x=>x=='1');
static string b(int v,int l)=>(l>1?b(v>>1,l-1):null)+"01"[v&1];

```

where the **o** holds the number of ones and where the **n** is the number.

# Answer
> 0 votes
# Javascript ES6, 35 bytes

```
a=>a.toString(2).match(/1/g).length

```

# Answer
> 0 votes
**x86 cpu instructions, 30 bytes**

```
56 89 E6 8B 44 04 3D 00 00 74 0F D1 E8 50 E8 EF FF 8B 4C 04 81 E1 01 00 01 C8 5E C2 02 00

```

meaning and disassembly:

```
; input in the stack sp+4
; output in ax
;0i,2Ka,4P
f:
push  si
mov   si,  sp
mov   ax,  [si+4]
cmp   ax,  0
je   .z
shr   ax,  1
push  ax
call  f
mov   cx,  [si+4]
and   cx,  1
add   ax,  cx
.z:
pop   si
ret 2

0000000F  56                push si
00000010  89E6              mov si,sp
00000012  8B4404            mov ax,[si+0x4]
00000015  3D0000            cmp ax,0x0
00000018  740F              jz 0x29
0000001A  D1E8              shr ax,1
0000001C  50                push ax
0000001D  E8EFFF            call 0xf
00000020  8B4C04            mov cx,[si+0x4]
00000023  81E10100          and cx,0x1
00000027  01C8              add ax,cx
00000029  5E                pop si
0000002A  C20200            ret 0x2
//30

```

# Answer
> 0 votes
# RProgN, 8 Bytes

```
2 B S ++

```

# Explination

```
2 B     # Convert to base 2
S       # Convert from string to a stack of individual characters
++      # Sum the stack.

```

Simple enough, Could be made cheaper if the sugar for sum was single character, instead of double, as `►2BS<SUM>` could then be used, saving a byte.

# Test Cases

```
1337:       6.0
16:         1.0
255:        8.0
1236172031: 21.0

```

# Answer
> 0 votes
## 16/32-bit x86 assembly, 9 bytes

(based on es1024's answer)

```
31 C0 D1 E9 10 E0 41 E2 F9
```

which is equivalent to:

```
xor ax, ax        ; 31 C0   Set ax to 0
shr cx, 1         ; D1 E9   Shift cx to the right by 1 (cx >> 1)
adc al, ah        ; 10 E0   al += (ah = 0) + (cf = rightmost bit before shifting)
inc cx            ; 41      Increment cx to offset following decrement
loop $-5          ; 75 F9   Jump up to shr cx, 1 if cx-1 is not zero
```

cx is the 16-bit integer to profile, result is returned in ax.

# Answer
> 0 votes
# Pip, 5 bytes

(The language postdates the question, barely.)

```
1NTBa

```

Try it online!

With the knowledge that `a` represents the first command-line argument, this program can be understood quite straightforwardly: `1 iN To-Binary(a)`. That is, convert `a` to binary and count the number of `1`s.

# Answer
> 0 votes
# Stax, 4 bytes

```
:B|+

```

Run and debug online!

## Explanation

```
:B|+
:B      Binary digits
  |+    Sum

```

# Answer
> 0 votes
# Japt `-x`, ~~3~~ 2 bytes

```
ì2

```

Try it here

# Answer
> 0 votes
# dc, 25 bytes

```
[2~rd0<B]dsBx[+z1<S]dsSxp

```

Try it online!

Two macros. `[2~rd0<B]dsBx` breaks a decimal value down into binary components by repeatedly dividing by two (using `~` to leave both quotient and remainder on stack) until left with a quotient of zero. After our stack is filled with ones and zeros, `[+z1<S]dsSx` sums it up by adding the top two values until there's only one value left. `p` prints our final answer.

# Answer
> 0 votes
# Add++, 8 bytes

```
L,BBBDBs

```

Try it online!

Surprisingly short for Add++

## How it works

```
L,      ; Define a lambda function
        ; Example argument: 1337
    BB  ; Binary;  STACK = [10100111001]
    BD  ; Digits;  STACK = [[1 0 1 0 0 1 1 1 0 0 1]]
    Bs  ; Sum;     STACK = [6]

```

# Answer
> 0 votes
# Kotlin, 30 bytes

```
{it.toString(2).sumBy{it-'0'}}

```

Try it online!

# Answer
> 0 votes
# cQuents, 6 bytes

```
uJ$);1

```

Try it online!

## Explanation

```
:uJ$);1
:            implicit :
              mode: sequence 1 - given input n, output nth term in sequence
             each term in the sequence is

 u   ;1      count(                , 1)
  J )              toBase(     , 2)
   $                      index

```

# Answer
> 0 votes
# PARI/GP, 13 bytes

```
hammingweight
```

Attempt This Online!

PARI/GP has a built-in for this.

---

# PARI/GP, 17 bytes

```
n->sumdigits(n,2)
```

Attempt This Online!

Another built-in, with a more obvious name.

---

# PARI/GP, 21 bytes

```
f(n)=if(n,n%2+f(n\2))
```

Attempt This Online!

Without built-in.

# Answer
> 0 votes
# Perl 6, 18 bytes

```
*.base(2).comb.sum

```

Works with any nonnegative integer, in fact.

Try it online!

# Answer
> 0 votes
# 8051 Machine Code, 13 bytes

```
7B 10 E8 13 50 01 0A BB 08 01 E9 DB F6

```

Takes the integer in R1 (highest 8 bits) and R0 (lowest 8 bits). Returns the result in R2

```
    MOV R3, #10        ; 7B 10     - Store 16 since we process a 16 bit number
    MOV A, R0          ; E8        - Move the first register to check to A

LAB1:
    RRC A              ; 13        - Rotate A through the carry to extract the nth bit
    JNC LAB2           ; 50 01     - If the current bit is set (Carry = 1)
    INC R2             ; 0A        - Increment the result

LAB2:
    CJNE R3, #08, LAB3 ; BB 08 01  - If we are done with the first 8 bits
    MOV A, R1          ; E9        - Move R1 into the accumulator

LAB3:
    DJNZ R3, LAB1      ; DB F6     - Jump back to LOOP if we have done less than 16 iterations
END

```

# Answer
> 0 votes
# SMALL, 28 bytes

```
0->n{x?[x%2=1?n+1->n]x/2->x}

```

Takes input in variable `x` and the output will be in variable `n`.

```
{
  x?

  [
    x % 2 = 1?
    n + 1 -> n
  ]

  x / 2 -> x
}

```

Repeatedly divides `x` by two until the number is zero, which means every 1 bit will be moved into its rightmost bit at some point. We then perform a check each loop to see if this bit is a 1 and if so, increment `n`.

# Answer
> 0 votes
# Thunno 2 `S`, 2 bytes

```
2B

```

Attempt This Online!

Convert to a binary list. `S` flag takes the sum.

### Thunno 2, 3 bytes

```
ḃ1c

```

Attempt This Online!

Convert to binary and count the 1s.

# Answer
> -1 votes
## LUA 55 bytes

```
while(i>0)do if(v-i)>=0 then c=c+1;v=v-i;end i=i/2 end

```

> **v** is the value
>
> **i** is the max value of an (x)bit Integer, 65535 in this example.
>
> **c** counts one up, if there's a remainder from (i-l), which means that a one is found.

This is more a simple algorithm than a single statement.

---
Tags: code-golf, binary, counting
---


# Question
Title: Output the alphabet, the ALPHABET, or just a character
The challenge is simple:

Write a function or program that takes an input `x`, and outputs the lower case alphabet if `x` is part of the lower case alphabet, outputs the upper case alphabet if `x` is part of the upper case alphabet and outputs just `x` if it's not part of either.

Rules:

* The input can be function argument or from STDIN
* The input will be any of the printable ASCII characters from 32 to 126 (space to tilde).
* The input may be inside quotation marks,`'x'` or `"x"`, but remember that `'` and `"` are valid input and should be supported.
* The input can be any of the letters in the alphabet, i.e. you can't assume it will be `a` or `A`.
* The output should be only one of the alphabets or the single symbol, but trailing newlines are OK.
* The letters in the alphabet should not be separated by spaces, commas or anything else.

Some examples:

```
F
ABCDEFGHIJKLMNOPQRSTUVWXYZ

z
abcdefghijklmnopqrstuvwxyz

"
"

    <- Input:  Space
    <- Output: Space

```

Shortest code in bytes win.

---

Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others.

---

## Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

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

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

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

# Answer
# TeaScript, 5 bytes

```
xN(0)

```

TeaScript has a (almost) built-in for this :D

Try it online (note: the online interpreter has been updated to TeaScript v3 so in which this is `N0`)

Try all the test cases

---

### TeaScript 3, 2 bytes \[non-competing\]

Using TeaScript 3, this can become 2-bytes. This is non-competing because TeaScript 3 was made after this challenge

```
N0

```

---

### 1 byte alternative

If we could output `0123456789` for digits, then this could be:

```
°

```
> 23 votes

# Answer
# Pyth, 10 bytes

```
h/#z[GrG1z

```

Test suite

We start by constructing a list with 3 elements: the lowercase alphabet, the uppercase alphabet, and the input. (`[GrG1z`) Then, we filter this list on the number of appearances of the input in the elements being nonzero. (`/#z`) Finally, we take the first element of the filtered list.
> 27 votes

# Answer
# LabVIEW, 23 LabVIEW Primitives

The selector (the ? on the cse structure) is connected to a vi that is called Lexical Class. It ouputs numbers from 1-6 depending on input, 5 is lower case 4 is upper case.

The for loop goes 26 times to create an alphabet or once to pass the symbol through.
> 15 votes

# Answer
## Haskell, 48 bytes

```
f c=filter(elem c)[['a'..'z'],['A'..'Z'],[c]]!!0

```

Usage example:

```
*Main> f 'g'
"abcdefghijklmnopqrstuvwxyz"
*Main> f 'H'
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
*Main> f '\''
"'"

```

Take all lists of \['a'..'z'\], \['A'..'Z'\] and the singleton list with the input char `c` where `c` is element of. For letters we have always two matches, so we pick the first one.
> 12 votes

# Answer
# JavaScript (ES6), 79 bytes

```
x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)

```

## Explanation

JavaScript compares the code of each character alphabetically when comparing strings, so the codes of the characters used in the comparisons are 1 below and above the required range of characters.

```
x=>(
  a="abcdefghijklmnopqrstuvwxyz", // a = lower-case alphabet
  x>"`"&x<"{"?a:                  // if x is a lower-case letter, output alphabet
  x>"@"&x<"["?a.toUpperCase():    // if x is an upper-case letter, output upper-case
  x                               // else just output x
)

```

## Test

```
var solution = x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)
```

```
X = <input type="text" oninput="result.textContent=solution(this.value)" />
<pre id="result"></pre>
```
> 11 votes

# Answer
## R, ~~90~~ 75 bytes

```
a=scan(,'');l=letters;L=LETTERS;cat("if"(a%in%l,l,"if"(a%in%L,L,a)),sep="")

```

Thanks to Giuseppe.

Old version (90 bytes):

```
a=scan(,'');l=letters;L=LETTERS;if(a%in%l)cat(l,sep="")else if(a%in%L)cat(L,sep="")else a

```

Looks ugly, but those `cat`s cannot be outsourced to functions, IMHO.
> 9 votes

# Answer
# Python 3, ~~92~~ ~~84~~ ~~82~~ 74 bytes

Current version: 74, thanks to isaacg and wnnmaw!

```
lambda c:(c,''.join(chr(x+(67,97)[c>'Z'])for x in range(25)))[c.isalpha()]

```

Ungolfed: (for some definition of ungolfed)

```
lambda c:
    (
        c,
        ''.join([chr(x + (67,97)[c > 'Z']) for x in range(25)])
    )
    [c.isalpha()]

```

---

First version: 92

```
def f(c):print(''.join([chr(x+(97if c>'Z'else 65)) for x in range(25)])if c.isalpha()else c)

```

Second version: 82, thanks to isaacg! :)

```
lambda c:''.join(chr(x+(97if c>'Z'else 65))for x in range(25))if c.isalpha()else c

```
> 8 votes

# Answer
# Python 3, ~~118~~ ~~105~~ ~~98~~ ~~97~~ 83 bytes

Simple solution. **EDIT:** Golfed with thanks to Erik the Golfer's suggestion.

```
lambda s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ':(s,(a,a.lower())[s.islower()])[s.isalpha()]

```

Ungolfed:

```
def f(s):
 a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 if s.isalpha():
  if s.islower():return a.lower()
  else:return a
 return s

```
> 6 votes

# Answer
# PHP, 62 ~~76~~ ~~82~~ bytes

PHP is doing OK now:

```
<?=ctype_alpha($x=$argv[1])?join(range(Z<$x?a:A,Z<$x?z:Z)):$x;

```

Takes an input from command line, like:

```
$ php alphabet.php A
$ php alphabet.php "a"
$ php alphabet.php " "
$ php alphabet.php _

```

**Edits**

* *Saved* **6 bytes** by replacing `91>ord($x)` with `Z<$x`. Thought way to complicated. Thanks to manatwork.
* *Saved* **14 bytes** by removing `strtoupper` and building the demanded range directly.
> 5 votes

# Answer
# Perl, ~~46~~ ~~34~~ 33 bytes

*includes +2 for `-nE`*

```
say/[a-z]/?a..z:/[A-Z]/?A..Z:$_

```

Run as

```
perl -nE 'say/[a-z]/?a..z:/[A-Z]/?A..Z:$_'

```

---

* *update 34* save 12 bytes by omitting `for` and using barewords, thanks to @Dom Hastings.
* *update 33* save 1 byte using `-E` and `say` instead of `print`.
> 5 votes

# Answer
# Ruby, 41 + 1 = 42

With switch `-p`, run

```
([*?A..?z]*'').scan(/\w+/){$&[$_]&&$_=$&}

```

This generates the string

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz

```

and checks each contiguous block of "word characters", which happen to be just the lowercase and uppercase alphabets and the underscore character. If there were multiple consecutive word characters between Z and a, this trick wouldn't work.

**Edited to add explanation, by request:**

The `-p` flag does essentially

```
while( $_ = STDIN.gets )
  #execute code
  print $_
end

```

`[*?A..?z]` is the array of characters between uppercase A and lowercase Z, in ASCII order. That's the uppercase alphabet, some non-letter characters, and the lowercase alphabet. `*''` joins the array into a string, so we can call `.scan` on it. `scan` will find each match of the regular expression `/\w+/`, populate the magic variable `$&` with it, and call the block. Each time the block is iterated, it checks whether the matched string contains `$_` and sets the output to that string if so. So if $\_ is contained in either the uppercase or lowercase alphabet, it gets modified accordingly, otherwise it's unchanged.

The ungolfed version would look something like

```
while ($_ = STDIN.gets )
 %w[ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz].each do |alphabet|
  $_ = alphabet if alphabet.include?($_)
 end
 print $_
end

```
> 5 votes

# Answer
# Ruby, ~~46~~ 43 characters

(42 characters code + 1 character command line option)

```
[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}

```

Thanks to:

* Jordan for the `===` magic (-3 characters)

Sample run:

```
bash-4.3$ echo -n 'm' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ echo -n 'W' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ echo -n '@' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
@

```
> 4 votes

# Answer
# CJam, 18 bytes

```
'[,65>_elr:R]{R&}=

```

`'[,65>` pushes the uppercase alphabet, `_el` the lowercase alphabet, and `r:R` a single-char string that is read from STDIN and assigned to variable `R`. These are wrapped in an array (`]`) and the first one that has any chars in common with `R` is selected using `{R&}=`.
> 4 votes

# Answer
# Retina, 62 bytes

```
[a-z]
abcdefghijklmnopqrstuvwxyz
[A-Z]
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

The two short lines are the regex to match. If the input is lowercase (in the range `[a-z]`), it replaces that character (in this case, that is the entire input) with the lowercase alphabet. The process is similar for uppercase. If it's not a letter, no replacements are made, and it is outputted untouched.

Try it online.
> 4 votes

# Answer
#MATL, 22 bytes

```
jtt1Y2XIm~Iw?km?Ik]]1$

```

This uses the current version (3.1.0) of the language.

*EDIT (Sep 15, 2017): Try it at MATL Online! (with a newer version of the language).*

###Examples

```
>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> e
abcdefghijklmnopqrstuvwxyz

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> T
ABCDEFGHIJKLMNOPQRSTUVWXYZ

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> "
"

```

###Explanation

```
j              % input string (assumed to be a single character)
tt             % duplicate twice
1Y2            % predefined literal: uppercase letters
XI             % copy to clipboard I
m~             % check if not member
I              % paste from clipboard I
w              % swap elements in stack
?              % if
    k          % convert string to lowercase
    m          % check if member
    ?          % if
        I      % paste from clipboard I
        k      % convert string to lowercase
    ]          % end
]              % end
1$             % input specification for implicit printing

```
> 4 votes

# Answer
## Python 2.7.10, ~~95~~ ~~93~~ 79 bytes

This is my first time even attempting to golf, so please, any help or advice is extremely appreciated!

```
from string import*
lambda i:(i,(uppercase,lowercase)[i.islower()])[i.isalpha()]

```

Thanks to Morgan Thrapp for the help!
> 4 votes

# Answer
# Lua, ~~98~~ 97 bytes

Sadly, I didn't find a solution shorter than 26 bytes to set `a` with the alphabet. In fact, I didn't find shorter than 32.

**Edit : save 1 Byte thanks to @ATaco, was doing this error a lot when started with Lua :p**

```
c=io.read()a="abcdefghijklmnopqrstuvwyz"print(not c:find"%a"and c or c:find"%u"and a:upper()or a)

```

You can test it online on the official site or on ideone. If you use the former, the input won't work (disabled), so use the following source, where it is wrapped into a function.

```
function f(c)
  a="abcdefghijklmnopqrstuvwyz"
  print(not c:find"%a"and c or c:find"%u"and a:upper()or a)
end

print(f("\""))
print(f("a"))
print(f("Q"))

```
> 3 votes

# Answer
## Perl, 23 bytes

Includes +2 for `-nE` (instead of the normal +1) to be fair to the other perl solution

Run with the input on STDIN without trailing newline:

```
echo -n g | perl -lnE 'say/\pL/?a&$_|A..Z:$_'

```

Just the code:

```
say/\pL/?a&$_|A..Z:$_

```
> 3 votes

# Answer
# Japt, 9 bytes

```
;[CBU]æøU

```

Run it online
> 3 votes

# Answer
# C (gcc), 91 bytes

A function that accepts a `char` and prints the result via stdout (91 bytes):

```
f(x){puts(isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x);}

```

Try it online!

Bonus (a shorter version of `MD XF`'s answer, since I don't have enough reputation to comment (90 bytes):)

```
#define f(x)isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x

```

Try it online!
> 3 votes

# Answer
# SpecBAS, 111 bytes

I've been through several versions of this, 111 seems to be the best I can manage.

```
1 INPUT l$: a$="abcdefghijklmnopqrstuvwxyz"
2  ?IIF$(l$ IN ["a" TO "z","A" TO "Z"],IIF$(l$=UP$ l$,UP$ a$,a$),l$)

```

Line 2 uses the `?` shortcut for `PRINT` and nested inline `IF` statements

Pseudo code explanation

```
IF character IN "a".."z","A".."Z"
THEN
 IF character = UPPERCASE character
 THEN
  print UPPERCASE alphabet
 ELSE
  print alphabet
 ENDIF
ELSE
 print the character
ENDIF

```
> 2 votes

# Answer
## Mathematica, 75 bytes

```
#/.Thread[Join[a=Alphabet[],b=ToUpperCase@a]->Array[""<>If[#>26,b,a]&,52]]&

```

Pretty good score for a non-golfing language... Any solutions using character code processing would take more bytes, due to the costs of `ToCharacterCode` and `FromCharacterCode`.
> 2 votes

# Answer
# Python, 81 bytes

```
f=lambda z,a="abcdefghijklmnopqrstuvwxyz":[k for k in[a,a.upper(),z]if z in k][0]

```

This is basically a translation of the Pyth answer. It defines a function `f` that takes as argument the character and returns the result.
> 2 votes

# Answer
## MATLAB: ~~71~~ 68 bytes

```
i=input('');b=i<65|i>122|(i>90&i<97);[i*b,~b*((65:90)+32*(i>96)),'']

```

(thanks to OP for saving 3 bytes)

Test:

```
i='a'
ans=
abcdefghijklmnopqrstuvwxyz

i='A'
ans=
ABCDEFGHIJKLMNOPQRSTUVWXYZ

i='~'
ans=
~

```

Explanation: Uppercase alphabet occupies `65:90` ASCII characters. Lowercase alphabet is at `97:122` ASCII. So, `b=i<65|i>122|(i>90&i<97)` checks whether the input character `i` is NOT alphabetic. If so, input is returned. The uppercase alphabet is returned if `b==1` and `i<97` (uppercase character). If `b==1` and `i>96`, 32 is added to `65:90` that corresponds to `97:122` \- the lowercase alphabet.
> 2 votes

# Answer
# Swift 2, 142 Bytes

```
func d(s:String)->String{let a="abcdefghijklmnopqrstuvwxyz";for v in s.utf8{return v>64&&v<91 ?a.uppercaseString:(v>96&&v<123 ?a:s)};return s}

```

### Ungolfed

```
func d(s: String) -> String{
    let a="abcdefghijklmnopqrstuvwxyz"
    for v in s.utf8{
        return (
            v > 64 && v < 91 ?
            a.uppercaseString :
            (
                v > 96 && v < 123 ?
                a :
                s
            )
        )
     }
    return s
}

```
> 2 votes

# Answer
# C (function), 71 bytes

```
f(s,n,c){n=1;if(isalpha(s))s-=s%32-1,n=26;for(c=s;c<s+n;)putchar(c++);}

```
> 2 votes

# Answer
# Jolf, 17 bytes

Try it here.

```
? hpLipl? hpUipui
?                  if
  hpL               the lowercase alphabet (array) contains
     i               the input
      pl            return the lowercase alphabet (string)
        ?          else if
          hpU       the uppercase alphabet (array) contains
             i       the input
              pu    return the uppercase alphabet (string)
                i  otherwise, return the input
                   implicit: print the result

```
> 2 votes

# Answer
## Java, 165 characters

```
class A {public static void main(String[]p){int c=p[0].charAt(0),d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);for(;e<f;e++){System.out.print((char)e);}}}

```

Generates the required output to stdout (rather than returning it). Input is via the runtime arguments.

How it works.

1) Setup some integer variables
c = the ASCII value of the first character of the first parameter of the runtime arguments.
d = c converted to lowercase ASCII value (by ORing it with 32)
b = calculation to see if d is a letter. Will be \<0 if a letter.
e = The start character for output. If ASCII value in d is a letter (see b) then it is set to 'A' (or 'a' by adding c AND 32 to 'A' ASCII value) else it is set to the original value of c.
f = the number of characters to output. If it not a letter (see b) then this is set to 1 else it is set to 26
2) Loop from e to e+f outputing each character to stdout.
> 2 votes

# Answer
# 05AB1E, ~~19~~ 16 bytes

-3 bytes thanks to `else`

```
DAsåiAëDAusåiAuë

```

How it works

```
                   # implicit input
D                  # duplicate
 A                 # push lowercase alphabet
  s                # swap last two elements
   å               # push a in b
    i              # if
     A             # lowercase alphabet
      ë            # else
         D         # duplicate
          Au       # uppercase alphabet
            s      # swap last two elements
             å     # push a in b
              I    # if
               Au  # uppercase alphabet
                 ë # else leave input
                   # implicit print

```

Try it online!
> 2 votes

# Answer
## Java SE 8, ~~71~~ 69 bytes

Golfed:

```
(a,s)->{char b=97;if(a<91)b-=32;a=b;b+=26;while(a<b)s+=a++;return s;}

```

Ungolfed:

```
(a,s)->{          // String as a parameter. If declaration is necessary it adds 8 bytes
char b = 97;      // Uppercase A char, this is important
if (a < 91)       // If it is not past 'z', where a is a char param
    b -= 32;      // Then go back to the lowercase alphabet
a = b;            // Done to prevent a cast
b += 26;          // End of alphabet
while (a < b)     // Go to end of alphabet
    s += a++;     // Append character
return s;}        // Then return

```

I had originally implemented the following

```
String s="";char b=96;if(a-91<0)b-=32;for(char c=b;++c<b+27;)s+=c;return s;

```

It's more elegant but sadly it's one byte larger. This is assuming that behavior for non alpha characters is undefined and string s is initialized to "" prior to execution. Be gentle it's my first post.

edit: 2 bytes saved by Stewie Griffin by changing

```
a - 91 < 0 to a < 91

```
> 2 votes

# Answer
# Scala, 91 characters

```
(c:Char)=>{var a='a'.to('z').mkString;if(c.isUpper)a=a.toUpperCase;if(!c.isLetter)a=""+c;a}

```

## Un-golfed

```
def f(c: Char): String = {
    var a='a'.to('z').mkString //set up lower case default response
    if (c.isUpper) {
        a = a.toUpperCase     //mutate the result if upper case
    }
    if (!c.isLetter) {
      a = ""+c                 //mutate the result if not a letter
    }
    a                         //return result
}

```

Having a initial mutable result rather than returning an immutable value from 3 distinct if else blocks saved me 2 chars, even though I hate it.

## Scala-thonic method

A better method for scala would be something like this:

```
def convertToAlphabet(c: Char): String = {
    c match {
      case x if !x.isLetter => x.toString
      case x if x.isUpper => ('A' to 'Z').mkString
      case _ => ('a' to 'z').mkString
    }
}

```
> 2 votes

# Answer
# Brachylog, 8 bytes

```
∈Ạ|ḷ∈Ạụ|

```

Try it online!

```
∈Ạ          The input is a member of the lowercase alphabet,
  |         which is output, or
   ḷ∈Ạ      the input lowercased is a member of the lowercase alphabet,
      ụ|    which is output uppercased, or the input is output.

```

It'd be two bytes shorter if we had a constant for the uppercase alphabet but we don't :(
> 2 votes

# Answer
# Keg, `-ir` ~~45~~ ~~37~~ 21 bytes

```
:AZ"•[_AZɧ|:az"•[_azɧ

```

Try it online!

*-16 bytes due to using ranges*

## Answer History

### 37 bytes

```
::`>$\~<*[_z(|:;)^|:A1->[_Z(|:;)^|,

```

-8 bytes thanks to A\__

Try it online!
> 2 votes

# Answer
# Pip, 13 bytes

```
aNz?zaNAZ?AZa

```

builtins.

Try it online!
> 2 votes

# Answer
# Vyxal, 9 bytes

```
Ǎ[æ[kA|ka

```

Try it Online!

Explanation:

```
           # Implicit input
Ǎ[         # If input is a letter:
  æ[       #   If input is capitalized:
    kA     #     Push 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      |    #   Else:
       ka  #     Push 'abcdefghijklmnopqrstuvwxyz'
           # Implicit output

```
> 2 votes

# Answer
# Pip, 12 bytes

```
aN_FI[zAZ]|a

```

Try it online!

Razetime's answer is the approach I thought of too, but 13 bytes seemed rather long. So I went looking for other approaches...

```
     [zAZ]    List containing the lowercase alphabet and the uppercase alphabet
   FI         Filter on this function:
aN_            Is the command-line argument in each string?
              If the argument is lowercase, the result is the lowercase alphabet*; if
              it's uppercase, the result is the uppercase alphabet*; and if it's
              neither, the result is an empty list, so...
          |a  Logical OR with the argument: if filter result is [], print arg instead

* As a single-element list, but without flags, that doesn't affect how it is displayed

```
> 2 votes

# Answer
# Python 3.8, ~~108~~ 93 bytes

-15 bytes thanks to Aaron Miller

```
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(a if(x:=input())in a else a.lower()if x.islower()else x)

```
> 2 votes

# Answer
# TI-Basic, 111 bytes

```
Input Str1
"inString(Ans,Str1→u
"ABCDEFGHIJKLMNOPQRSTUVWXYZ
If u
Stop
"abcdefghijklmnopqrstuvwxyz
If u
Stop
Str1

```

Output is stored in `Ans`.
> 2 votes

# Answer
# Gema, 60 characters

```
\A=@set{a;abcdefghijklmnopqrstuvwxyz}
<J>=$a
<K>=@upcase{$a}

```

Sample run:

```
bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'm'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< '@'
@

```
> 1 votes

# Answer
## Python 2, 67 bytes

```
f=lambda c,i=26:c[c.isalpha():]or c*i and f(c,i-1)+chr(i^ord(c)&96)

```

For letter inputs, generates the string of letters recursively. Doing `ord(c)&96` removes the 5 high bits, and the xor'ing the values `i` from 1 to 26 gives the letter char codes. For control flow, we count `i` down, adding new letters to the end, stopping when `i=0`. When the input `c` is not a letter, immediately outputs it and stops.

Thanks to Mauris for 2 bytes.

Previous solution (68):

```
lambda c:[c,str(bytearray(range(ord(c)&96,255)[1:27]))][c.isalpha()]

```
> 1 votes

# Answer
# Sed, 61 characters

(60 characters code + 1 character command line option)

```
s/[a-z]/&abcdefghijklmnopqrstuvwxyz/i
s/[A-Z].*/\U&/
T
s/.//

```

Sample run:

```
bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'm'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< '@'
@

```
> 1 votes

# Answer
# Python 2.7, 88 bytes (incl. print)

```
from string import*
def f(c):print[c,uppercase,c,lowercase,c][sorted('@Z`z'+c).index(c)]

```
> 1 votes

# Answer
## JavaScript (ES6), ~~99~~ ~~87~~ ~~79~~ 78 bytes

```
x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)

```

~~Uses the short array fill trick to allocate space, then just math and `String.fromCharCode` to get the alphabet.~~ Thought it would be shorter until I realized the rule about non-alphabet characters. `parseInt` turned out to be helpful in determining if the character was in the alphabet.

## Test

```
var F=x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)
```

```
x = <input type="text" oninput="result.textContent=this.value?F(this.value):''" />
<pre id="result"></pre>
```
> 1 votes

# Answer
# Mouse-2002, 125 bytes

... or 126 bytes if I can't assume a REPL envrironment (which assumes a `$` at the end of the program; the non-REPL interpreter crashes without one)

An attempt at code deduplication... probably a failed one.

Golfed:

```
?'a:123b:a.65<a.31>*1=a.90>a.97<*1=+a.122>+1=[a.!']a.63>a.91<*1=[65i:(i.91<^i.!'i.1+i:)]a.96>a.b.<*1=[97i:(i.b.<^i.!'i.1+i:)]

```

Ungolfed:

```
?' a:                    ~ a = getchar();
123 b:                   ~ b = 123
a. 65 <                  ~ return whether a < 65
a. 31 >                  ~ same for 31
  * 1 =                    ~ AND
a. 90 >                  ~ a > 90 ?
a. 97 <                  ~ a < 97 ?
  * 1 =                    ~ AND
+                          ~ OR
a.122 >                  ~ a > 122 ?
  + 1 =                    ~ OR
[                          ~ if 1
  a.!'                       ~ print ascii codepoint
]                          ~ fi
a. 63 >                  ~ a > 63 ?
a. 91 <                  ~ a < 91 ?
  * 1 =                    ~ AND
[                          ~ if 1
  65 i:                      ~ for i = 65;
  (                          ~ do;
    i. 91 < ^                  ~ i < 91;
    i.!'                       ~ print(charAt(i));
    i. 1+ i:                   ~ i++;
  )                         ~ done;
]                          ~ fi
a. 96 >                  ~ a > 96 ?
a. b. <                  ~ a < b ?
  * 1 =                    ~ AND
[                          ~ if 1
  97 i:                      ~ for i = 97;
  (                          ~ do;
    i. b. < ^                  ~ i < 91;
    i.!'                       ~ print(charAt(i));
    i. 1+ i:                   ~ i++;
  )                          ~ done;
]                          ~ fi
$                        ~ \bye
```
> 1 votes

# Answer
# Ruby, 56+2 = 58 bytes

2 bytes for `-p` flag

```
c=$_[0]
[?a..?z,?A..?Z].map{|r|r===c&&c=r.to_a.join}
p c

```

Ungolfed version (no `-p` flag)

```
while true
  char = gets.chars.first
  [("a".."z"),("A".."Z")].each do |range|
    char = range.to_a.join("") if range.include? char
  end
  p char
end

```
> 1 votes

# Answer
# s-lang, 40 bytes (non-competing)

Replaces any letter with the alphabet, matching the case.

```
t@[[a-z]][abcdefghijklmnopqrstuvwxyz]

```
* t Replace with regex function
* @ Match case for entire match parameter for t function
* \[\[a-z\]\] first argument (\[a-z\]) regex for matching any letter (@ parameter makes it so this function ignores the case when matching, so we don't need A-Z too)
* abcdefghijklmnopqrstuvwxyz what to replace it with

## Try it here
> 1 votes

# Answer
## Java 7, 99 bytes

```
void f(char c){for(int a=c|32,i=97;i<123;i++)System.out.print(a<123&a>96?(char)(i-a+c):i<98?c:"");}

```

Slightly more readable, with no scrollbars:

```
void f(char c){
    for(int a=c|32,i=97;i<123;i++)  // a is lowercased input, i loops alphabet
        System.out.print(
            a<123&a>96?             // if a is a letter
                (char)(i-a+c):      //   subtract diff between lower and input
                    i<98?c:"");     // else print input if first iteration
}

```

The logic here is pretty straightforward, but a different method than the other Java answer.
> 1 votes

# Answer
## Perl 6, 50

```
{join "",/<:Lu>/??"A".."Z"!!/<:Ll>/??"a".."z"!!$_}

```
> 1 votes

# Answer
# PHP, 60 bytes

```
for(ctype_alpha($c=$argn)?$c=$c&a|A:$z=25;$z++<26;)echo$c++;

```

Run as pipe with `-R`.
> 1 votes

# Answer
# Recursiva, 13 bytes

```
||&N(a(&N)a)a

```

Try it online!

# Explanation:

This roughly translates to `'N(a and (' or 'N)a and )' or a`. `N(a` checks if `a` is in `(`. `(` and `)` are upper and lower-case alphabet yield.
> 1 votes

# Answer
# Ly, 32 bytes

```
"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

```

Try it online!

Explanation:

```
"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

     is                          # take input and save it
"AZ"R  ~[    ]                   # is it in the uppercase alphabet?
         p&o;                    # output the stack, terminate
              &p                 # clear stack
                     l           # load input
                "az"R ~[    ]    # is it in the lowercase alphabet?
                        p&o;     # output the stack, terminate
                             lo; # output the input, terminate

```
> 1 votes

# Answer
# Python 2, 73 bytes

```
c=ord(input())
print[chr(c),bytearray(range(c&96|1,c&96|27))][64<c&95<91]

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), ~~26~~ 24 bytes

```
t←{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵}

```

Try it online!

The byte count does not include `t←` because it's not *necessary*, it just assigns the function to `t` (so you can call it by using `t input`).

If input is not a number, it needs to be enclosed in single quotes. For the input `'`, you need to escape it by typing it twice (so the call is `t ''''`)

Thanks to @Adám for 2 bytes.

### How it works:

```
{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵} ⍝ Main function
             :            ⍝ if
         f←⎕A             ⍝ Assigns the uppercase alphabet to f
   g←819⌶                 ⍝ Assigns the I-Beam command 819 (case convert) over the uppercase alphabet (f) to g
 ⍵∊                       ⍝ The right argument 'is in' the lowercase alphabet
              g           ⍝ then print g (the lowercase alphabet)
               ⋄   :      ⍝ else if
                ⍵∊f       ⍝ the right argument 'is in' f (the uppercase alphabet)
                    f     ⍝ print f
                     ⋄⍵   ⍝ else, print the right argument.

```
> 1 votes

# Answer
# APL (Dyalog), 22 bytes

Unnamed prefix lambda.

```
{⊃a/⍨⍵∊¨a←⎕A(819⌶⎕A)⍵}

```

Try it online!

`{``}` anonymous function where  represents the argument:

`⎕A(819⌶⎕A)⍵` uppercase **A**lphabet, lowercased **A**lphabet, argument

`a←` store in `a` (for **a**ll)

`⍵∊¨` three Booleans for argument's membership of each those

`a/⍨` filter `a` by that

pick the first
> 1 votes

# Answer
# C (gcc), 94 bytes

```
#define f(c)isupper(c)?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":islower(c)?"abcdefghijklmnopqrstuvwxyz":&c

```

`#define f(c)` is like declaring a function `f` that takes a variable `c`.

`isupper(c)` checks if `c` is an uppercase letter, returns the uppercase alphabet if so. Otherwise, it checks if it's lowercase. If so, it returns the lowercase alphabet. Otherwise, it returns a pointer to `c`, which can be printed as a string (since you must pass a `char` or `int` to `f`).

Try it online!
> 1 votes

# Answer
# , 80 bytes

```
s=(r=65:90)+32
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%r,r,"if"(a%in%s,s,a)))

```

Try it online!

-1 byte thanks to Giuseppe. Still not the golfiest way (see here). Similar ideas include:

### , 87 bytes

```
f=function(x,y)"if"(a%in%x,x,y)
a=utf8ToInt(scan(,''));intToUtf8(f(r<-65:90,f(r+32,a)))

```

Try it online!

```
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%c(32:64,91:96,123:126),a,65:90+32*(a>90)))

```

and my favorite:

```
a=utf8ToInt(scan(,''));intToUtf8(c(a,65:90+32*(a>90))[2*a%in%c(32:64,91:96,123:126)-1])

```

and inspired by the other R solution (same bytecount):

```
"+"=function(x,y)"if"(a%in%x,x,y)
a=scan(,'');cat(letters+LETTERS+a,sep="")

```

Try it online!
> 1 votes

# Answer
# Noether, 40 bytes

```
{0A~bI~a/~c}{bP}b{Ua/~d}{bUP}1{cd|-}{aP}

```

**Try it online!**

Uses Noether's built-in constant function `A` to return the string `abcdefghijklmnopqrstuvwxyx`.
> 1 votes

# Answer
# C# .NET, 193 bytes

```
class P{static void Main(string[]a){var z="ABCDEFGHIJKLMNOPQRSTUVWXYZ";var b=a[0];System.Console.Write(b.Length>1?b:z.IndexOf((b[0]))>-1?z:z.ToLower().IndexOf((b[0]))>-1?z.ToLower():b[0]+"");}}

```

Try Online EDIT: Variable assignment with if statements is stupid
> 1 votes

# Answer
# Zsh, 75 bytes

```
l=${(j::):-{a..z}} u=$l:u
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}

```

---

```
l=${(j::):-{a..z}}                                  # set l to the (j::)oined lowercase
                   u=$l:u                           # set u to :uppercase'd l
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}
       ${l:#*$1*}                                   # remove *$1* from $l (is empty if $1 is lower)
     ${          :+                        }        # If non-empty, then...
                       ${u:#*$1*}                   # remove *$1* from $u (is empty if $1 is upper)
                     ${          :+$1}              # If non-empty, substitute $1
                   ${                 :-$u}         # If empty, substitute $u
    ${                                       :-$l}  # If empty, substitute $l

```

Try it online!
> 1 votes

# Answer
# Python 3, 84 bytes

```
lambda x,a='abcdefghijklmnopqrstuvwxyz':[x,a,a.upper()][(x in a)+2*(x in a.upper())]

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~62~~ 49 bytes

```
#/.(#|##->""<>##&)@@@{A=Alphabet[],Capitalize@A}&

```

Try it online!
> 1 votes

# Answer
## Python 3, 93 bytes

```
i=input();a="abcdefghijklmnopqrstuvwxyz";A=a.upper();print(i in a and a or i in A and A or i)

```

Under 100 bytes!
> 1 votes

# Answer
# C - 65 Bytes

```
f(c){for(c=islower(c)?97:c>64&c<91?65:c;(putchar(c++)|32)<122;);}

```

Thanks to @ceilingcat for -5 bytes

**Ungolfed (original version)**

```
i = 65;

f(c)
{
    if(isalpha(c))
        while(i < 91)
            putchar(c & 32 | i++);
    else
        putchar(c);
}

```

**Explanation**

A function that receives an integer (the input character) and prints it if it is not a letter or prints the entire alphabet with the capitalization of the input character.
> 1 votes

# Answer
## Seriously, 17 bytes

```
    ;;ú(úíuIúû;(@íuI

```

Hex Dump:

```
093b3ba328a3a17549a3963b2840a17549

```

Try It Online

Given that it pretty much just reads in an unformatted byte, checks if it's in the lowercase alphabet, then checks if it's in the uppercase alphabet, the automatic documentation given in the link is sufficient. (Note, however, that the documentation for `í` has the argument order reversed; it pops the sequence first.)
> 0 votes

# Answer
## k4, 24 bytes

```
{*b@&x in/:b:(.Q`A`a),x}

```

Another port of the Pyth answer—constructs a list of upper, lower, and the arg, and returns the first one that contains the arg.
> 0 votes

# Answer
# Sprects, 207 bytes

```
|<CHAR>|ZA|YA|XA|WA|VA|UA|TA|SA|RA|QA|PA|OA|NA|MA|LA|KA|JA|IA|HA|GA|FA|EA|DA|CA|BA|AABCDEFGHIJKLMNOPQRSTUVWXYZ|za|ya|xa|wa|va|ua|ta|sa|ra|qa|pa|oa|na|ma|la|ka|ja|ia|ha|ga|fa|ea|da|ca|ba|aabcdefghijklmnopqrstuvwxyz

```

Enter character on `<CHAR>`.
> 0 votes

# Answer
# AWK 104 bytes

```
/[a-z]/{print"abcdefghijklmnopqrstuvwxyz"}
/[A-Z]/{print"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
/[^A-z]/{print$0}

```
> 0 votes

# Answer
# Powershell, 116 bytes

```
$b='j';$a='ABCDEFGHIJKLMNOPQRSTUVWXYZ';switch($b){{$b-cmatch'[a-z]'}{$a.ToLower()}{$b-cmatch'[A-Z]'}{$a}default{$_}}

```

Change `$b='j'` to modify result.

I couldn't figure out a way to get the alphabet that was shorter than just writing the alphabet unfortunately.

e.g. `(65..90|%{[char][byte]$_})-join''`
> 0 votes

# Answer
# Excel VBA, 114 Bytes

Anonymous VBE immediate window function that takes input and outputs to the VBE immediate window.

```
a=Asc([A1]):i=IIf(a>64And a<91,64,(a>96And a<123)*-96):?IIf(i=0,[A1],"");:If i>0 Then For j=1To 26:?Chr(i+j);:Next

```
> 0 votes

# Answer
## REXX, 75 bytes

```
b=arg(1)
a=xrange(a,z)
if b>z then a=lower(a)
if verify(b,a) then a=b
say a

```
> 0 votes

# Answer
# Jelly, 11 bytes

```
XØA,Øa¤ċÐfȯ

```

Try it online!
> 0 votes

# Answer
# Ink, 103 bytes

```
VAR u="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
VAR l="abcdefghijklmnopqrstuvwxyz"
=o(c)
{u?c:{u}|{l?c:{l}|{c}}}->->

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 17 bytes

```
AsAus©åiAuë®åiAë®

```

Try it online or verify all test cases.

```
                   # (implicit) push STDIN to stack
A                  # push "abcdefghijklmnopqrstuvwxyz"
 s                 # swap top two values of stack
  Au               # push "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    s              # swap top two values of stack
     ©             # store top of stack in register_c
      åi           # if top of stack in second-to-top of stack...
        Au         # push "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          ë®åi     # elif value of register_c in second-to-top of stack...
              A    # push "abcdefghijklmnopqrstuvwxyz"
               ë   # else...
                ®  # push value of register_c
                   # (implicit) output top of stack to STDOUT

```
> 0 votes

# Answer
# Pyt, 17 bytes

```
ĐĐʊɔ?ĉʊ:ŕɫɔ?ĉɫ:ŕ;

```

Try it online!

```
ĐĐ                     implicit input; duplicate twice on stack
  ʊɔ?ĉʊ:               is it a lowercase letter? if so, push lowercase letters
        ŕɫɔ?ĉɫ:        else is it an uppercase letter? if so, push uppercase letters
               ŕ       otherwise, leave input on stack
                ;      end if-then-else statements; implicit print

```
> 0 votes

# Answer
# Zsh\*+coreutils, 45 bytes

```
l=${(j::):-{a-z}};<<<"$l
$l:u"|grep $1||<<<$1

```

Try it online!

(\*) Using `setopt braceccl` to save 1 byte
> 0 votes

# Answer
# Thunno 2, 9 bytes

```
A?fh?kA:Ạ

```

Attempt This Online!

## Thunno 2, 13 bytes

```
ẠD$Ƈ?:RD$Ƈ?:$

```

Attempt This Online!

#### Explanation

```
A?fh?kA:Ạ  # Implicit input
A?         # If it's alphabetic:
  fh?      #  If it's uppercase:
     kA    #   Push the uppercase alphabet
       :   #  Otherwise:
        Ạ  #   Push the lowercase alphabet
           # Otherwise, the input remains on top
           # Implicit output

```

```
ẠD$Ƈ?:RD$Ƈ?:$  # Implicit input
ẠD             # Push the lowercase alphabet and duplicate
  $Ƈ           # Pop one copy and check if the input is in it
    ?          # If it is, do nothing, leaving the lowercase alphabet
               # on the top of the stack to be implicitly output
     :         # Otherwise:
      RD       #  Push the uppercase alphabet and duplicate
        $Ƈ     #  Pop one copy and check if the input is in it
          ?    #  If it is, do nothing, leaving the uppercase alphabet
               #  on the top of the stack to be implicitly output
           :$  #  Otherwise, push the input
               # Implicit output of top of stack

```
> 0 votes

---
Tags: code-golf, string, alphabet
---