title: Big or Little Endian

text:
# Question
Title: Big or Little Endian
Write a program or function that outputs an `L` if run on a little endian architecture or a `B` if run on a big endian architecture. Lower case output `l` or `b` is also acceptable.

There is no input.

Scoring is code golf, so the code with the fewest bytes wins.

**Edit:** *As per the comments below, I am clarifying that the entry must be able to run on either architecture.*

*I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.*

# Answer
> 40 votes
# Python, 33 bytes

```
import sys
exit(sys.byteorder[0])

```

`sys.byteorder` is either `'little'` or `'big'` (and for those of you who will read this sentence without looking at the code, `[0]` means take the first character).

# Answer
> 35 votes
# C, 26 bytes

```
a=66<<24|76;f(){puts(&a);}

```

Assumes 32-bit `int` and ASCII characters. Tested on amd64 (little-endian) and mips (big-endian).

# GCC, 23 bytes

```
00000000: 613d 2742 0000 4c27 3b66 2829 7b70 7574  a='B..L';f(){put
00000010: 7328 2661 293b 7d                        s(&a);}

```

Suggested by feersum. The value of multi-character constants is implementation-dependent, but this seems to work in GCC. Tested on the same architectures.

# Answer
> 24 votes
# MATLAB / Octave, 24 bytes

```
[~,~,e]=computer;disp(e)

```

The `computer` function gives information about, well, the computer it's running on. The third output is endianness: `L` or `B` for little- or big-endian respectively.

Try it on Ideone.

# Answer
> 20 votes
# JavaScript ES6, 50 bytes

```
_=>"BL"[new Int8Array(Int16Array.of(1).buffer)[0]]

```

I don’t know who decided it was a good idea for TypedArray objects to expose the native endianness of the interpreter, but here we are.

# Answer
> 11 votes
# C, ~~36~~ 35 bytes

**1 byte thanks to @algmyr and @owacoder.**

```
~~main(a){printf(*(char*)&a?"L":"B");}~~
main(a){putchar(66+10**(char*)&a);}
main(a){putchar("BL"[*(char*)&a]);}

```

Credits here.

Untested since I don't have a big-endian machine.

# Answer
> 8 votes
### Mathematica, 22

```
{B,L}[[$ByteOrdering]]

```

This probably breaks some rule about not using a built-in function but I'm not really interested in rube goldberging an alternative.

# Answer
> 8 votes
# C, 27

One byte longer, but here it is anyway:

```
f(){putchar(htons(19522));}

```

# Answer
> 8 votes
# PowerPC machine code - 20 bytes

PowerPC is bi-endian (the endianness can be set up at startup), so this code should conform to the challenge request of being able to run both on BE and LE machines. This is a function that *returns*1 `'L'` or `'B'` depending on the endianness currently set.

As a function, AFAICT it conforms the SVR4 PowerPC ABI (used by Linux on ppc32), the PowerOpen ABI (used e.g. by AIX) and the OS X ABI. In particular, it relies just on the fact that GPR 0 is a volatile scratch register, and GPR 3 is used to return "small" values.

```
00000000 <get_endian>:
   0:   7c 00 00 a6     mfmsr   r0
   4:   54 03 0f fe     rlwinm  r3,r0,1,31,31
   8:   1c 63 00 0a     mulli   r3,r3,10
   c:   38 63 00 42     addi    r3,r3,66
  10:   4e 80 00 20     blr

```

Now, it goes like this:

* the MSR is read into GP register 0; the MSR contains at bit 31 the endianness settings (0 = big endian; 1 = little endian);
* `rlwinm` extracts just that bit: it takes the value in GPR0, **r**otates **l**eft by 1 place (so that now is in position 0) and **m**asks it with 1 (the mask generated by those 31,312); the result is put into GP register 3;
* multiply the result by 10 and sum 66 (`'B'`) (10 is the difference between `'L'` and `'B'`)
* finally, return to the caller

---

### Notes

1. yep, the question does ask to *print*, but it's not clear how I should print stuff in assembly expected to run unmodified on different operating systems. =)
2. for those interested, see the rlwinm documentation; knowing next to nothing about PowerPC, I found this kind of instructions extremely interesting.

**2018 update**: Raymond Chen is publishing a series about the PowerPC architecture, you can find here his great post about `rlwinm` & friends.

# Answer
> 7 votes
# Java 8, ~~96, 64~~ 52 bytes

```
()->(""+java.nio.ByteOrder.nativeOrder()).charAt(0);

```

A golf based on this SO answer. All credit goes to @LeakyNun and @AlanTuning. Java keeps the loosing streak.

96 bytes:

```
 char e(){return java.nio.ByteOrder.nativeOrder().equals(java.nio.ByteOrder.BIG_ENDIAN)?'b':'l';}

```

64 bytes:

```
char e(){return(""+java.nio.ByteOrder.nativeOrder()).charAt(0);}

```

Untested b/c I don't have access to a big-endian machine.

# Answer
> 6 votes
# Perl, ~~38~~ 36 bytes

```
say+(pack"L",1 eq pack"V",1)?"L":"B"

```

Works by packing a number in the system's default byte order and comparing it to a number packed in little-endian byte order.

# Answer
> 6 votes
# (G)Forth, 24 bytes

```
here $4200004C , c@ emit

```

Assumes that cells are 32 bits (and that your Forth interpreter supports Gforth's base prefixes). It simply stores the number 0x4200004C in memory and then displays the byte at the low end.

# Answer
> 5 votes
# PHP 5.6, ~~41~~ 31 bytes (thx to isertusernamehere)

`<?=unpack(S,"\x01\x00")[1]-1?B:L;`

# PHP 7, 41 bytes

`echo unpack('S',"\x01\x00")[1]-1?'B':'L';`

Idea stolen from: https://stackoverflow.com/a/24785578/2496717

# Answer
> 5 votes
# C#, 60 52 bytes

C# is surprisingly competitive in this one.

```
char e=>System.BitConverter.IsLittleEndian?'L':'B';

```

Credits to Groo for the C#6 syntax.

60 bytes:

```
char e(){return System.BitConverter.IsLittleEndian?'L':'B';}

```

# Answer
> 5 votes
## Common Lisp, 27 bytes

*Tested on SBCL and ECL. For a portable approach, one should use trivial-features.*

```
(lambda()'L #+big-endian'B)

```

The `#+` notation is a read-time condition, that *reads* the next form only if the conditional expression evaluates to true. Here the condition is the whole `#+big-endian` text which means that the test is satisfied if the `:big-endian` keyword belongs to the `*FEATURES*` list (a list which contains among other things platform-specific information). The following expression is `'B`, which is either read or skipped according to the outcome of the test. If your platform is big-endian and you write the above form in the REPL, it is exactly as if you wrote the following:

```
CL-USER>(lambda()'L 'B)

```

 (NB.`CL-USER>` is the prompt)

A function's body is an implicit `PROGN`, meaning that only the evaluation of the last expression is returned. So the above actually returns symbol ̀`B`. If however the read-time condition evaluates to false, the form reads as if you wrote:

```
CL-USER>(lambda()'L)

```

... which simply returns symbol `L`.

# Answer
> 5 votes
# C, 34 bytes

This assumes ASCII character encoding

```
main(a){putchar(66+10**(char*)a);}

```

Call without argument.

Explanation:

On call, `a` will be 1. `*(char*)a` accesses the first byte of `a`, which on little-endian platforms will be 1, on big-endian platforms will be 0.

On big-endian platforms, this code will therefore pass 66 + 10\*0 = 66 to `putchar`. 66 is the ASCII code for `B`. On little-endian platforms, it will pass 66 + 10\*1 = 76, which is the ASCII code for `L`.

# Answer
> 5 votes
# Julia, ~~24~~ 19 bytes

```
()->ntoh(5)>>55+'B'

```

This is an anonymous function that takes no input and returns a `Char`. To call it, assign it to a variable. It assumes that integers are 64-bit.

The `ntoh` function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, `ntoh` is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so `ntoh(5) == 360287970189639680`. Which is also, perhaps more readably, equal to: `0000010100000000000000000000000000000000000000000000000000000000` in binary.

If we right bit shift the result of `ntoh(5)` by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant `'B'`, we'll get `'B'` or `'L'` for big or little endian machines, respectively.

Saved 5 bytes thanks to FryAmTheEggman and Dennis!

# Answer
> 5 votes
## ARMv6 and later: 20 bytes machine code

```
0xE10F1000 : MRS   r0,CPSR        ; read current status register
0xE3110C02 : TST   r0,#1<<9       ; set Z flag if bit 9 set
0x03A0004C : MOVEQ r0,#'L'        ; return 'L' if Z clear
0x13A00042 : MOVNE r0,#'B'        ; return 'B' if Z set
0xEBxxxxxx : BL    putchar        ; print it (relative branch)

```

Untested, as I don't have a suitable machine to hand. Bit 9 of the CPSR gives the current load/store endianness.

# Answer
> 4 votes
# Perl 5, 21 + 1 = 22 bytes

Run with `perl -E`.

```
say ord pack(S,1)?L:B

```

Tested on amd64 (little-endian) and mips (big-endian).

# Answer
> 4 votes
# R, ~~28~~ 23 bytes

```
substr(.Platform$endian,1,1)

```

`.Platform$endian` returns `big` if run on big endian and `little` if on little. Here, using `substr`, it returns the first letter of the output, so either `b` or `l`.

As `endian` is the only object starting with an `e` contained in object `.Platform` we can reduce it thanks to partial matching to the following 23 bytes code:

```
substr(.Platform$e,1,1)

```

# Answer
> 3 votes
# Clojure, ~~46~~ 44 bytes

```
#(nth(str(java.nio.ByteOrder/nativeOrder))0)

```

This is a function that uses the Java builtin to get the endianness of the machine. Then get the string representation of it which will be either `"LITTLE_ENDIAN"` or `"BIG_ENDIAN"` and take the first character of whichever string is chosen and return that.

Saved 2 bytes thanks to @cliffroot.

# Answer
> 3 votes
# Ruby, ~~31~~30 chars.

```
puts [1].pack("s")>"\01"??L:?B

```

Hmm, must be a better way. Count 5 characters less if the char need not to be output as I think other solutions omit printing. i.e. remove the "puts " part if you don't want anything printed.

# Answer
> 3 votes
# Bash (and other unix shells), 32 (33) bytes

First and second attempt:

```
case `echo|od` in *5*)echo B;;*)echo L;;esac # portable
[[ `echo|od` =~ 5 ]]&&echo B||echo L         # non-portable

```

Thanks to Dennis, shorter version:

```
od<<<a|grep -q 5&&echo L||echo B  # non-portable
echo|od|grep -q 5&&echo B||echo L # portable

```

The `echo` utility outputs a newline, with hex value `0A`, and no other output. For `<<<a` it is `61 0A`.

The `od` utility, by default, interprets the input as two-byte words, zero-padded if the number of bytes is odd, and converts to octal. This results in the output of echo being interpred as `0A 00`, which is converted to `005000` as big-endian or `000012` in little-endian. `61 0A` becomes `005141` in little-endian and `060412` in big-endian. The full output of od also includes address and size data meaning we cannot use `0`, `1`, or `2` for the test.

The command is well-defined to expose the system's endianness. From the standard:

> The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.

## Compatibility notes

I am not certain if putting `echo|od` in backquotes with no double quotes around them \[which results in a three-word argument to `case`\] is supported on all systems. I am not certain if all systems support shell scripts with no terminating newline. I am mostly certain but not 100% of the behavior of od with adding the padding byte on big-endian systems. If needed, `echo a` can be used for the portable versions. All of the scripts work in bash, ksh, and zsh, and the portable ones work in dash.

# Answer
> 3 votes
## PHP, 16 bytes

```
<?=pack(S,14)^B;

```

This uses two tricks not used in the two existing PHP answers:

1. The value passed to pack() or unpack() can be anything, not just 0 or 1.
2. The bitwise XOR operator (`^`) works on strings, and the result is only as long as the shorter string, avoiding the need for a string indexing or ternary operator.

# Answer
> 2 votes
# Node, 42 bytes

```
n=>require('os').endianness()[0]

```

Pro: there's a builtin. Con: property names are very long

# Answer
> 2 votes
# PowerShell, 44 bytes

```
[char](66+10*[BitConverter]::IsLittleEndian)

```

Character 66 is `B`, and 10 characters later is number 76, `L`. A Boolean value of "true" becomes `1` when cast to a number. `BitConverter` is a standard .NET class.

# Answer
> 2 votes
## Bash, 27 bytes

```
iconv -tucs2<<<䉌|head -c1

```

(U+424C) is encoded as three UTF-8 bytes: `E4 89 8C`.

It is assumed that `iconv` uses the function from glibc and that a UTF-8 locale is used.

# Answer
> 1 votes
# Racket, ~~35~~ 28 bytes

```
(if(system-big-endian?)'B'L)

```

`'B` or `'L` respectively. Let me know if this is not specific enough :)

# Answer
> 1 votes
# Kotlin, 42 bytes

```
{(""+java.nio.ByteOrder.nativeOrder())[0]}

```

Pretty straightforward. Uses "native" Java API. This is a lambda of `() -> Char` type.

String templates don't help much, unfortunately (still 42 bytes):

```
{"${java.nio.ByteOrder.nativeOrder()}"[0]}

```

Function approach (48 bytes):

```
fun e()=(""+java.nio.ByteOrder.nativeOrder())[0]

```

# Answer
> 1 votes
# PHP, 22 bytes

```
<?=ord(pack(S,1))?L:B;

```

# Answer
> 1 votes
## Haskell (using GHC-only size-restricted numeric types), 75 bytes

```
import Unsafe.Coerce
import GHC.Int
f="BL"!!fromEnum(unsafeCoerce 1::Int8)

```

(not tested on a big-endian architecture, but it seems like it *ought* to work!)

# Answer
> 1 votes
## K, 15 bytes

```
    ("bl")@*6h$-8!`
    ,"l"

```

Explanation;

```
    From right to left;
    -8!`       /serialises the back tick and returns (0x010000000a000000f500)
    6h$-8!`    /This casts the result to `int which is type 6h(could have used `int$-8!`) - the result is (1 0 0 0 10 0 0 0 245 0i)
    *6h$-8!`   /* means first, we take the first item which is 1. Since it will be either 1 or 0, we can use it to index (@) into the two element list on the left i.e. ("bl")1 returns "l" and ("bl")0 returns b

```

# Answer
> 1 votes
# GNU Utils, 35 bytes

```
lscpu|grep -o ':.*n'|grep -Eo 'L|B'

```

*Tested on `Linux kali 4.6.0-kali1-amd64 #1 SMP Debian 4.6.4-1kali1 (2016-07-21) x86_64 GNU/Linux`, but I'm pretty sure the output should be fairly standard on most GNU/Linux distros.*

# Answer
> 0 votes
# Dyalog APL, ~~28~~ ~~19~~ ~~16~~ 15 bytes

Both solutions below require `⎕IO←0`, which is default on many systems.

In cooperation with my CTO:

```
'BL'⊃⍨⊃11⎕DR'⊢'

```

`11⎕DR'⊢'` interpret the character as 1 bit Boolean
{0,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0} on big-endian systems
{1,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0} on little-endian systems

pick the first number, i.e. 0 on big endian systems, and 1 on little-endian systems

`'BL'⊃⍨` use that to pick from the string

This one is a bit interesting, as it requires storing in the "Classic" character set to be only 15 bytes, but must be executed in the "Unicode" interpreter to get a two byte representation. However, this is not a contradiction as the Unicode interpreter can load Classic workspaces.

---

Old solution:

```
'LB'⊃⍨'E'⎕FPROPS⎕D⎕FCREATE 0

```

`⎕D⎕FCREATE 0` create an APL component file with the name `0123456789`
`'E'⎕FPROPS` query endian-ness (`0`=little, `1`=big)
`'LB'⊃⍨` pick from the string

# Answer
> 0 votes
# Nim, ~~21~~ 20 bytes

```
($cpuEndian)[0].echo

```

Takes the `cpuEndian` builtin (either `littleEndian` or `bigEndian` depending on the target CPU), stringifies it with `$`, takes its 0th character (`l` or `b` depending on the target CPU), and uses Nim's uniform function call syntax to `echo` the result.

# Answer
> 0 votes
# VBA, 151 Bytes

```
Type x
q As Long
End Type
Type z
w As Integer
End Type
Sub q()
Dim i As x, y As z
y.w=1
LSet i=y
Debug.? IIf(i.q=1,"L","B")
End Sub

```

# Answer
> 0 votes
## Lua, 31 bytes

```
print(("H"):pack(19522):sub(2))

```

Lua 5.3 is required.

# Answer
> 0 votes
# C# 50 49 bytes

Works, but has to be marked as unsafe

```
char i(){var a=0x0001;return*(byte*)&a>0?'L':'B';}

```

Updated:

```
unsafe char i(){int a=1;return"BL"[*(byte*)&a];}

```

# Answer
> 0 votes
## Tcl, 46 bytes

```
puts [string index $tcl_platform(byteOrder) 0]

```

(Nothing fancy. Just in case someone wants to know how to do it in Tcl.)

---
Tags: code-golf
---


title: The nth numerator

text:
# Question
Title: The nth numerator
You can create a list of all rationals 0 \< r ≤ 1 by listing them ordered first by denominator and then by numerator:

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

```

Note that we skip any rational number that already occurred before. E.g. 2/4 is skipped because we already listed 1/2.

In this challenge we're interested in the numerators only. Looking at the list above, write a function or program taking a positive integer *n* that returns the *nth* **numerator** from the list.

---

Testcases:

```
1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15

```

# Answer
> 4 votes
# Jelly, ~~11~~ 9 bytes

```
gRỊTµ€Fị@

```

Try it online! or verify all test cases.

### How it works

```
gRỊTµ€Fị@  Main link. Argument: n

    µ€     Map the monadic chain to the left over [1, ..., n]; for each k:
 R           Range; yield [1, ..., k].
g            Compute the GCD of k and each j in [1, ..., k].
  Ị          Insignificant; yield 1 for 1; 0 for 2, ..., k.
   T         Truth; yield all indices of 1's, i.e., all coprimes with k.
      F      Flatten the resulting 2D array.
       ị@    At-index swapped; return the n-th element.

```

# Answer
> 7 votes
# MATL, ~~17~~ 13 bytes

```
:tt!/XR6#uG))

```

Try it online! Or verify all test cases.

Input size may be limited by floating point accuracy. All test cases give the correct result.

### Explanation

This generates all fractions `k/m` with `k`, `m` in `[1 2 ...n]`, as an `n`×`n` matrix. The row indicates the numerator and the column indicates the denominator. Actually the matrix entry contains the inverse fraction `m/k`, instead of `k/m`, but this is irrelevant and can be ignored in the rest of the explanation.

Matrix entries are implicitly considered to be sorted in column-major order. In this case this corresponds to the required order: denominator, then numerator.

Three types of entries need to be disregarded from this matrix:

1. Entries `k/m`, `k>m`, that have the same value as a previous entry (for example, `2/4` is disregarded because it is the same as `1/2`)
2. Entries `k/k`, `k>1`. Entries that have a numerator exceeding the denominator
3. Entries `k/m`, `k<m` (these are not part of the problem).

Disregarding entries is done with a `unique` function, which stably removes duplicate values and outputs the indices of the surviving entries. With this, entries of type 1 above are automatically removed. To deal with types 2 and 3, the matrix entries at the diagonal and below are set to `0`. This way, all zero entries will be removed except the first (corresponding to the valid fraction `1/1`).

Consider input `4` as an example.

```
:     % Input n implicitly. Push range [1 2 ...n]
      % STACK: [1 2 3 4]
t     % Duplicate
      % STACK: [1 2 3 4], [1 2 3 4]
t!    % Duplicate and transpose
      % STACK: [1 2 3 4], [1 2 3 4], [1; 2; 3; 4]
/     % Divide element-wise with broadcast: gives matrix with all pairs
      % STACK: [1 2 3 4], [1       2       3       4;
                           0.5000  1       1.5000  2;
                           0.3333  0.6667  1       1.3333;
                           0.2500  0.5000  0.7500  1     ]
XR    % Upper triangular part above the diagonal. This sets to 0 all entries
      % corresponding to fractions that equal or exceed 1. (Since the matrix
      % actually contains the inverse fractions, nonzero entries will contain
      % values greater than 1)
      % STACK: [1 2 3 4], [0       2       3       4;
                           0       0       1.5000  2;
                           0       0       0       1.3333;
                           0       0       0       0     ]
6#u   % Indices of first appearance of unique elements
      % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15]
G     % Push input n again
      % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15], 4
)     % Index: get the n-th entry from the array of indices of unique elements
      % STACK: [1 2 3 4], 10
)     % Index (modular): get the corresponding real part. Display implicitly
      % STACK: 2

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~53~~ 49 bytes

```
(Join@@Array[Pick[r=Range@#,r~GCD~#,1]&,#])[[#]]&

```

Try it online!

# Answer
> 4 votes
## Haskell, 40 bytes

```
((0:[n|d<-[1..],n<-[1..d],gcd n d<2])!!)

```

An anonymous function. Pretty straightforward: uses a list comprehension to generate an infinite list, looping over all numerators `n` and relatively prime denominators `d`. To convert zero-index to one-indexed, we prepend a `0`, which takes `4` bytes.

# Answer
> 1 votes
# Pyth, 13 bytes

```
@smfq1idTUhdh

```

Try it online. Test suite.

# Answer
> 1 votes
# Pyth, 11 bytes

```
@sm.mibdhdS

```

Try it online: Demonstration

### Explanation:

```
@sm.mibdhdSQQ   implicit Qs at the end (Q = input number)
  m       SQ    map each denominator d from [1, 2, ..., Q] to:
   .m   hd        select the numerators b from [0, 1, ..., d]
     ibd             for which gcd(b, d) == 1 (which is the smallest possible gcd)
                  this gives [0, 1] for d=1, [1] for d=2, [1,2] for d=3, ...
 s              combine all lists to a big one
@           Q   print the Qth element

```

# Answer
> 1 votes
# Actually, 15 bytes

This answer is based on Dennis' Jelly answer. I use `HN` at the end to avoid issues with 0-indexing and needing to decrement n and swap at the beginning or end. `H` gets the first `n` members of the list of numerators that results and `N` gets the last member of that selection, i.e. the `n`th numerator, all without fiddling about with stack operations. Golfing suggestions welcome. Try it online!

```
;R`;r;)♀┤░`MΣHN

```

**Ungolfing**

```
          Implicit input n.
;         Duplicate n. Leave one n on the stack for getting the nth numerator at the end.
R`...`M   Map the following function over the range [1..n]. Variable m.
  ;         Duplicate m. Leave one m on the stack for checking coprimality later.
  r         Push the range [0...m].
  ;)        Move a duplicate of range [0...m] to BOS.
  ♀┤        Push a list of 0's and 1's where a 1 denotes a number coprime to m (a numerator),
             and 0 denotes a fraction we have counted before.
  ░         Filter the second list (range [0...m])
             by the truthy values in the first list (our coprime check).
Σ         Sum all of the lists in the result into one list.
H         Push result[:n] using the duplicate of n from the beginning of the program.
N         Push result[:n][:-1], which is the same as result[n-1], our nth numerator.
          Implicit return.

```

# Answer
> 1 votes
## Python, ~~111~~ 110 bytes

```
from fractions import*
def g(n):
 x,y=1,1
 while n>1:
  x+=1
  if x>y:x,y=1,y+1
  if gcd(x,y)<2:n-=1
 return x

```

The fraction is represented with `x/y`. The argument `n` is decremented when a new fitting fraction is found (the `gcd` from `fractions` checks can the fraction be reduced). In each iteration of the loop, `x` is incremented, then, if `x>=y`, a new series of fractions with `y+1` is started, `>` because of the "special case" `(x,y)=(2,1)`, golfed to `x>y`.

I am sure this can be golfed more, but I am missing where I could improve it. Found it.

Link to code and test cases

# Answer
> 0 votes
## JavaScript (ES6), 95 bytes

```
n=>[...Array(n*n).keys()].filter(i=>i%n<=i/n&g(i%n+1,i/n+1|0)<2,g=(a,b)=>b?g(b,a%b):a)[n-1]%n+1

```

Works by generating all  fractions with numerators and denominators from `1` to `n` and filtering out those greater than `1` or previously seen, then taking the `n`th.

# Answer
> 0 votes
# Perl, 82 + 2 (`-pl` flag) = 84 bytes

```
perl -ple '{{$d>$n?($n++,(grep!($n%$_||$d%$_),2..$d)&&redo):($n=1,$d++)}++$i!=$_&&redo;$_=$n}'

```

Ungolfed:

```
while (<>) {  # -p flag
    chomp();  # -l flag

    my $i = 0;
    my $n = 0;
    my $d = 0;

    for (;;) {
        for (;;) {
            if ($d <= $n) {
                $n = 1;
                $d++;
                last;
            }
            else {
                $n++;
                last unless grep { !($n % $_) && !($d % $_) } 2 .. $d;
            }
        }
        if (++$i == $_) {
            $_ = $n;
            last;
        }
    }
}
continue {
    print($_, "\n");
}

```

# Answer
> 0 votes
# JavaScript (ES6), 76

```
x=>eval("for(g=(a,b)=>b?g(b,a%b):a,d=n=0;x;g(n,d)-1||--x)n=++n>d?(++d,1):n")

```

*Less golfed*

```
x=>{
  g=(a,b) => b ? g(b,a%b) : a; // gcd
  for (d=n=0; x; )
  {
     ++n;
     if (n > d)
     {
        ++d;
        n=1;
     }
     if (g(n,d) == 1) // if the fraction is irreducible
        --x;
  }
  return n
}

```

**Test**

```
f=
x=>eval("for(g=(a,b)=>b?g(b,a%b):a,d=n=0;x;g(n,d)-1||--x)n=++n>d?(d++,1):n")

;`1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15`.split`\n`.forEach(
  r=>{
    var [a,k]=r.match(/\d+/g),r=f(a)
    console.log(r==k?'OK':'KO',a,r)
  }
)
```

# Answer
> 0 votes
# Clojure, 85 bytes

```
#(if(= 1 %)1(numerator(nth(distinct(for[i(range)j(range 1(inc i))](/ j i)))(dec %))))

```

Uses list comprehension to generate list of all rationals, then filters it to get only distinct ones. Takes `nth` item of the list and returns its numerator. Also separate condition is needed for the first element because Clojure isn't able to take numerator of an integer. (for whatever reason considering an integer to be not Rational – https://goo.gl/XETLo2)

See it online – https://ideone.com/8gNZEB

---
Tags: code-golf, rational-numbers
---


title: How many significant figures?

text:
# Question
Title: How many significant figures?
Given a number as input, determine how many significant figures it has. This number will should be taken as a string because you have to do some special formatting. You'll see what I mean soon (I think).

A digit is a sig-fig if at least one of the following apply:

* Non-zero digits are always significant.
* Any zeros between two significant digits are significant.
* final zero or trailing zeros in the decimal portion only are significant.
* all digits are significant if nothing follows the decimal place.
* when there are only zeroes, all but the last zero are considered leading zeroes

## Input

A string or string array of the number. It might have a decimal point at the end without a digit after it. It might not have a decimal point at all.

## Output

How many sig-figs there are.

## Examples

```
1.240 -> 4
0. -> 1
83900 -> 3
83900.0 -> 6
0.025 -> 2
0.0250 -> 3
2.5 -> 2
970. -> 3
0.00 -> 1

```

# Answer
> 1 votes
# 05AB1E, ~~11~~ 10 bytes

```
D.ïi0Ü}þïg

```

Try it online! or as a Test suite

**Explanation**

```
D            # duplicate
 .ïi  }      # if it is an integer
    0Ü       # remove trailing zeroes
       þ     # remove the "." if present
        ï    # convert to int
         g   # length

```

# Answer
> 4 votes
# Retina, ~~29~~ 27 bytes

*Saved 2 bytes thanks to @MartinEnder*

```
^0\.0*.|^\d(\d*?)0+$
1$1
\d

```

**Try it online!** | **Test suite**

# Answer
> 1 votes
## Batch, ~~204~~ 202 bytes

```
@set/ps=
:t
@if %s:.=%%s:~-1%==%s%0 set s=%s:~,-1%&goto t
@set s=%s:.=%
:l
@if not %s%==0 if %s:~,1%==0 set s=%s:~1%&goto l
@set n=0
:n
@if not "%s%"=="" set/an+=1&set s=%s:~1%&goto n
@echo %n%

```

Takes input on STDIN. Works by removing trailing zeros if the number does not contain a `.`, then removing the `.` and leading zeros, unless there are only zeros, in which case it leaves one zero. Finally it takes the length of the remaining string.

# Answer
> 0 votes
# Scala, 90 bytes

```
& =>(if(&contains 46)&filter(46!=)else&.reverse dropWhile(48==)reverse)dropWhile(48==)size

```

Explanation:

```
& =>               //define an anonymous function with a parameter called &
  (
  if(&contains 46) //if & contains a '.'
    &filter(46!=)    //remove all periods
  else             //else
    &.reverse        //reverse the string
    dropWhile(48==)  //remove leading zeros
    reverse          //and reverse again
  )
  dropWhile(48==) //remove leading zeros
  size            //return the length

```

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

```
using System.Linq;
int a(string s)=>System.Math.Max(s.Contains('.')?(s[0]<'1'?s.SkipWhile(x=>x<'1').Count():s.Length-1):s.Reverse().SkipWhile(x=>x<'1').Count(),1);

```

Ungolfed

```
int a(string s)=>
    System.Math.Max(
        s.Contains('.')                                // Has decimal place?
            ?(                                         // Has decimal place!
                s[0]<'1'                               // Start with '0' or '.'?
                    ?s.SkipWhile(x=>x<'1').Count()     // Yes: Skip leading '0' and '.', then count rest... But gives 0 for "0." and "0.00"
                    :s.Length-1)                       // No: Count length without decimal place
            :s.Reverse().SkipWhile(x=>x<'1').Count()   // No decimal place: Skip trailing '0' and count rest
    ,1);                                               // For "0." and "0.00"

```

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


title: N-dimensional Circles!

text:
# Question
Title: N-dimensional Circles!
Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object.

If we call the first number `n`, the second one `r`, and the output `x`, we get that:

* for n = 0, x = 1
* for n = 1, x = 2×r
* for n = 2, x = r2×π
* for n = 3, x = (4/3)×r3×π
* and so on... if you want, though.

Notes:

* Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered.
* The program must not read from any file and the only input are those two numbers.
* The output should use only numerals (e.g. not "14\*pi"), and should be accurate to at least two decimal digits.
* As for n = 0, you can output 0 if it makes the code shorter.
* **Extra swag for an answer covering even 4 and more-dimensional "spheres"!**
* It's , so the shortest answer in bytes wins!

Examples:

```
 1 1 -> 2

 2 3 -> 28,27

 3 1 -> 4,19

 3 4,5 -> 381,70

 1 9.379 -> 18.758

 0 48 -> 1

```

# Answer
# Jelly, 13 bytes \+ extra swag

```
÷2µØP*÷!
ç×*@

```

**Try it online!**

Works for any dimension, so long as the fixed value of π yielded by `ØP` (`3.141592653589793`) is accurate enough.

### How?

```
÷2µØP*÷! - Link 1: n, r
÷2       - n / 2
  µ      - monadic chain separation
   ØP    - π (3.141592653589793)
     *   - exponentiate: π^(n/2)
       ! - Pi(n/2): Gamma(n/2 + 1)
      ÷  - divide: π^(n/2) / Gamma(n/2 + 1)

ç×*@     - Main link: n, r
ç        - call last link (1) as a dyad: π^(n/2) / Gamma(n/2 + 1)
  *@     - exponentiate with reversed @rguments: r^n
 ×       - multiply: r^n * π^(n/2) / Gamma(n/2 + 1)

```
> 7 votes

# Answer
# Mathematica, 18 bytes, up to ~168.15 trillion dimensions

```
Pi^(a=.5#)/a!#2^#&

```

Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs `1.` for *n* = 0. Uses the formula from Volume of an n-ball on Wikipedia.

### Explanation

We are attempting to compute π*n*/2/*Γ*(*n*/2 + 1)·*R**n*, or `N[Pi^(n/2)/Gamma[n/2 + 1] R^n]` in Mathematica. In our case, `#` (first argument) is *n* and `#2` (second argument) is *R*. This leaves us with `N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &`, which can be golfed as follows:

```
N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# &    (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# &            (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# &              (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#&                (* remove whitespace *)

```

and thus, our original program.
> 13 votes

# Answer
# R, ~~75~~ ~~40~~ 38 bytes (plus extra swag)

Well, looks like I could golf this down by giving in and using the gamma function rather than recursive functions.

```
function(n,r)pi^(n/2)/gamma(n/2+1)*r^n

```

Defines an anonymous function to calculate the volume of an `n`-dimensional hypersphere of radius `r`.

Some examples:

> 1 1 -\> 2
>
> 0 48 -\> 1
>
> 2 3 -\> 28.27433
>
> 3 4.5 -\> 381.7035
>
> 7 7 -\> 3891048
>
> 100 3 -\> 122051813

# Swagless solution, ~~38~~ 34 bytes

For a few bytes less, you can have an anonymous function that only works for dimensions 1 to 3. Returns `numeric(0)` for `n=0`, and `NA` for `n>3`. (`numeric(0)` is a numeric vector of length 0; `NA` is for "not available".) Performance is otherwise identical to the general solution above.

```
function(n,r)c(1,pi,4/3*pi)[n]*r^n

```
> 6 votes

# Answer
# JavaScript (ES6), 45 bytes + extra swag

Recursive formula from wikipedia, should work for any number of dimension

```
f=(n,r)=>n<2?n?2*r:1:f(n-2,r)*2*Math.PI*r*r/n

```
> 6 votes

# Answer
# JavaScript, ~~61~~ ~~51~~ ~~49~~ 43 bytes

**0-3 dimensions are supported because there is no 4th dimension**.

Thanks to @Hedi for saving 7 bytes

```
d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3))

```

Creates function `d`. Then raises `r` to the `n`th power and then multiplies it with a number depending on `n` using ternary operators. Outputs `1` for `n=0`

Gives output to at least 2 decimal places (10+ dp)

## Here's a snack snippet!

```
var N = document.getElementById("n");
var R = document.getElementById("r");
N.value="3";//default
R.value="4.5";//default
d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3));
var b = document.getElementById("b");
b.onclick = function() {
  var s = document.getElementById("s");
  var n = document.getElementById("n").value;
  var r = document.getElementById("r").value;
  s.textContent = d(parseFloat(n),parseFloat(r));
}
```

```
span {border:1px solid black;padding:10px;font-size:30px;}
```

```
Value of n: <input id="n" type="number"></input>
Value of r: <input id="r" type="number"></input><br>
<button id="b">Calculate!</button><br><br><br>
<span id="s">THERE IS NO 4TH DIMENSION</span>
```
> 5 votes

# Answer
# Haskell, ~~74~~ ~~65~~ 36 bytes + extra swag

```
0%r=1
1%r=2*r
n%r=2*pi*r^2/n*(n-2)%r

```

Recursive formula, works for all dimensions that can be presented exactly as a double-precision floating point number but will loop infinitely for non-integral dimensions. The old version for posteriority's sake:

```
n%r=(max 1$1-(-1)**n)*(2*pi)^(floor$n/2)*r**n/product[n,n-2..1.1]

```

~~Works for all dimensions. Uses the formula from the tau manifesto. `product[n,n-2..1.1]` is a double factorial hack that won't count zero for `n==2`~~
> 5 votes

# Answer
# MATL, 17 bytes

```
3:^[2P4*P/3]*1hi)

```

This works up to 3 dimensions only. Inputs are in reverse order, that is: `r`, then `n`.

Try it online!

Consider `r=3`, `n=2` as an example.

```
3:         % Push array [1 2 3]
           % STACK: [1 2 3]
^          % Take r implicitly, and raise it to [1 2 3] element-wise
           % STACK: [3 9 27]
[2P4*P/3]  % Push array [2 pi 4*pi/3]
           % STACK: [3 9 27], [2 pi 4*pi/3]
*          % Multiply element-wise
           % STACK: [6 28.2743 113.0973]
1h         % Append 1
           % STACK: [6 28.2743 113.0973, 1]
i)         % Input n and use it as modular index into the array. Display implicitly
           % STACK: 28.2743

```
> 3 votes

# Answer
## Racket 69 bytes (plus extra swag)

Uses recursive formula from https://en.wikipedia.org/w/index.php?title=Volume\_of\_an\_n-ball&section=3#Recursions

Including suggestions by @wchargin

```
(define(v d r)(match d[0 1][1(* 2 r)][_(/(* 2 pi r r(v(- d 2)r))d)]))

```

Ungolfed (v=volume, d=dimensions, r=radius):

```
(define(v d r)
  (match d
    [0 1]
    [1 (* 2 r)]
    [_ (/ (*  2   pi   r   r   (v (- d 2) r)  )
          d)]
    ))

```

Testing:

```
(v 1 1)
(v 2 3)
(v 3 1)
(v 3 4.5)
(v 1 9.379)
(v 0 48)

```

Output:

```
2
28.274333882308138
4.1887902047863905
381.7035074111599
18.758
1

```
> 2 votes

# Answer
## Java/C/C++/C#, 69 67 bytes + extra swag!

Edit: Saved 2 bytes thanks to @AlexRacer

A dyadic function - first argument is number of dimensions, second is the radius of the n-ball.

`float v(int n,float r){return n<1?1:n<2?2*r:6.283f*r*r*v(n-2,r)/n;}`

Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)n

Whoa! Java (my test language) beats Scala here, thanks to the terse `?:` ternary syntax! This function is syntactically correct in all 4 languages in the heading, and I have tested it with C (MinGW GCC 5.4.0), & C# (VS Ultimate 2016, C# 6.0). I'm assuming that it will work in C++ too, so there. Since this function is pretty much library-independent, it should work in any C-like language with similar syntax.
> 2 votes

# Answer
## Haskell, 52 bytes for tab indent 42 bytes + extra swag

Edit: Saved 10 bytes thanks to @WChargin

A dyadic curried function - first argument is number of dimensions, second is the radius of the n-ball.

```
v 0 r=1
v 1 r=2*r
v n r=2*pi*r*r*v(n-2)r/n

```

Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)n

Save this as a separate script file and run with GHCi, with a function for testing `v` for output, e.g., `show (v 3 4.5)`. I did not test this, please let me know if this doesn't work.

Old program with 6.2832 approximation for 2π replaced (50 bytes with tab indent):

```
let v 0 r=1
    v 1 r=2*r
    v n r=2*pi*r*r*(v(n-2)r)/n

```

This can be used with GHCi in multiline mode (using `:set +m` or enclosing the code between `:{` & `:}`, the enclosures being on their own lines. Tester function required.

Static typing with full-program type inference comes into play here, allowing Haskell to do far better than Scala, and approaching Groovy, but not quite beating it thanks to the pattern match instead of a ternary, involving some character repetition.
> 2 votes

# Answer
## Python 3, ~~76~~ ~~72~~ 68 bytes + extra swag!

Recursive solution with extra swag!
Returns `0` for `n=0`

```
from math import*
f=lambda n,r:n*r*2*(n<2or pi*r/n/n*(f(n-2,r)or 1))

```

Old approach (`1` for `n=1`):

```
from math import*
f=lambda n,r:1*(n<1)or r*2*(n<2)or 2*pi*r*r/n*f(n-2,r)

```

Recursive formula from Wikipedia.

Try it online.
> 1 votes

# Answer
## Python 3, 56 bytes + extra swag!

Straightforward with extra swag!

```
from math import*
lambda n,r:pi**(n/2)*r**n/gamma(n/2+1)

```

Standard formula.

Try it online
> 1 votes

# Answer
# Perl, 63 bytes + extra swag

```
@a=1..2;push@a,6.283/$_*@a[$_-2]for 2..($b=<>);say$a[$b]*<>**$b

```

Accepts two integers n and r, one at a time, then outputs the n-volume for given radius r of an n-sphere. When n = 0, V = 1, and when n = 1, V = 2r. All further dimensions are calculated by the following formula:

Since rn is the radius's factor in every formula, I leave it out of the base calculation and only apply it at the end.

2π is approximated in the code by 6.283.
> 1 votes

# Answer
# Scala, 53 bytes

```
{import math._;(n,r)=>pow(r,n)*Seq(1,2,Pi,Pi*4/3)(n)}

```

Sorry, no extra swag for me :(

Explanation:

```
{                     //define a block, the type of this is the type of the last expression, which is a function
  import math._;        //import everything from math, for pow and pi
  (n,r)=>               //define a function
    pow(r,n)*             //r to the nth power multiplied by
    Seq(1,2,Pi,Pi*4/3)(n) //the nth element of a sequence of 1, 2, Pi and Pi*4/3
}

```
> 1 votes

# Answer
## JavaScript (ES6), 39 bytes, no swag

```
(n,r)=>[1,r+r,a=Math.PI*r*r,a*r*4/3][n]

```
> 1 votes

# Answer
## Groovy, 49 47 bytes + extra swag!

Edit: Saved 2 bytes thanks to @AlexRacer

A dyadic function - first argument is number of dimensions, second is the radius of the n-ball.

`def v(n,r){n<1?1:n<2?2*r:6.2832*r*r*v(n-2,r)/n}`

Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)n

Dynamic Typing FTW!

My Scala and Java answers use the same logic, but with static typing so higher byte counts due to type annotations :(. However, Scala and Groovy allow me to omit the `return` and the semicolon, so that helps the byte count, unlike Java/C...
> 1 votes

# Answer
# Scala, 81 79 bytes + extra swag!

Edit: Saved 2 bytes thanks to @AlexRacer

A dyadic function - first argument is number of dimensions, second is the radius of the n-ball.

`def v(n:Int,r:Float):Float=if n<1 1 else if n<2 2*r else 6.2832f*r*r*v(n-2,r)/n`

Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)n

Scala's lack of type inference for return types of recursive functions and function parameters and verbose ternary syntax hurts quite a bit here :(
> 1 votes

# Answer
# Lithp, 96 characters + extra swag

Line split in 2 for readability:

```
#N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2)
        3.1416) R) R) N))))

```

Thinking I need to upgrade my parser to require less spaces. Code size would be cut down nicely, especially in that `((/ (* (* (* (*` section.

Usage:

```
% n-circle.lithp
(
    (def f #N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2) 3.1416) R) R) N)))))
    (print (f 1 1))
    (print (f 2 3))
    (print (f 3 1))
    (print (f 3 4.5))
    (print (f 1 9.379))
    (print (f 0 48))
)

#./run.js n-circle.lithp
2
28.274333882308138
4.1887902047863905
381.7035074111598
18.758
1

```

Thanks to Rudolf for shaving a few bytes off.
> 1 votes

# Answer
## CJam (27 bytes with extra credit)

```
{1$_[2dP]*<f*\,:)-2%./1+:*}

```

Online test suite. This is an anonymous block (function) which takes arguments `d r` on the stack and leaves the result on the stack.

### Dissection

The general n-dimensional formula can be rewritten as

$$\frac{2^{\left\lceil\frac{d}{2}\right\rceil}\pi^{\left\lfloor\frac{d}{2}\right\rfloor} r^d}{d!!}$$

```
{            e# Begin block: stack holds d r
  1$_[2dP]*< e#   Build a list which repeats [2 pi] d times and take the first d elements
  f*         e#   Multiply each element of the list by r
  \,:)-2%    e#   Build a list [1 ... d] and take every other element starting at the end
  ./         e#   Pointwise divide. The d/2 elements of the longer list are untouched
  1+:*       e#   Add 1 to ensure the list is non-empty and multiply its elements
}

```
> 1 votes

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


title: Square-unspiral the string!

text:
# Question
Title: Square-unspiral the string!
Given a string, first square it as follows:

First, write the string.

```
abcde

```

Next, write the string rotated one left.

```
abcde
bcdea

```

Keep doing this until you have written *len(string)* lines.

```
abcde
bcdea
cdeab
deabc
eabcd

```

Now, read from the string like this:

```
----+
+--+|
|+>||
|+-+|
+---+

```

Which gives:

```
abcdeabcdcbaedcbcdeabaede

```

Print this string.

### Test cases

```
abcdef -> abcdefabcdedcbafedcbcdefabcbafedefaf
cena! -> cena!cenanec!anena!cec!a!
ppcg -> ppcgppcppgcpcgpg
abc -> abcabacbc
ab -> abab
a -> a
 ->

```

Please comment if a test case is incorrect.

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
> 8 votes
# JavaScript (ES7), ~~83~~ ~~80~~ ~~78~~ 77 bytes

```
s=>s.repeat(l=s.length).replace(/./g,_=>s[(c-=--i**.5-l&1||-1)%l],c=-1,i=l*l)

```

Bonus ES3-compliant program:

```
for(s=prompt(r=""),c=-1,l=s.length,i=l*l;i;)r+=s[(c-=l-Math.sqrt(i--)&1||-1)%l];alert(r)

```

---

## Explanation

This takes advantage of the fact that the output for e.g. a length 5 string can be represented as:

```
abcdeabcd cbaedcb cdeab aed e
012345678 7654321 23456 543 4

```

where each digit represents an index in the string (starting at 0), modulo the length of the string. In other words, if **n** is the length of the string, we increment the index **2n - 1** times, then decrement it **2(n - 1) - 1** times, then increment it **2(n - 2) - 1** times, etc. This can be simplified to the following algorithm:

* Start the index **i** at **-1**.
* For each integer **x** in the range **\[n2..1\]**:
    + If **floor(sqrt(x))** is of the same parity (even/odd) as **n**, increment **i**.
    + Otherwise, decrement **i**.
    + Add the character at index **i mod n** to the output.

This works because **floor(sqrt(x))** switches parities after **2n - 1** iterations, then **2(n - 1) - 1** iterations, etc.

# Answer
> 1 votes
# Python 2.7 (in CMD.EXE), 91 bytes

This requires a terminal with a working backspace(`\b`), and will not work on repl.it or ideone.com. A print statement ending in a comma separates further output with space instead of a newline or return. The backspace allows us to overwrite the separating space.

```
s=input();r=s[::-1];n=len(s)-1;i=0
while i<=n:print'\b'+s[i:]+s[:n-i]+r[i+2:]+r[:n-i],;i+=2

```

# Python 2.7, 96 bytes

Try it on ideone.com or repl.it (thanks to Oliver). Input must be a python string, e.g.`'cena!'`.

```
s=input();r=s[::-1];n=len(s)-1;i=0;S=''
while i<=n:S+=s[i:]+s[:n-i]+r[i+2:]+r[:n-i];i+=2
print S

```

---

The four slices appended by the loop (`s[i:]`,`s[:n-i]`,`r[i+2:]`,`r[:n-i]`) are taken from four edges of the spiral. For instance with `01234` the square is:

```
01234
12340
23401
34012
40123

```

So we take `01234`,`0123`,`210`,`4321`. The variable `i` is the index of the top-left value in each step of the process. In the final spiral several of the slices may be empty.

# Answer
> 1 votes
# Pyth, 15 bytes

```
.Wp.(H0_CZ.<LQU

```

A program that takes input of a `"quoted string"` and prints the result.

Try it online! or verify all test cases (modified for multiple input).

**How it works**

```
.Wp.(H0_CZ.<LQU  Program. Input: Q
            L U  Map over [0, 1, 2, 3, ..., Q-1] (implicit input):
          .< Q     Q left-shifted by that many characters
                 Call this X
.W               While
   .(H0          popping the first element of X (mutates X in-place)
  p              and printing it with no trailing newline is truthy:
         Z           X =
        C            X transposed
       _             reversed

```

# Answer
> 1 votes
# Jelly, ~~11~~ 10 bytes

```
ẋ2µṖȮṖUµÐL

```

**TryItOnline!**, or all tests

### How?

The unspiralled square is a series of "top-edge plus right-edge" and "bottom-edge plus left-edge" runs, each of which is the reverse of the previous run without the first and last letter, and the first of which is the input plus the input without the last letter (e.g. input `"abcde"` has an output of `"abcdeabcd" + "cbaedcb" + "cdeab" + "aed" + "e"`).

```
ẋ2µṖȮṖUµÐL - Main link: s                            e.g. abcde
ẋ2         - repeat s twice                          e.g. abcdeabcde
  µ    µ   - monadic chain separation
        ÐL - repeat until results are no longer unique:
   Ṗ       -     remove the last character                abcdeabcd / cbaedcb / cdeab / aed / e   / ""
    Ȯ      -     print z (with no linefeed) and return z
     Ṗ     -     remove the last character                abcdeabc  / cbaedc  / cdea  / ae  / ""  / ""
      U    -     reverse                                  cbaedcba  / cdeabc  / aedc  / ea  / ""  / "" <- no longer unique.

```

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
2×[DõQ#¨D?¨R

```

Try it online!

Explanation:

```
 2×[DõQ#¨D?¨R
               # Implicit input
 2×            # Repeat twice
   [           # Begin infinite loop
┏>  DõQ#       # If empty string, break
┃       ¨      # Remove last character
┃        D     # Duplicate
┃         ?    # Print with no newline and pop
┃          ¨   # Remove last character
┃           R  # Reverse
┗━━━━━━━━━━━━┛ # Implicit end infinite loop

```

# Answer
> 0 votes
# MATL, 27 bytes

```
"GX@q_YS]vGn1YL_GnoQ&Ple&S)

```

The empty input exits with an error (producing the correct output).

Try it online! Or verify all test cases.

# Answer
> 0 votes
# C, ~~95~~ 94 Bytes

```
i,j,k,l;f(char*s){for(k=-1,l=i=strlen(s);i--;)for(j=i*2;~j--;putchar(s[(k+=(l-i)%2*2-1)%l]));}

```

Inspired by @ETHproductions answer.

# Answer
> 0 votes
# Perl, 99 bytes

```
$_=<>;
chop;
@a=split//;
print(@a[$%,(@f=1-($b=@a-$%)..$b-3),$b-1?$b-2:(),reverse@f]),$%+=2 until$%>@a

```

Whitespace is not part of the program and is provided for readability.

Not extremely efficient code. I should be able to shorten the first three lines somehow, but everything I tried to do failed. That ternary operator also needs to be fixed somehow, but having it this way made it possible to shorten my code by like, 10 bytes because I could cut out so much.

The code works by compiling a list of palindromes, separated by even numbers, which represent the place values of the string to be pulled.

# Answer
> 0 votes
# Actually, ~~21~~ 13 bytes

This algorithm is largely based on Jonathan Allan's Jelly answer. There are two ways to go about printing the result as one string. The approach used here duplicates an intermediate step and then adds it to a running total in register 1 (an empty string by default); `;╕` in the function, then  at the end. The other approach is to duplicate an intermediate step, leave those duplicate steps on the stack, and sum them into one string at the end; `;` in the function, then  at the end.

Golfing suggestions welcome. Try it online!

```
2*`dX;╕dXR`Y╛

```

**Ungolfing**

```
         Implicit input s.
2*       Push a string that repeats s two times.
`...`Y   Call the following function until there is no change from the last call
  dX       Discard the last element. Call this new string m.
  ;╕       Duplicate m and add it to the running total in register 1.
  dXR      Discard the last element again and reverse the string.
╛        Push the unspiralled string from register 1 to the stack.
         Implicit return.

```

# Answer
> 0 votes
# Python 3, 59 bytes

```
x=input()*2
while x:x=x[:-1];print(x,end='');x=x[:-1][::-1]

```

**repl.it**

A direct port of my Jelly answer; only a full program taking input (rather than a function).
The `print(x,end='')` is a print statement which will not print the default newline.

# Answer
> -1 votes
# Python 3, 93 bytes

```
s=input();r,n,i=s[::-1],len(s)-1,0
while n-i:print(s[i:]+s[:n-i]+r[i+2:]+r[:n-i],end='');i+=2

```

Try it online!

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


title: Character by Character

text:
# Question
Title: Character by Character
Your program must take in a string like:

```
test string

```

And must output each character adding one at a time like this:

```
t
te
tes
test
test
test s
test st
test str
test stri
test strin
test string

```

notice how spaces count!

Good luck! Least Bytes win. ~N

# Answer
> 0 votes
# Pyth, 3 bytes

```
j._

```

Try it here.

```
j       Join by newlines
 ._     all prefixes of implicit input

```

# Answer
> 3 votes
# 05AB1E, 3 bytes

Uses CP-1252 encoding.

```
.p»

```

Try it online!

**Explanation**

```
     # implicit input
.p   # list of prefixes
  »  # join by newlines

```

# Answer
> 1 votes
# MATL, 6 bytes

```
"GX@:)

```

Try it online!

```
         % Implicit input
"        % For each
  G      %   Push input again
  X@:    %   Push [1 2 ... k] where k is iteration index
  )      %   Use as index into the string
         % End for each
         % Implicit display

```

# Answer
> 1 votes
# Brachylog, 5 bytes

```
@[@w\

```

Try it online!

Assuming that a trailing new line is acceptable

### Explanation

```
@[       Take a prefix of the Input
  @w     Write it to STDOUT followed by a linebreak
    \    False: try another prefix of the input

```

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


title: Reverse an xxd hexdump

text:
# Question
Title: Reverse an xxd hexdump
Given an `xxd` hexdump such as this one:

```
00000000: 1f8b 0808 4920 2258 0003 7069 6c6c 6f77  ....I "X..pillow
00000010: 2e74 7874 00d3 d707 8218 10d0 2799 c545  .txt........'..E
00000020: ba96 41a1 994c 7d60 d650 d53c 44a3 8a22  ..A..L}`.P.<D.."
00000030: cd43 34aa 28d2 3c44 a38a 22cd 4334 aa28  .C4.(.<D..".C4.(
00000040: d20c 00fd 512d 46b8 0500 00              ....Q-F....

```

Reverse it to produce the original input:

```
I "Xpillow.txt����'��E��A��L}`�P�<D��"�C4�(�<D��"�C4�(�
                                                      �Q-F�

```

(This is only an approximation of the original input)

You do not need to expand to shellcodes.

### Dupe alert

This is not a duplicate of the other `xxd` hexdump challenge because this one does not to be expanded to shellcodes.

## Rules

* You may not use external programs that parse hexdumps (such as `xxd`).
* Standard loopholes apply
* This is , smallest code wins.

# Answer
> 3 votes
# , 27 bytes

```
ÎdW40|D
Í üî
Ó../<C-v><C-v>x&
éiD@"

```

Try it online!

Note that `<C-v>` represents the unprintable character `0x16`.

# Explanation

This answer is pretty fun because it's about modifying the input into V code and then executing that code. I'll explain each command one at a time

```
Î                " On every line:
 dW              "   Delete a word
   40|           "   Move to the 40th column
      D          "   Delete everything after this

Í                " Remove all occurrences of
                 " A space
  üî             " or a newline

```

Now the buffer looks like this:

```
1f8b080849202258000370696c6c6f772e74787400d3d707821810d02799c545ba9641a1994c7d60d650d53c44a38a22cd4334aa28d23c44a38a22cd4334aa28d20c00fd512d46b8050000

```

The command to insert a character by its hex value is

```
<C-v>x<hex-value>

```

Here is where we start transforming it into actual V code.

```
Ó                " Replace
 ..              "   Two characters
   /             "   with
    <C-v><C-v>x  "   the text "<C-v>x"
               & "   And the two characters we just matched

<C-v>x1fi<C-v>x8bi<C-v>x08i<C-v>x08i<C-v>x49...

```

But the command has to be in insert mode. So we insert an 'i' at the beginning.

```
éi               " Insert an 'i'
  D              " Delete this line
   @"            " And evaluate it as V code

```

---
Tags: code-golf, string, hexadecimal
---


title: Given a Diagram, Find X

text:
# Question
Title: Given a Diagram, Find X
# Find X

I was inspired by math questions in which one is asked to "Find X" for a given shape. Originally, I was just going to have the challenge be to print the x and y location of the character 'x' in a String. But I supposed that would be too simple. So I considered the context they were normally in, and decided finding the length of a Line next to the x just seemed appropriate.

Given a string input containing a Diagram of ascii 'lines' as well as a single 'x' and potentially junk characters, print the length of the only line that has an 'x' directly adjecent to it.

## Examples

Input:

```
|
|
|x
|
|

```

Ouput:

```
5

```

Input:

```
|\
| \x
|  \
|___\

```

Output:

```
4

```

Input:

```
Diagram of a Wobbly Line:
IRRELEVANTTEXT____
____     ____/
    \___/ X ;)
      x

```

Output:

```
3

```

Input:

```
  ______________
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/

```

Output:

```
5

```

## Notes

* The Valid line characters are `\/_|`
* `\` connects the top left and bottom right of itself.
* `/` connects the top right and bottom left of itself.
* `_` connects the left and right of itself
* `|` connects the top and bottom of itself
* A line will always be straight, and only consist of one of the line characters repeated n times.
* The x will always be lowercase, and it will always be the only one in the diagram.
* Adjecent refers to the x being exactly one character above, below, or besides.
* The x will always be next to exactly one Line.
* Tabs will never appear in the input.
* Input and Output may be any acceptable format.
* This is Code Golf, so Shortest Code Wins!
* HAVE FUN. DO IT. ENJOY YOURSELF.

Reference Implementation

# Answer
# JavaScript (ES6), ~~165~~, 155 bytes

EDIT: Inlined *x* and *w*, to save some more bytes.

**Golfed** (assumes input is padded with spaces to make a rectangle)

```
t=>([k=e=o=1,v=t.search`\n`+2,-1,-v].some(h=>i=({"|":v-1,"_":1,"/":v,"\\":v})[d=t[r=l=t.search`x`+h]]),[...t].map(_=>o+=(k&=t[l-=i]==d)+(e&=t[r+=i]==d)),o)

```

**Expanded**

```
/*
   G(<input string,space padded>) => line length
*/
G=t=> {

    /*
     ! Note that these two are inlined, in the "golfed" version !
     "w" - line "width"
     "x" - index of "x"
    */
    x=t.search`x`;
    w=t.search`\n`+1;

    /*
    Locate the "line"
     l,r - left cursor, right cursor (for navigating along the line)
     k - left stop flag, e - right stop flag
     i - increment
     d - direction (char)
    */
    [k=e=o=1,v=w+1,-1,-w-1].some(h=>i=({"|":w,"_":1,"/":v,"\\":v})[d=t[r=l=x+h]]);

    /*
     Travel along the line axis in both directions

     Note, the stop condition should rather be: while(k|e),
     but we iterate over all the chars with map instead (as o is guaranteed to be < # chars),
     to save some space
    */
    [...t].map(_=>o+=(k&=t[l-=i]==d)+(e&=t[r+=i]==d));

    /*
      Resulting line length
    */
    return o;
};

```

**Test**

```
G=
t=>([k=e=o=1,v=t.search`\n`+2,-1,-v].some(h=>i=({"|":v-1,"_":1,"/":v,"\\":v})[d=t[r=l=t.search`x`+h]]),[...t].map(_=>o+=(k&=t[l-=i]==d)+(e&=t[r+=i]==d)),o);

[
G(
 "| \n" +
 "| \n" +
 "|x\n" +
 "| \n" +
 "| \n"
),

G(
"|\\   \n" +
"| \\x \n" +
"|  \\ \n" +
"|___\\\n"
),

G(
"Diagram of a Wobbly Line:\n" +
"IRRELEVANTTEXT____       \n" +
"____     ____\/           \n" +
"    \___\/ X ;)           \n" +
"      x                  \n"
),

G(
" ______________ \n"  +
"/ ____________ \\\n" +
"|/ __________ \\|\n" +
"||/ ________ \\||\n" +
"|||/ ______ \\|||\n" +
"||||/      \\||||\n" +
"|||||/  x  |||||\n"  +
"|||||\_____\/||||\n" +
"||||\_______\/|||\n" +
"|||\_________\/||\n" +
"||\___________\/|\n" +
" \_____________\/\n"
)
]

```

Sample output (if you run this in Google Chrome Developer Tools console)

> \[5, 4, 3, 5\]
> 3 votes

# Answer
# Python 3, ~~428~~ ~~408~~ ~~385~~ 378 bytes

Working, but has a ton of potential to be golfed. I'm a bit rusty.

Assumes input is padded with spaces to make a rectangle.

EDIT: Thanks to @Artyer for 23 byte savings!

EDIT2: Wow I completely missed a 6 byte savings. Saved 1 more by swapping sides of an equals check.

```
*i,=map(list,input().split('\n'))
r=c=s=q=e=w=0
o=lambda y,x:len(i[0])>x>=0<=y<len(i)
d='\/_|'
for l in i:
 if'x'in l:r=i.index(l);c=l.index('x')
for a,b in(1,0),(0,1),(-1,0),(0,-1):
 y,x=r+a,c+b;f=o(y,x)and i[y][x]
 if f in d:s=f;w=d.index(f);q,e=y,x
k=lambda y,x,g=[1,1,0,1][w],v=[1,-1,1,0][w]:o(y,x)and s==i[y][x]and(exec('i[y][x]=0')or 1+k(y+g,x+v)+k(y-g,x-v))
print(k(q,e))

```

Expanded version with explanation:

```
inputtt='''  ______________.
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/'''

# First, we get the input from STDIN and make it
# into a doubly-nested array

*input_text,=map(list,inputtt.split('\n'))

# A pretty cool Python trick to assign 0 to
# mulitple variables at once.

row=col=line_letter=line_row=line_col=line_char_index=0

# A function to check if a certian row and col is
# in bounds or not. Uses python's comparator chaining

in_bounds=lambda y,x:len(input_text[0])>x>=0<=y<len(input_text)

# A string to store all the line characters.
chars='\/_|'

# Search for the x
for line in input_text:

 # If this line contains the x...
 if'x'in line:

     # Mark the row and column
     row=input_text.index(line);col=line.index('x')

# For each direction...
for down,right in(1,0),(0,1),(-1,0),(0,-1):

 # Move in that direction
 y,x=row+down,col+right

 # If the position is in bounds, mark the char at that position
 line_found=in_bounds(y,x)and input_text[y][x]

 # If the char is a line char, set all the variables saying we found it
 if line_found in chars:
  line_letter=line_found
  line_char_index=chars.index(line_found)
  line_row,line_col=y,x

recur=lambda y,x,\
       # Find which directions we are supposed to recur in based on the line char
       g=[1,1,0,1][line_char_index],v=[1,-1,1,0][line_char_index]:\
       # If the char is in bounds and we are still on the line...
       in_bounds(y,x)and input_text[y][x]==line_letter and\
       # Set the spot to a 0, so we won't go back, increment,
       # and recur in both directions
       (exec('i[y][x]=0')or 1+recur(y+g,x+v)+recur(y-g,x-v))

# Finally, print the answer
print(recur(line_row,line_col))

```
> 8 votes

# Answer
# Lua, 480 Bytes

Lua, Being the Verbose Language it is, doesn't beat the Python Answer. But it doesn't need to.

```
a=...s={}for _ in a:gmatch"[^\n]*"do s[#s+1]={}for S in _:gmatch"."do if S=="x"then x=#s[#s]+1y=#s end s[#s][#s[#s]+1]=S end end c="\\/_|"X={-1,1,1,0}Y={-1,-1,0,-1}for _,d in pairs({{x-1,y},{x,y-1},{x+1,y},{x,y+1}})do K=d[2]k=d[1]h=s[K]w=h and h[k]C=w and c:find(w)if C then n=1 j=k J=K while true do j=j+X[C]J=J+Y[C]if s[J]and s[J][j]==w then n=n+1 else break end end j=k J=K while true do j=j-X[C]J=J-Y[C]if s[J]and s[J][j]==w then n=n+1 else break end end print(n)break end end

```

Similar to my reference implementation, but takes an actual shot at golfing, and does some things a bit more smartly than before. Still could probably be golfed a bit better though.

## With comments.

```
a=... -- Take the input from the command line.
s={}  -- Store the string as a 2D Table, instead of a multiline string.
for _ in a:gmatch"[^\n]*"do -- For each new row.
    s[#s+1] = {}            -- Make a new sub-table. This is our line.
    for S in _:gmatch"."do  -- For every character.
        if S=="x"then x=#s[#s]+1y=#s end -- If it's an x, mark down the X and Y position of it.
        s[#s][#s[#s]+1]=S                -- Push the character. This could probably be better golfed.
    end
end
c="\\/_|"   -- The ascii line characters.
X={-1,1,1,0}    -- Their X Directionals.
Y={-1,-1,0,-1}  -- Their Y Directionals.
                -- These are inversed to get their opposite direction.
for _,d in pairs({{x-1,y},{x,y-1},{x+1,y},{x,y+1}}) do -- For each up down left and right.
    K=d[2]  -- K = y
    k=d[1]  -- k = x
    h=s[K]  -- h = the yth row
    w=h and h[k]    -- w = the xth character of the yth row, if the yth row exists.
    C=w and c:find(w) -- C = the id of the ascii line character, if w existed.
    if C then
        n=1 -- n = the length of the line.
        j=k -- Temp x
        J=K -- Temp y
        while true do
            j=j+X[C] -- Increment j by the directional of the ascii.
            J=J+Y[C] -- Ditto. for J
            if s[J]and s[J][j]==w then -- if it's still the same.
                n=n+1 -- Add 1 to the length.
            else
                break -- Or stop.
            end
        end
        j=k -- Re-assign the temps as their original.
        J=K
        while true do
            j=j-X[C] -- Search in the other direction.
            J=J-Y[C]
            if s[J]and s[J][j]==w then
                n=n+1
            else
                break
            end
        end
        print(n) -- Print the length.
        break
    end
end

```
> 0 votes

# Answer
# JavaScript (ES6), 175

Assuming input is padded with spaces to make a rectangle.

```
s=>(o=>{s.replace(/[_|\\/]/g,(c,p)=>[o,-o,1,-1].map(d=>s[p+d]=='x'?[q,k]=[p,c]:c));for(n=z=k>'_'?o:k>'\\'?-1:k>'/'?o-1:o+1;s[q+=z]==k||z<0&&(n=-1,z=-z);)n++})(~s.search`
`)||n

```

*Less golfed*

```
s=>{
  o = ~s.search`\n`; // offset between rows (negated)
  // look for a line character near an 'x'
  s.replace(/[_|\\/]/g,
     (c,p)=> // for each line char 'c' in position 'p'
     [o,-o,1,-1].map(d=>s[p+d]=='x' // found a near 'x' ?
                        ?[q,k]=[p,c] // remember char and position
                        :c)
  );
  n=0;
  z=k>'_'?o:k>'\\'?-1:k>'/'?o-1:o+1; // offset to prev char of line
  while (s[q+=z]==k // move to left/top first
         || z<0 && (n=0,z=-z) // at left/top, go back and start counting
        )
    n++;
  return n-1;
}

```

**Test** Dots instead of spaces for clarity

```
f=
s=>(o=>{s.replace(/[_|\\/]/g,(c,p)=>[o,-o,1,-1].map(d=>s[p+d]=='x'?[q,k]=[p,c]:c));for(n=z=k>'_'?o:k>'\\'?-1:k>'/'?o-1:o+1;s[q+=z]==k||z<0&&(n=-1,z=-z);)n++})(~s.search`
`)||n

out=x=>O.textContent+=x

;["|.\n|.\n|x\n|.\n|.\n", "|\\...\n|.\\x.\n|..\\.\n|___\\\n"
,"Diagram of a Wobbly Line:\nIRRELEVANTTEXT...........\n____.....____/...........\n....\\___/.X.;)...........\n......x..................\n"
,"./ ____________ \\\n.|/ __________ \|\n.||/ ________ \\||\n.|||/ ______ \\|||\n.||||/      \\||||\n.|||||/  x  |||||\n.|||||\\_____/||||\n.||||\\_______/|||\n.|||\\_________/||\n.||\\___________/|\n. \\_____________/\n"].forEach(s=>out(s+f(s)+'\n\n'))
```

```
<pre id=O></pre>
```
> 0 votes

---
Tags: code-golf, string, ascii-art
---


title: Randomly Misspell a Word

text:
# Question
Title: Randomly Misspell a Word
Inspired by this CR question <sup>(please don't kill me for browsing CR)</sup>

## Spec

The probabilities of misspelling a word are:

* 1/3 of the time don't change the output
* 1/3 of the time remove a random character
* 1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.

If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for `AA` (which are `AA` or `A` or `AAA`) should all have the same probability.

---

The input will only contain of letters for simplicity.

## Examples

First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.

```
foo

fo
oo
ffoo
fooo

```

```
PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG

```

# Answer
## Pip, ~~38~~ 27 bytes

```
a@:`(.)\1*`YRR#aa@y@0X:RR3a

```

This was fun--got to use Pip's regex and mutable string capabilities, which I hadn't pulled out in a while. Takes input via command-line argument.

Explanation:

```
a@:`(.)\1*`                  Split a into runs of identical chars using regex match
           YRR#a             Yank randrange(len(a)) into y (randomly choosing one such run)
                a@y@0        Take the first character of that run
                     X:RR3   Modify in place, string-multiplying by randrange(3):
                               If RR3 is 0, character is deleted
                               If RR3 is 1, no change
                               If RR3 is 2, character is duplicated
                          a  Output the modified a

```

Try it online!
> 5 votes

# Answer
# Ruby, ~~64~~ 55 + 1 (`p` flag) = 56 bytes

Input is a line of STDIN piped in without trailing newline.

```
a=[]
gsub(/(.)\1*/){a<<$&}
a.sample[-1]*=rand 3
$_=a*''

```
> 3 votes

# Answer
## CJam (21 bytes)

```
re`_,mr_2$=3mr(a.+te~

```

Online demo

### Dissection

```
r     e# Read a line of input from stdin
e`    e# Run-length encode it
_,mr  e# Select a random index in the RLE array
_     e# Hang on to a copy of that index
2$=   e# Copy the [run-length char] pair from that index
3mr(  e# Select a uniformly random integer from {-1, 0, 1}
a.+   e# Add it to the run-length
t     e# Replace the pair at that index
e~    e# Run-length decode

```
> 2 votes

# Answer
# JavaScript (ES6), 107

```
w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

```

*Less golfed*

```
w=>(
  a = w.match(/(.)\1*/g),
  r = x => Math.random()*x | 0,
  p = r(a.length),
  b = a[p],
  a[p] = [b, b+b[0], b.slice(1)][r(3)],
  a.join``
)

```

**Test**

```
f=w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

function update() {
  O.innerHTML = Array(99)
  .fill(I.value)
  .map(x=>(
    r=f(x),
    r==x?r:r.length<x.length?'<b>'+r+'</b>':'<i>'+r+'</i>'

    )
  ).join` `
}

update()
```

```
#O { width:90%; overflow: auto; white-space: pre-wrap}
```

```
<input id=I oninput='update()' value='trolley'><pre id=O></pre>
```
> 2 votes

# Answer
# Java 7, ~~189~~ ~~180~~ 178 bytes

```
import java.util.*;String c(String i){Random r=new Random();int x=r.nextInt(2),j=r.nextInt(i.length());return x<1?i:i.substring(0,j-(x%2^1))+(x<2?i.charAt(j):"")+i.substring(j);}

```

**Ungolfed & test cases:**

Try it here.

```
import java.util.*;
class M{
  static String c(String i){
    Random r = new Random();
    int x = r.nextInt(2),
        j = r.nextInt(i.length());
    return x < 1
            ? i
            : i.substring(0, j - (x%2 ^ 1)) + (x<2?i.charAt(j):"") + i.substring(j);
  }

  public static void main(String[] a){
    for(int i = 0; i < 5; i++){
      System.out.println(c("foo"));
    }
    System.out.println();
    for(int i = 0; i < 5; i++){
      System.out.println(c("PPCG"));
    }
  }
}

```

**Possible output:**

```
foo
fooo
foo
foo
ffoo

PPCCG
PPCG
PPCCG
PPPCG
PPCG

```
> 2 votes

# Answer
# Python 2, 134 bytes

```
from random import*
def f(s):
 p=c=0;M,L=[],list(s)
 for t in L:
  if t!=p:M+=c,;p=t
  c+=1
 L[choice(M)]*=randint(0,2);return''.join(L)

```

White spaces in for loop are tabs.

Try it on Ideone
> 1 votes

# Answer
# Pyth - 17 bytes

This one actually handles the special cases with consecutive char correctly.

```
 XZOKrz8Or_1 2r9K

```

Test Suite.
> 1 votes

# Answer
# JavaScript (ES6), 103

```
w=>{w=w.split(''),r=Math.random,x=r(),i=r()*w.length|0;w.splice(i,x<.6,x>.3?w[i]:'');alert(w.join(''))}

```
> 1 votes

# Answer
## APL, 21

```
{⍵/⍨3|1+(?3)×(⍳=?)⍴⍵}

```

This starts by creating a vector of zeros with a 1 in random position. Then multiplies it by a random number between 1 and 3. +1 and mod 3 obtains a vector with all 1s and one random positioned 0,1 or 2.

Finally, ⍵/⍨ says that each letter should be written n times, where n are the numbers in the vector.

Try it on tryapl.org
> 1 votes

# Answer
# Python 2, 123 bytes

```
from random import*
R=randint
s=input()
m=n=R(0,len(s)-1)
c=R(0,2)
m=[m,1+[-len(s),m][m>0]][c==1]
n+=c==2
print s[:m]+s[n:]

```
> 0 votes

# Answer
# APL, 27 bytes

```
{⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵}

```

Explanation:

```
                        ⍴⍵  ⍝ length of ⍵
                   (⍳=?)    ⍝ bit vector with one random bit on
                 1+         ⍝ add one to each value (duplicate one character)
           2 0∘.|           ⍝ mod by 2 and 0 (remove instead of duplicate)
         1⍪                 ⍝ add a line of just ones (do nothing)
    (?3)⌷                   ⍝ select a random line from that matrix
 ⍵/⍨                        ⍝ replicate characters in ⍵

```

Test:

```
      {⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵} ¨ 10/⊂'foo'
 fooo  foo  oo  foo  fo  fo  oo  fo  oo  fooo

```
> 0 votes

---
Tags: code-golf, string, random
---


title: Product catalog

text:
# Question
Title: Product catalog
This problem is about separating a string representing a product identifier into three components.

* The first part consists of upper and lower letters of arbitrary length which represents the warehouse.
* The second part is digits which represents the product number. This part is also of arbitrary length.
* The last part is qualifiers as size and colours, and this part continues to the end of the string. The qualifiers are guaranteed to start with a capital letter and consist of alphanumeric characters.

Each part should be printed clearly separated. It is guaranteed that each part is non-empty.

The winner is the one who uses least bytes to solve this problem.

**Example:**
*Input:* UK7898S14
*Output:*
UK
7898
S14

Here UK is United Kingdom, 7898 is the product code, and S14 is size 14.

**Example 2:**
*Input:* cphDK1234CYELLOWS14QGOOD
*Output:*
cphDK
1234
CYELLOWS14QGOOD

Here cphDK is Copenhagen, Denmark, 1234 is the product code, CYELLOWS14QGOOD represents yellow colour, size 14, and good quality.

# Answer
## Perl, 12 bytes

11 bytes of code + 1 byte for `-p` flag.

```
s/\d+/
$&
/

```

To run it :

```
perl -pe 's/\d+/
$&
/' <<< "CYELLOWS14QGOOD"

```
> 10 votes

# Answer
# Retina, ~~28~~ ~~14~~ ~~10~~ 8 bytes

Saved 4 bytes thanks to *Dom Hastings*.
Saved 2 bytes thanks to *Martin Ender*.

```
S1`(\d+)

```

Try it online!
> 4 votes

# Answer
## APL, 18

```
{⍵⊂⍨3⌊+\1,2≠/⍵∊⎕D}'UK7898S14'
UK  7898  S14

```

Works by searching the first 2 points where there is a change from character to digit or vice-versa, and using those to split the string.
> 4 votes

# Answer
# JavaScript, ~~38~~ 36 bytes

```
s=>/(\D+)(\d+)(.+)/.exec(s).slice(1)

```

### Example

```
const f =

s=>/(\D+)(\d+)(.+)/.exec(s).slice(1)

console.log(f("UK7898S14"));
console.log(f("cphDK1234CYELLOWS14QGOOD"));
```
> 3 votes

# Answer
## Haskell, 36 bytes (no regex)

```
d c='/'<c&&c<':'
(span d<$>).break d

```

This gives the result in the format `("UK",("7898","S14"))`. The idea is to split at the first digit, and then split the rest at the first non-digit. Try it on Ideone.
> 3 votes

# Answer
## JavaScript (ES6), ~~28~~ 26 bytes

```
s=>s.replace(/\d+/,`
$&
`)

```

Saved 2 bytes thanks to @Grax

### Examples

```
let f =

s=>s.replace(/\d+/,`
$&
`)

console.log(f('UK7898S14'));
console.log(f('cphDK1234CYELLOWS14QGOOD'));
```
> 3 votes

# Answer
# Gema, ~~17~~ 12 characters

(The trick of not handling the country code explicitly shamelessly borrowed from Dada's Perl solution. Appreciation should be expressed there.)

```
<D>*=\n$1\n*

```

Sample run:

```
bash-4.3$ gema '<D>*=\n$1\n*' <<< 'UK7898S14'
UK
7898
S14

bash-4.3$ gema '<D>*=\n$1\n*' <<< 'cphDK1234CYELLOWS14QGOOD'
cphDK
1234
CYELLOWS14QGOOD

```
> 2 votes

# Answer
# 05AB1E, ~~39~~ ~~37~~ 16 bytes

Saved a lot of bytes thanks to Emigna.

It uses CP-1252 encoding.

```
TvDSdykF¬?¦}¶?}?

T                push "10"
 v               for each element (i.e., 1 and 0). Element is stored in 'y'
  DS             split string (input during the first iteration)
    d            for each character, 1 if digit or 0 otherwise
     yk          get index of the first occurrence of 'y'
       F         for 0 <= i < string.firstIndexOf(y)
        ¬?       print the first character of the string
          ¦      remove it from the string
           }     end inner for
            ¶?   display a newline
              }  end outer for
               ? display the remaining string

```

Try it online!

(This is my first post here!)
> 2 votes

# Answer
# Python 2, 40 Bytes

I don't know much Regex, but thankfully this problem is simple enough :) Seperates the input string into a list of length 3 which contains each part.

```
import re
lambda k:re.split('(\d+)',k,1)

```
> 2 votes

# Answer
# MATLAB, ~~81~~ 73 bytes

```
function y=f(x)
[~,~,~,m,~,~,s]=regexp(x,'(?<=^\D+)\d+');y=[s(1) m s(2)];

```

Function that accepts a string and returns a cell array of three strings. Tested in version R20105b.

Example use:

```
>> f('UK7898S14')
ans =
    'UK'    '7898'    'S14'

>> f('cphDK1234CYELLOWS14QGOOD')
ans =
    'cphDK'    '1234'    'CYELLOWS14QGOOD'

```

### Explanation

The regular expression `(?<=^\D+)\d+')` matches a group of digits preceded by non-digits from the start of the string; the latter are not part of the match.

The fourth output of `regexp` is the `'match'`; and the seventh output is the `'split'`, that is, the two parts of the string before and after the match.
> 1 votes

# Answer
# Java 7, ~~200~~ ~~185~~ ~~174~~ 167 bytes

```
import java.util.regex.*;String c(String s){Matcher m=Pattern.compile("(.*?)(\\d+)(.*)").matcher(s);s="";for(int i=0;i<3;)if(m.matches())s+=m.group(++i)+" ";return s;}

```

**Ungolfed & test code:**

Try it here.

```
import java.util.regex.*;
class M{
  static String c(String s){
    Matcher m = Pattern.compile("(.*?)(\\d+)(.*)").matcher(s);
    s = "";
    for(int i = 0; i < 3;){
      if(m.matches()){
        s += m.group(++i) + " ";
      }
    }
    return s;
  }

  public static void main(String[] a){
    System.out.println(c("UK7898S14"));
    System.out.println(c("cphDK1234CYELLOWS14QGOOD"));
  }
}

```

**Output:**

```
UK 7898 S14
cphDK 1234 CYELLOWS14QGOOD

```
> 1 votes

# Answer
## JavaScript (ES6), 36 bytes

```
s=>/(.+?)(\d+)(.*)/.exec(s).slice(1)

```

### Examples

```
let f =

s=>/(.+?)(\d+)(.*)/.exec(s).slice(1)

console.log(f('UK7898S14'));
console.log(f('cphDK1234CYELLOWS14QGOOD'));
```
> 1 votes

# Answer
# C#, ~~191~~ 177 bytes

Golfed:

```
void F(string s){var a=s.ToList();int i=a.FindIndex(char.IsDigit);int n=a.FindIndex(i,char.IsUpper);Console.Write($"{s.Substring(0,i)}\n{s.Substring(i,n-i)}\n{s.Substring(n)}");

```

Ungolfed:

```
    void F(string s)
    {
        var a = s.ToList();
        int i = a.FindIndex(char.IsDigit);
        int n = a.FindIndex(i, char.IsUpper);

        Console.Write($"{s.Substring(0, i)}\n{s.Substring(i, n - i)}\n{s.Substring(n)}");
    }

```

EDIT1: @Link Ng saved 14 bytes.
> 1 votes

# Answer
# PHP, 48 bytes

```
print_r(preg_split('/(\D+|\d+)\K/',$argv[1],3));

```

With its `$limit` parameter, and the fantastically useful `\K`, `preg_split()` is perfect for this challenge.
> 1 votes

# Answer
# Ruby, 28 bytes

```
->s{puts s.sub(/\d+/,"\n\\&\n")}

```

This surrounds the first cluster of digits with newlines.
> 1 votes

# Answer
# PHP, 61 59 5655 bytes

```
preg_match('/(\D+)(\d+)(.+)/',$argv[1],$a);print_r($a);

```

This does output the initial code as well:

```
Array
(
    [0] => cphDK1234CYELLOWS14QGOOD
    [1] => cphDK
    [2] => 1234
    [3] => CYELLOWS14QGOOD
)

```

### Edit

Thanks to @manatwork for saving a few bytes for me
Thanks to @RomanGräf for another few bytes saved
> 0 votes

# Answer
# JavaScript without regex, 84 81 79 bytes

`p=>{for(i=n=o='';i<p.length;){if(n==isNaN(c=p[i++])){o+=' ';n++}o+=c}return o}`
> 0 votes

# Answer
# jq, 47 characters

(43 characters code + 4 characters command line options.)

```
match("(\\D+)(\\d+)(.+)").captures[].string

```

(Again the old story: fairly elegant at the beginning, then becomes painfully verbose.)

Sample run:

```
bash-4.3$ jq -Rr 'match("(\\D+)(\\d+)(.+)").captures[].string' <<< 'UK7898S14'
UK
7898
S14

bash-4.3$ jq -Rr 'match("(\\D+)(\\d+)(.+)").captures[].string' <<< 'cphDK1234CYELLOWS14QGOOD'
cphDK
1234
CYELLOWS14QGOOD

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)
> 0 votes

# Answer
# R, 63 52 bytes

Edit: Saved a bunch of bytes thanks to @JDL

Takes input from stdin and prints to stdout:

```
gsub("([a-z]+)(\\d+)(.+)","\\1 \\2 \\3",scan(,""),T)

```

Example output:

```
[1] "UK 7898 S1"
[1] "cphDK 1234 CYELLOWS14QGOOD"

```
> 0 votes

# Answer
# Python 2, ~~103~~ ~~94~~ 88 bytes

Solution without using regex

```
a,b=input(),""
for f in a:
 if ord(f)<58:b+=f
 elif b"":c,d=a.split(b);print c,b,d;break

```

Simply extracts the numbers from the middle then slices the input using the number as an index. Requires quotes around the input but I didn't see anywhere that quotes are disallowed.

-9 by splitting a on the middle number then print the components with b in the middle

-6 Thanks to @Shebang

Test Cases

```
D:\>python codes.py
"UK7898S14"
UK 7898 S14

D:\>python codes.py
"cphDK1234CYELLOWS14QGOOD"
cphDK 1234 CYELLOWS14QGOOD

```
> 0 votes

# Answer
# Mathematica, 39 bytes

```
StringSplit[#,a:DigitCharacter..:>a,2]&

```

Anonymous function. Takes a string as input, and returns a list of strings as output.
> 0 votes

# Answer
## Racket 274 bytes

```
(let((g 0)(j'())(k'())(l'())(m list->string)(r reverse)(n char-numeric?)(c cons))(for((i(string->list s)))
(when(and(= g 0)(n i))(set! g 1))(when(and(= g 1)(not(n i)))(set! g 2))(match g[0(set! j(c i j))]
[1(set! k(c i k))][2(set! l(c i l))]))(list(m(r j))(m(r k))(m(r l))))

```

Ungolfed:

```
(define (f s)
  (let ((g 0)
        (j '())
        (k '())
        (l '())
        (m list->string)
        (r reverse)
        (n char-numeric?)
        (c cons))
    (for ((i (string->list s)))
      (when (and (= g 0) (n i)) (set! g 1)  )
      (when (and (= g 1) (not (n i))) (set! g 2) )
      (match g
        [0 (set! j (c i j))]
        [1 (set! k (c i k))]
        [2 (set! l (c i l))]))
    (list (m (r j)) (m (r k)) (m (r l)))))

```

Testing:

```
(f "UK7898S14")
(f "cphDK1234CYELLOWS14QGOOD")

```

Output:

```
'("UK" "7898" "S14")
'("cphDK" "1234" "CYELLOWS14QGOOD")

```
> 0 votes

# Answer
# Jelly, 14 bytes

```
O<65ITḣ2‘ṬœṗµY

```

**TryItOnline!**

### How?

```
O<65ITḣ2‘ṬœṗµY - Main link: productIdentifier   e.g. "UK7898S14"
O              - cast to ordinals               e.g. [85,75,55,56,57,56,83,49,52]
 <65           - less than 65?                  e.g. [ 0, 0, 1, 1, 1, 1, 0, 1, 1]
    I          - incremental difference         e.g. [ 0, 1, 0, 0, 0,-1, 1, 0]
     T         - truthy indexes                 e.g. [2, 6, 7]
      ḣ2       - head to 2                      e.g. [2, 6]
        ‘      - increment                      e.g. [3, 7]
         Ṭ     - set truthy indexes             e.g. [0, 0, 1, 0, 0, 0, 1]
          œṗ   - split y at truthy indexes of x e.g. ["UK", "7898", "S14"]
            µ  - monadic chain separation
             Y - join with line feeds

```
> 0 votes

# Answer
# C, 107 bytes

```
#define p(x) printf("%c",x);
f(char*s){for(;*s>64;s++)p(*s)p(10)for(;*s<58;s++)p(*s)p(10)for(;*s;s++)p(*s)}

```

Call with:

```
int main()
{
   f("UK7898S14");
   return 0;
}

```
> 0 votes

# Answer
# C#, 74 bytes

```
v=>new System.Text.RegularExpressions.Regex("\\d+").Replace(v,"\n$&\n",1);

```

Replace 1st set of digits with carriage return, set of digits, and another carriage return, as Johan Karlsson did for JavaScript.
> 0 votes

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


# Question
Title: I deserve a castle for it only being Tuesday
It is only Tuesday, ugh. I deserve a treat. Golf me a Castle. The Least amount of bytes wins!

Taken no input and output this image exactly:

```
 /\           /\
/  \         /  \
----         ----
|  |^^^^^^^^^|  |
-----------------
|       _       |
|   |  | |  |   |
|      | |      |

```

### Edit

Build me a brick wall! 36 votes versus my -9. Okay.

# Answer
> 4 votes
# Bubblegum, 52 bytes

```
00000000: 35c8 3111 c030 1443 b1fd a310 815c 08f5  5.1..0.C.....\..
00000010: 5a22 06df 64b0 263f db0f 7562 367d b831  Z"..d.&?..ub6}.1
00000020: eb50 3726 e4ad 9059 5513 c007 c804 2142  .P7&...YU.....!B
00000030: f441 74fc                                .At.

```

Obligatory Bubblegum answer.

# Answer
> 3 votes
# Swift 3, 200 bytes

```
var z=" /\\ 9/\\\n/  \\ 7/  \\\n-2 7-2\n|  |^7|  |\n-95\n| 5_ 5|\n| 1|  | |  | 1|\n| 4| | 4|",o="",x=""
for c in z.characters{let k="\(c)"
if let b=Int(k){for i in 0...b{o+=x}}else{o+=k
x=k}}
print(o)

```

Basically loop trough the `Characters` of `z` string, if a digit (b) is found then repeat the last character `b+1` times

Try online here

# Answer
> 2 votes
# Ruby, 130 bytes

```
f=->a,b=' '{a+b*9+a};g=->s{?|+s.center(15)+?|};puts f[' /\\ '],f['/  \\'],f[c=?-*4],f[d='|  |',?^],f[c,?-],g[?_],g[d+' '+d],g['| |']

```

This can probably be golfed down more.

# Answer
> 1 votes
## JavaScript (ES6), 120 bytes

```
_=>` /\\44/\\
/8\\36/8\\
173617
|8|38|8|
69
|28_28|
|12|8| |8|12|
|24| |24|`.replace(/\d\d?/g,n=>' -^'[n&3].repeat(n/4))

```

### Demo

```
let f =

_=>` /\\44/\\
/8\\36/8\\
173617
|8|38|8|
69
|28_28|
|12|8| |8|12|
|24| |24|`.replace(/\d\d?/g,n=>' -^'[n&3].repeat(n/4))

console.log(f())
```

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Create another empty string in .NET?

text:
# Question
Title: Create another empty string in .NET?
I apologize if this isn't fit for this site but it is a puzzle, not all that practical, so I thought it would fit.

Take this code:

```
string s = "";
Console.WriteLine(ReferenceEquals(s, string.Empty));

```

This will print out `true` because `""` is interned by the JITter at some early point and literals are reused from the interning cache.

The question and puzzle is this:

> How can you initialize `s` such that
> 1. `s.Length == 0`
> 2. `ReferenceEquals(s, string.Empty) == false`

I've tried the following:

```
string s = "test".Substring(0, 0); // any arbitrary legal start offset tried
string s = new string(' ', 0);
string s = new string(new char[0]);
string s = CallSomeMethodThatWontBeInlined() + CallSomeMethodThatWontBeInlined();

```

These three all end up being equal to `string.Empty`.

Bonus if you can explain the above behavior with regards to `new string(...)`. I have my thoughts about it but no solid evidence one way or another.

I can understand that all methods that concatenate or take substrings of existing strings special-case the result that will end up with length zero, but how `new string(...)` actually doesn't create a new object I don't know.

**Note!** I'm asking for legal C#. I'm not asking for a p/invoke or assembly code call that just manually constructs the bytes of an empty string object in memory and stuffs a pointer to it into a string variable.

Any method or path through existing classes in .NET or using operators of strings or whatnot that would end up with the required results are legal. As such, take the `Substring` example above, if that returned a new empty string that isn't the same as the existing one, then that would be a/the answer to this puzzle.

Reflection is boundary, at the very least it has to be reflection that can run in untrusted scenarios.

---

My own "conclusion" is that this may indeed be impossible because the actual C# code that would end up constructing such a string would end up with one of the `new string(...)` overloads, or using one of the operators which all seem to handle this cases. As such, the end-point of any such code may be the one that handles this case and since it does, it may not be possible.

# Answer
So, I'll take the easy way:

```
string s = "";

```

So, `s.Length` is now 0, so far so good. But how can we get `ReferenceEquals(s, string.Empty)` to false.

Piece of cake, just put that into your class:

```
public static new bool ReferenceEquals(object a, object b) => false;

```

and the above call will result in false.

I will look for some more sneaky methods, so.
> 3 votes

# Answer
# 1st try: Reflection

```
String s = "abc";
PropertyInfo pi = s.GetType().GetProperty("Length");
pi.SetValue(s, 0, null);

```

Yields error, there is no set property

# Loophole

```
var s = new { Length = 0 };

```

Now the `ReferenceEquals` will return `false` and `s.Length == 0`. Just sticking to your rules =)
> 2 votes

---
Tags: code-golf, c#
---


title: Print a ballot!

text:
# Question
Title: Print a ballot!
As you all know, today is election day!

Your task today is to print out a ballot, given an input.

If the input is `Hillary Clinton`, print:

```
Hillary Clinton   ===-----===>
Donald Trump      ===     ===>
____________      ===     ===>

```

However, if the input is `Donald Trump`, print:

```
Hillary Clinton   ===     ===>
Donald Trump      ===-----===>
____________      ===     ===>

```

If it is something else, write it on the third line:

```
Hillary Clinton   ===     ===>
Donald Trump      ===     ===>
Oliver Ni         ===-----===>

```

(Technically, I'm not 18 yet...)

Remember, this is , so the code with the fewest bytes wins.

# Answer
> 6 votes
# Jelly, ~~55~~ 53 bytes

```
³ẇị⁾- x5⁾ =,”=x3¤j;”>ṭ
ṭ“Gụ©l⁴“%eŻƤ(»”_x12¤ṭQḣ3z⁶ZÇ€Y

```

Try it online!

### Explanation

```
³ẇị⁾- x5⁾ =,”=x3¤j;”>ṭ   Helper link. Argument: row
³ẇ                       Check if the user's vote is in this row
  ị⁾-                    Take "-" if it was, " " otherwise
      x5                 Take five of that character
        ⁾ =,”=           Take the array [" =", "="]
              x3         Turn it into ["   ===", "==="]
                ¤        Combine the two previous steps into a nilad
                 j       Join the list by the five character string
                  ;”>    Add ">"
                     ṭ   Prepend the original row

ṭ“Gụ©l⁴“%eŻƤ(»”_x12¤ṭQḣ3z⁶ZÇ€Y   Main link. Argument: vote
 “Gụ©l⁴“%eŻƤ(»                   Take the array ["Hillary Clinton", "Donald Trump"]
ṭ                                Add the user's vote to the list
              ”_                 Take "_"
                x12              Take twelve times that
                   ¤             Combine the two previous steps into a nilad
                    ṭ            Add that string to the list
                     Q           Remove duplicates
                      ḣ3         Take the three first items
                        z⁶       Transpose, padding with spaces
                          Z      Transpose back
                           Ç€    Apply the helper to each row
                             Y   Join with newlines

```

# Answer
> 4 votes
# 05AB1E, ~~74~~ ~~59~~ 57 bytes

Uses CP-1252 encoding.

```
”ŽÏaryµÍ””¹Ñ Trump”I'_12×)Ù3£vyð18yg-×„ -¹yQè5×'=3×.ø'>J,

```

Try it online!

# Answer
> 4 votes
## Python 2, 127 bytes

```
X=['Hillary Clinton','Donald Trump']
i=input()
X+=[[i],['_'*12]][i in X]
for x in X:print x.ljust(18)+'==='+' -'[i==x]*5+'===>'

```

# Answer
> 2 votes
## JavaScript (ES6), 149 bytes

```
s=>['Hillary Clinton','Donald Trump',0].map(S=>((S?S:s||'____________')+p+p+p+p+p).slice(0,18)+`===${!S^S==s?(s=0,'-----'):p}===>`,p='     ').join`
`

```

### Demo

```
let f =

s=>['Hillary Clinton','Donald Trump',0].map(S=>((S?S:s||'____________')+p+p+p+p+p).slice(0,18)+`===${!S^S==s?(s=0,'-----'):p}===>`,p='     ').join`
`

console.log(f('Hillary Clinton'))
console.log(f('Donald Trump'))
console.log(f('Obi-Wan Kenobi'))
```

# Answer
> 2 votes
# Java 7, ~~390~~ ~~339~~ 335 bytes

```
String c(String s){String h="Hillary Clinton",d="Donald Trump",r=h+"   ===Q===>\n"+d+"      ===X===>\nZ===J===>";boolean H=h.equals(s),D=d.equals(s);for(int i=s.length();i++<18;s+=" ");return r.replace(H?"Q":D?"X":"J","-----").replace(H|D?"Z":"~","____________      ").replaceAll(H?"X|J":D?"Q|J":"Q|X","     ").replace(H|D?"~":"Z",s);}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(String s){
    String h = "Hillary Clinton",
           d = "Donald Trump",
           r = h+"   ===Q===>\n"+d+"      ===X===>\nZ===J===>";
    boolean H = h.equals(s),
            D = d.equals(s);
    for(int i = s.length(); i++ < 18; s += " ");
    return r.replace(H?"Q":D?"X":"J", "-----")
            .replace(H|D?"Z":"~", "____________      ")
            .replaceAll(H?"X|J":D?"Q|J":"Q|X", "     ")
            .replace(H|D?"~":"Z", s);
  }

  public static void main(String[] a){
    System.out.println(c("Hillary Clinton"));
    System.out.println();
    System.out.println(c("Donald Trump"));
    System.out.println();
    System.out.println(c("Anyone else?.."));
    System.out.println();
    System.out.println(c("S"));
    System.out.println();
    System.out.println(c("Anyone who is willing to take the job"));
  }
}

```

**Output:**

```
Hillary Clinton   ===-----===>
Donald Trump      ===     ===>
____________      ===     ===>

Hillary Clinton   ===     ===>
Donald Trump      ===-----===>
____________      ===     ===>

Hillary Clinton   ===     ===>
Donald Trump      ===     ===>
Anyone else?..    ===-----===>

Hillary Clinton   ===     ===>
Donald Trump      ===     ===>
S                 ===-----===>

Hillary Clinton   ===     ===>
Donald Trump      ===     ===>
Anyone who is willing to take the job===-----===>

```

# Answer
> 1 votes
# , 104 bytes

```
OHillary Clinton³ ³=µ ³=>YpRDonald Trump   p15r_ñ/^¨á« á«¾©.*î¨.*î©*\1
22|5r-Gdññ3GjéRDk@"Í_/
22|5r-

```

Try it online!

This answer is way too hacky, and way too long. I guess that's what you get when you design a golfing-language off of a text-editor. `¯\_(ツ)_/¯`

# Answer
> 0 votes
## Batch, 210 bytes

```
@set s=%1
@call:l %1 "Hillary Clinton"
@call:l %1 "Donald Trump"
@call:l %1 %s%
@exit/b
:l
@set v=
@if %1==%2 set v=-----&set s=____________
@set t=%~2
@echo %t:~0,18%===%v%===^>

```

Note: the line `@set v=` has 5 trailing spaces, and the line `@set t=%~2` has 18. Accepts input as a quoted command-line parameter.

# Answer
> 0 votes
# C#, 266 Bytes

Golfed:

```
string B(string s){var h="Hilary Clinton".PadRight(17);var d="Donald Trump".PadRight(17);var r="===     ===>\n";var c=r.Replace(" ", "-");var b="____________".PadRight(17);return s==h.Trim()?s.PadRight(17)+c+d+r+b+r:s==d.Trim()?h+r+d+c+b+r:h+r+d+r+s.PadRight(17)+c;}

```

Ungolfed:

```
public string B(string s)
{
  var h = "Hilary Clinton".PadRight(17);
  var d = "Donald Trump".PadRight(17);
  var r = "===     ===>\n";
  var c = r.Replace(" ", "-");
  var b = "____________".PadRight(17);
  return s == h.Trim() ? s.PadRight(17) + c + d + r + b + r :
    s == d.Trim() ? h + r + d + c + b + r :
      h + r + d + r + s.PadRight(17) + c;
}

```

*Tried to create a Func for all those PadRights...Exactly the same byte count...*

Testing:

```
var printABallot = new PrintABallot();
Console.WriteLine(printABallot.B("Hilary Clinton"));

Hilary Clinton   ===-----===>
Donald Trump     ===     ===>
____________     ===     ===>

Console.WriteLine(printABallot.B("Donald Trump"));

Hilary Clinton   ===     ===>
Donald Trump     ===-----===>
____________     ===     ===>

Console.WriteLine(printABallot.B("Kanye West"));

Hilary Clinton   ===     ===>
Donald Trump     ===     ===>
Kanye West       ===-----===>

```

# Answer
> 0 votes
# Python 3.6, 132 bytes

```
i=input()
s=['Hillary Clinton','Donald Trump','_'*12]
if x not in s:s[2]=i
for k in s:print(f'{k:18}==={" -"[k==i]*5}===>')

```

Uses 3.6's new f-strings.

# Answer
> 0 votes
# Pyth, 76 bytes

```
V{+_tW!}zJ[*\_12"Donald Trump""Hillary Clinton")Jzs[.[Nd18K*\=3*?qzN\-d5K\>

```

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Determine the optimal cruise control options
A cruise control has 3 different options to move the handle to set the speed you want to drive with.

* Towards you: Adds 1 speed.
* Upwards: Increases speed to the next multiple of 10 (e.g. 20--\>30, 32--\>40)
* Downwards: Decreases speed to the next multiple of 10 (e.g. 20--\>10, 32--\>30)

**Input**

* 2 integers: the first is the starting speed and the second is your desired speed, both non-negative and in any form you like (array, two arguments, etc.)

**Task**

* Determine the optimal way of using the handle to reach the desired speed and print out the moves in the correct order.

**Rules**

* If you have the choice between pulling towards you and going upwards (like from 39 to 40) you can choose either option, but stay with whatever you choose for similar cases
* You may use any 3 different (preferably visible) symbols to distinguish between the moves in the output (T, U and D for example).
* The symbols can be seperated by new lines, spaces, etc. but don't have to be

Here are some test cases:

```
start speed, desired speed  -->  output
30, 40  -->  U
30, 43  -->  UTTT
43, 30  -->  DD
51, 39  -->  DDDTTTTTTTTT
29, 30  -->  T or U
29, 50  -->  TUU or UUU
12, 12  -->

```

This is so the shortest answer in bytes wins.

# Answer
# JavaScript (ES6), ~~91~~ ~~84~~ 75 bytes

*Saved 4 bytes thanks to @Neil*

```
f=(s,d)=>s-d?(q=s+10-s%10)>d?s>d?0+f(s-(s%10||10),d):1+f(s+1,d):2+f(q,d):""

```

Uses `0` for `D`, `1` for `T`, and `2` for `U`.
> 1 votes

# Answer
# Java, 144 139

Saved 5 bytes thanks to Kevin.

```
void o(int s,int e){int t=10,x=s/t;System.out.print(s>e?"D":s<e?x<e/t?"U":"T":"");if(s!=e)o(s>e?x*t-(s%t<1?t:0):s<e?x<e/t?(x+1)*t:s+1:0,e);

```

Ungolfed

```
public static void optimalCruise(int start, int end){

    if(start > end) {
        System.out.print("D");
        optimalCruise(start/10*10-(start%10<1?10:0), end);
    } else if(start < end){
        if(start/10 < end/10){
            System.out.print("U");
            optimalCruise(((start/10)+1)*10, end);
        } else {
            System.out.print("T");
            optimalCruise(start+1, end);
        }
    }
}

```
> 1 votes

# Answer
## Batch, 175 bytes

```
@set/as=%1,d=%2,e=d/10*10
:d
@if %s% gtr %d% echo d&set/as=~-s/10*10&goto d
:u
@if %s% lss %e% echo u&set/as=s/10*10+10&goto u
:t
@if %s% neq %d% echo t&set/as+=1&goto t

```

Fairly straightforward this time. Takes input as command-line parameters, which it saves into `s` and `d`. `e` is `d` rounded down to the previous multiple of 10. If `s` is greater than `d`, then we obviously need to invoke `d` until `s` becomes lower than `d`. Otherwise, we need to check whether `s` is lower than `e`; if so, we can invoke `u` until `s` equals `e`. At this point `s` is now between `e` and `d` and we can simply invoke `t` until we reach `d`. I looked into `for` loops but they use inclusive endpoints so would have become too verbose.
> 0 votes

# Answer
# Python, 76 bytes

```
lambda a,b: "U"*(b//10-a//10)+"D"*(a//10-b//10+(b<a))+"T"*min(b%10,(b-a)%99)

```
> 0 votes

# Answer
# C, 156 bytes

```
t,x,y;main(int s,char**a){x=(s=atoi(a[1]))/10,y=(t=atoi(a[2]))/10;if(s^t){for(;y>x;++x)puts("U");for(x+=(s-t>10);x>y;--x)puts("D");for(;t--%10;)puts("T");}}

```

Ungolfed:

```
#include <stdio.h>
#include <stdlib.h>
int t, x, y;
int main(int s, char **a)
{
    x = (s = atoi(a[1])) / 10,
    y = (t = atoi(a[2])) / 10;

    if (s ^ t) {
        for ( ; y > x; ++x)
            puts("U");

        for (x += (s - t > 10) ; x > y; --x)
            puts("D");

        for ( ; t-- % 10; )
            puts("T");
    }
    return 0;
}

```
> 0 votes

---
Tags: code-golf, arithmetic
---