# Question
Title: Numbers vs. Strings: Language fitness challenge
*inspired by thejonymyster's idea*

## Rules

This challenge is about finding languages that are very suitable for one task but quite the opposite in the other. The two tasks share a theme, but Task 1 is designed to be number-oriented while 2 is string-oriented. You can participate in **three categories**:

* **Numbers**: Choose a language, and solve both tasks in it. The language must be specified down to a specific *implementation, version, and flags*, and these *cannot be changed once posted*. Each solution is scored by the code size in bytes; your answer's score is \\${T\_2}/{T\_1}\\$ where \\$T\_1\\$ is the score for Task 1 and \\$T\_2\\$ is for Task 2. Higher score is better.
* **Strings**: Same as Numbers, except for scoring. Your answer's score is \\${T\_1}/{T\_2}\\$, i.e. the reciprocal of that of Numbers. Higher score is better.
* **Robbers**: Choose an answer X for Numbers or Strings. Come up with a better solution for the worse task for the given language, and post it as a comment. By doing this, you gain (effectively steal) X's score lost. Higher total score is better.
    + Example: Let's assume a Numbers post with 4B in task 1 and 9B in task 2. If you golf task 2 down to 7B, the answer's score is reduced from 9/4 to 7/4, and you get 2/4 = 0.5 points.

You will naturally participate in Numbers if your solution to Task 2 is longer than Task 1, and in Strings otherwise. However, you may *not* switch the category of an answer already posted, even if the golfing attempts result in the score less than 1.

Everyone is free to give golfing suggestions to existing answers, but the only ones that *reduce* the answer's score count as robbers.

Once the challenge is inactive for **1 week**, the winners of each category will be decided as follows:

* **Numbers** and **Strings**: the highest scoring answer in each category wins.
* **Robbers**: the participant with the highest total stolen score wins.

## Task 1: Number thickness

Given a positive integer \\$n\\$ and integer base \\$b \ge 2\\$, compute the thickness of \\$n\\$ in base \\$b\\$. For base 2, the values are A274036. The thickness is computed as follows: if the inputs are \\$n = 22\\$ and \\$b = 2\\$,

* Convert \\$n\\$ to base-\\$b\\$ digits: \\$10110\_2\\$
* Treat it as a polynomial: \\$B\_n(x) = 1x^4 + 0x^3 + 1x^2 + 1x^1 + 0x^0\\$
* Compute its square: \\$B\_n(x)^2 = x^8 + 2x^6 + 2x^5 + x^4 + 2x^3 + x^2\\$
* Take the highest coefficient: 2.

Therefore, the thickness of 22 in base 2 is 2.

**Test cases**

```
22, 2 -> 2
8, 2 -> 1
15, 2 -> 4
100, 3 -> 6
12345, 10 -> 46

```

## Task 2: String thickness

Given a nonempty string \\$s\\$ consisting of uppercase letters, compute the string thickness of \\$s\\$. It is calculated as follows: if the input is `ABAAB`,

* For each length-2 substring of \\$s\\$, replace all non-overlapping appearances of it with \\$s\\$.
    + `AB -> ABAAB`: `ABAABAABAAB`
    + `BA -> ABAAB`: `AABAABAABAABAABAABAB`
    + `AA -> ABAAB`: `ABAABBABAABBABAABBABAABBABAABBABAABBAB`
    + `AB -> ABAAB`: `ABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAAB`
* Count how many times \\$s\\$ appears as non-overlapping substrings of the result.

```
ABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAAB
11111 22222 33333 44444 55555 66666 77777 88888 99999 aaaaa bbbbb ccccc ddddd

```

The string thickness of `ABAAB` is 13.

For this task, taking the input string as a list of chars or a list of codepoints is allowed.

**Test cases**

```
ABAAB -> 13
AB -> 1
XXYY -> 2
ARRAY -> 3
NUMBER -> 5
PQRRQP -> 6
XYXZYX -> 21

```

## Example submission

```
# Numbers, Python 3.10, score 109 / 54 = 2.0185

## Task 1, 54 bytes

    <insert code here><insert code here><insert code here>

## Task 2, 109 bytes

    <insert code here><insert code here><insert code here>
    <insert code here><insert code here><insert code here>

```

# Answer
> 7 votes
# Strings, Python 3.8.10, score 83 / 65 = 1.2769

## Task 1, 83 bytes

*-7 bytes from @xnor **(+7/65)***

```
lambda n,b:max(sum(n//b**i%b*(n*b**i//b**k%b)for i in range(n))for k in range(n+1))

```

Attempt this Online!

## Task 2, 65 bytes

*-1 byte from @Steffan*

```
s=t=p=input()
for c in s:t=t.replace(p+c,s);p=c
print(t.count(s))

```

Attempt This Online!

# Answer
> 6 votes
# Numbers, Factor 0.99 Build #1889 + `math.extras math.polynomials`, score 66 / 53 = 1.2453

## Task 1, 53 bytes

```
[ '[ [ _ /mod , ] until-zero ] f make 2 p^ supremum ]

```

Attempt This Online!

## Task 2, 66 bytes

```
[| s | s s s 2 clump [ <regexp> s re-replace ] each count-subseq ]

```

Attempt This Online!

I didn't expect Factor to score particularly well here since it's pretty consistent in most areas. Now if it were iterative vs. recursive, you might see Factor reigning supreme...

P.S. I was able to knock 12 bytes off one of the answers after posting, so FML.

# Answer
> 5 votes
# Numbers, PARI/GP 2.13.4, score 77 / 37 = 2.0811

## Task 1, 37 bytes

```
n->b->vecmax(Vec(Pol(digits(n,b))^2))

```

Attempt This Online!

PARI/GP has a built-in polynomial type.

## Task 2, 77 bytes

```
s->u=strjoin;v=strsplit;for(i=2,#t=s,t=u(v(t,u(Vec(s)[i-1..i])),s));#v(t,s)-1

```

Attempt This Online!

PARI/GP has only two string-manipulation built-ins: `strjoin` and `strsplit`. We can do string search-and-replace by `strjoin(strsplit(s,a),b)`.

# Answer
> 3 votes
# Numbers, Mathematica 13.1.0, score ~~1.26315~~ 1.47826

+0.2151 score thanks to att!

## Task 1, ~~57~~ 46 bytes

```
Max@ListConvolve[#,#,{1,-1},0]&@*IntegerDigits

```

Try it online!

-11 bytes thanks to att

## Task 2, ~~72~~ 68 bytes

```
Fold[StringReplace,x=#,#->x&/@StringPartition[x,2,1]]~StringCount~x&

```

Try it online!

-4 bytes thanks to att

# Answer
> 3 votes
# Strings, 05AB1E, score 15/9 = 1.666...

## Task 1, 15 bytes

```
вDδ*εā_«NFÁ]øOà

```

Try it online.

## Task 2, 9 bytes

```
ü2I.:I¡g<

```

Try it online.

05AB1E lacks any polynomial builtins, and unfortunately also a matrix-diagonals builtin. So all things considering, the Numbers Task 1 isn't too long, if I say so myself.

No doubt someone still finds something to golf, since that's usually the case with my answers. ;)

# Answer
> 3 votes
# Numbers, Vyxal 2.17.1, score 9/8 = 1.125

Vyxal doesn't do very well for this challenge.

## Task 1, 8 bytes

```
τ:v*ÞḋṠG

```

Try it Online!

## Task 2, 9 bytes

```
2l(n?V)$O

```

Try it Online!

# Answer
> 2 votes
# Numbers, Jelly, score 13/5 = 2.6

## Task 1, 5 bytes

```
bæc`Ṁ

```

Try it online!

## Task 2, 13 bytes

```
ṡ2œṣj³ɗƒœṣ¹L’

```

Try it online!

It's common knowledge that Jelly is not good with strings, but this is exceptionally awkward for its builtin set with some chaining issues on top. Maybe I'll get robbed?

# Answer
> 2 votes
# Numbers, J 806, Score 48 / 23 = 2.08696

## Task 1, 23 bytes

```
[:>./[:+//.@:(*/)~#.inv

```

Try it online!

## Task 2, 48 bytes

```
#%~;&''(]-&#rplc~)[:;<rplc~&.>/@|.@,<<"1@,.~2<\]

```

Try it online!

Strings might have an open window or two for an enterprising robber...

# Answer
> 2 votes
# Numbers, Charcoal, score 23 / 19 = 1.21

## Task 1, 19 bytes

```
ＮθＮηＩ⌈↨Ｘ↨↨θη×θη²×θη

```

Try it online! Link is to verbose version of code. Explanation: Based on @dingledooper's Python answer but using Charcoal's base conversion builtins to simplify the process.

## Task 2, 23 bytes

```
ＳηＦＥΦθκ⁺§θκι≔⪫⪪ηιθηＩ№ηθ

```

Try it online! Link is to verbose version of code. Explanation: Charcoal struggles to extract overlapping substrings, and like PARI/GP, has to use both Split and Join to perform string replacement. It does at least have a convenient way to refer to the same string input twice.

# Answer
> 2 votes
# Strings, Go 1.19.1, score ~~177 / 162 = 1.09259~~ 176 / 121 = 1.41322

## Task 1: ~~177~~ 176 bytes

```
func n(n,b int)int{c,m:=[]int{},-1
for n>0{c=append(c,n%b)
n/=b}
s:=make([]int,len(c)*2)
for i,x:=range c{for j,y:=range c{s[i+j]+=x*y}}
for _,n:=range s{if m<n{m=n}}
return m}

```

Attempt This Online!

* -1 by @Steffan

## Task 2: ~~162~~ 121 bytes

```
import."strings"
func s(s string)int{p,t:=s,s
for _,c:=range s{q:=string(c);t=ReplaceAll(t,p+q,s);p=q}
return Count(t,s)}

```

Attempt This Online!

* -41 by @Steffan

# Answer
> 1 votes
# Numbers, Pyxplot 0.8.4, score 188/99 = 1.8990

## Task 1, 99 bytes

```
su N(n,b){m=0
fo j=0ton{s=0
fo i=0ton{f='floor(n/b*'
s=s+@f*i)%b*@f*j*b**i)%b
}
m=max(m,s)
}
pr m
}

```

The algorithm is the same as in @dingledooper's answer.

## Task 2, 188 bytes

```
su S(s){t=s
L='strlen'
r='strrange'
fo i=2to@L(s){j=0
c=0
while j<@L(t){if strcmp(@r(t,j,j+2),@r(s,i-2,i)){j=j+1
}else{t='%s%s%s'%(@r(t,0,j),s,@r(t,j+2,@L(t)));j=j+@L(s);c=c+1
}
}
}
pr c
}

```

Pyxplot has a search-and-replace operator (`=~`) but it only works with literal text and so is not of use here. There are only five string manipulation functions (two of which perform case conversions). The three used here are `strcmp`, which performs lexicographical comparison; `strlen`, which returns the length; and `strrange`, which returns a slice.

---

There is no online interpreter. To install Pyxplot 0.8.4 on an up-to-date system, you need to add `-fgnu89-inline` to the compile flags in line 44 of `Makefile.skel`. You might also need to change `python` to `python2` or `python2.X` in lines 97, 180, and 183.

---
Tags: string, number, code-challenge
---


title: I'm Blue, Da ba dee da ba die

text:
# Question
Title: I'm Blue, Da ba dee da ba die
Write a program, which outputs `I'm Blue,`  and then `Da, Ba, Dee, Da, Ba, Die,`  forever, **the words must be space-seperated in one line, and it must pause 0.4 to 0.6 seconds after printing each word.** Also, the text should be outputted in the color blue 0x0000FF or in ANSI escape code blues.

So the output must be something like this:

You can use any programming language you want. The output can be in either text or image form (escape codes allowed!).

This is , so shortest program in bytes wins!

# Answer
> 2 votes
# 05AB1E, ~~46~~ 45 bytes

```
27ç"ÿ[34mI'm"?…žå°êèÞ#5∍'—ÇªÞ'‡—š',«™1úε₄;.W?

```

Uses an ANSI escape code to print in blue (which is `rgb(0,55,218)` in Windows 10 by default \- see screenshot below - but could be changed to the required `rgb(0,0,255)` in the console properties itself if necessary).

Try it online (with the sleep `₄;.W` removed).

*Screenshot:*

**Explanation:**

```
27ç             # Push 27, and convert it to a character with this codepoint: <ESC>
   "ÿ[34mI'm"   # Push this string, where `ÿ` is filled with the earlier <ESC> character
             ?  # Pop and print it (without newline)
…žå°êèÞ         # Push dictionary string "da ba dee"
       #        # Split it on spaces: ["da","ba","dee"]
        5∍      # Extend it to size 5: ["da","ba","dee","da","ba"]
          '—Ç  '# Push dictionary string "die"
             ª  # Append it to the list: ["da","ba","dee","da","ba","die"]
Þ               # Cycle this list indefinitely:
                #  ["da","ba","dee","da","ba","die","da","ba","dee","da",...]
 '‡—           '# Push dictionary string "blue"
    š           # Prepend it in front of the infinite list
     ',«       '# Append a comma to each string
        ™       # Titlecase each word
         1ú     # Prepend a leading space to each string
ε               # Foreach over the list:
 ₄;             #  Push 500 (push 1000 and halve it)
   .W           #  Pop and sleep that many millisecond
     ?          #  Print the string (without newline)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `…žå°êèÞ` is `"da ba dee"`; `'—Ç` is `"die"`; and `'‡—` is `"blue"`.

# Answer
> 2 votes
# HTML + JavaScript (All Browsers), ~~30 + 77 = 107~~ ~~24 + 90 = 114~~ 24 + 87 = 111 bytes

```
i=5
setInterval(a=>b.append("Da0Ba0Dee0Da0Ba0Die0Blue".split(0)[(i<6)+i++%6]+", "),500)
```

```
<body id=b text=blue>I'm
```

---

+7 because the original code didn't match the spec.
-3 from @jdt for using `.append(...)` instead of `.innerHTML+=...`

# Answer
> 1 votes
# HTML + JavaScript, ~~22~~ 18 + ~~90~~ ~~89~~ ~~88~~ 86 = 104 bytes

```
setInterval("b.append(`${'Da Ba Dee Da Ba Die Blue'.split` `[i++%7]}, `);i%=6",i=419)
```

```
<a href=# id=b>I'm
```

-6 bytes: use `.append()` instead of `.before()`, use `setInterval` string eval (from @jdt)

# Answer
> 1 votes
# Python 3, 135 bytes

```
import time
def f(l):[print(end=i+' ')==time.sleep(.5)for i in l.split()]
f("\033[34mI'm Blue,")
while 1:f("Da, Ba, Dee, Da, Ba, Die,")

```

Works on Windows Command Prompt

Try it online!

# Python 3, 145 bytes

```
import time
def f(l):[print(end=i+' ',flush=1)==time.sleep(.5)for i in l.split()]
f("\033[1;34mI'm Blue,")
while 1:f("Da, Ba, Dee, Da, Ba, Die,")

```

Works on MacOS iTerm

Try it online!

-8 thanks to 97.100.97.109

# Python 3, 196 bytes

```
from time import*;from itertools import*
p=print;s=sleep
p(end="\033[1;33mI'm ",flush=1);s(.5)
p(end="Blue, ",flush=1)
for i in cycle(['Da','Ba','Dee','Da','Ba','Die']):s(.5);p(end=i+', ',flush=1)

```

Works on MacOS iTerm

Try it online!

---

Note: on TIO, colours aren't shown, and everything gets shown when the program finishes. Here is a video of this running on another editor:

# Answer
> 1 votes
# Python 3 + `colorama`, ~~177 176 175 167 166 162~~ 160 bytes

I used `colorama` when I was interested in coloring `stdout`, and it certainly should help here!

(Also used because The Thonnu's answer was really long)

```
import colorama,time;colorama.init()
def m(n):[print(end=i+" ")==time.sleep(.5)for i in n.split()]
m("\033[34mI'm Blue,")
while 1:m("Da, Ba, Dee, Da, Ba, Die,")

```

## How to use:

As The Thonnu pointed out, this program fails on TIO, so to execute it:

1. Download IDLE (if you don't have it)
2. Open your terminal
3. Type `py -m pip install colorama`
4. Create a new file
5. Copy the code
6. Save it (here it will be `colored.py`)
7. Type `py -m colored` (or whatever you saved the file as without the `py` part) on your terminal.

See this video that shows it being done.

## Direct downloading version, 223 bytes:

Will download `colorama` from pip and executes.

```
import os,time
os.system("py -mpip install colorama")
import colorama;colorama.init
m=lambda n:print(end="\033[34m"+n)or time.sleep(.5)
m("I'm ");m("Blue, ")
while 1:
    for i in['Da','Ba','Dee','Da','Ba','Die']:m(i+", ");

```

## Non-Windows version, 135 bytes:

On windows platforms, Colorama is required for initializing the terminal. Other ones, don't think so.

```
import time
def m(n):[print(end=i+' ')==time.sleep(.5)for i in n.split()]
m("\033[34mI'm Blue,")
while 1:m("Da, Ba, Dee, Da, Ba, Die,")

```

# Answer
> 0 votes
## Batch, 148 bytes

```
@set/p=␛[94mI'm <nul
@call:c Blue
:l
@for %%i in (Da Ba Dee Da Ba Die) do @call:c %%i
@goto l
:c
@ping 192.512 -n 1 -w 500>nul
@set/p=%1, <nul

```

Note:  represents the Escape character (`^[`). Explanation:

```
@set/p=␛[94mI'm <nul

```

Set the text colour to bright blue and write the initial `I'm`  without starting a new line.

```
@call:c Blue

```

Start with the word `Blue`.

```
:l
@for %%i in (Da Ba Dee Da Ba Die)do @call:c %%i
@goto l

```

Loop over the remaining words, and then repeat indefinitely.

```
:c
@ping 192.512 -n 1 -w 500>nul
@set/p=%1, <nul

```

Wait `500ms`, and then output the word with a trailing `,`  without starting a new line. `192.512` is a reserved IP address and it should not be possible to ping it, so the ping will time out after `0.5s` as desired.

---
Tags: code-golf, graphical-output, color
---


title: Convert a string to sentence case

text:
# Question
Title: Convert a string to sentence case
**Input:**

A string (or the closest thing to that in your language)

**Output:**

The same string but converted to sentence case

**Rules:**

* For this challenge, sentence case can be considered "`The first letter of each sentence is capitalized. The rest are lowercase.`" (i.e. proper nouns do not have to be capitalized)
* If the input does not include a period, it is treated as one sentence.
* The other 2 punctuation marks used to end a sentence in english (`?` and `!`) can be considered periods
* If a letter immediately follows a punctuation mark the same rules still apply (i.e. the first letter is capitalized and all following letters are lowercased until the next punctuation mark)

**Sample test cases:**

```
"hello world." // "Hello world."

"CODEGOLF IS FUN." // "Codegolf is fun."

"no period" // "No period"

"the ball was red. so was the balloon." // "The ball was red. So was the balloon."

"I love codegolf.stackexchange.com" // "I love codegolf.Stackexchange.Com"

"heLLo! hOW are yOU toDay? hOpEfulLy yOu are okay!" // "Hello! How are you today? Hopefully you are okay!"

```

**This is , so the shortest code wins!**

# Answer
> 8 votes
# 05AB1E, 3 bytes

```
l.ª

```

Try it online!

Nothing like a good old built-in answer! This converts the string to lowercase and then performs sentence case.

# Answer
> 5 votes
# Vyxal, 1 byte

```
¡

```

Try it Online!

"Nothing like a good old built-in answer!" I suppose not younger lyxal, I suppose not.

Alternatively, a non-trivial 24 byte answer:

```
`([.?!])`ṡλ⇩⌈:Th~iǐȦṄ;Ẇṅ

```

Try it Online!

## Explained

```
`([.?!])`ṡλ⇩⌈:Th~iǐȦṄ;Ẇṅ
`       `ṡ               # Split the input on the regex "[.?!]", keeping the thing that causes splits (wrapping something in `()` when regex splitting keeps it in the split list)
          λ          ;Ẇ  # To each second item of that list (guaranteed to not be punctuation), starting at index 0:
           ⇩⌈             #   Split the lowercase version of the string on spaces
             :Th~i        #   Get the first word by getting the first truthy index in the splitted string (because it may contain `""`s) and get the item at that index
                  ǐȦṄ     #   Replace the word at that index with a title-cased version of the string, and join the list on spaces.
                      ṅ   # Join the result on nothing

```

# Answer
> 3 votes
# Python 3, 67 bytes

*-7 bytes thanks to Surculose Sputum*

If other punctuation like `!` or `?` are allowed.

```
lambda s:re.sub(r'\w[\w ]+',lambda x:x[0].capitalize(),s)
import re

```

Try it online!

---

# Python 2, 53 bytes

```
lambda s:'. '.join(map(str.capitalize,s.split('. ')))

```

Try it online!

# Answer
> 3 votes
# Erlang (escript), 77 bytes

If non-periods are allowed... well, that greatly golfs my program!

```
g(H)->[string:titlecase(string:lowercase(I))||I<-re:split(H,"(\\W[\\W ]+)")].

```

Try it online!

## Explanation

```
g(H)->                      % Define a function.

re:split(H,"(\\W[\\W ]+)")  % Split the operand on "sentences", keeping the items reserved for splitting.

                            % I.e. none of the items from the string is missing after the split

||I<-   ]                   % For every item in a sentence,
[string:titlecase(string:lowercase(I))

                            %     Title case the sentence.
.                           % End the function.

```

# Answer
> 3 votes
# JavaScript (Node.js), 101 bytes

```
s=>(s.reduce((a,c)=>c=='.'?(r+=c,'Upp'):c>' '?(r+=c['to'+a+'erCase'](),'Low'):(r+=c,a),'Upp',r=''),r)

```

Try it online!

# Answer
> 3 votes
# C (gcc), <sup>~~80~~ \\$\cdots\\$ ~~87~~</sup> 76 bytes

Added 13 bytes to fix a bug kindly pointed out by Abigail.

```
c;b;f(char*s){for(b=1;c=*s;b|=ispunct(c))*s++=isalpha(c)?b?b=0,c&95:c|32:c;}

```

Try it online!

**How**

Capitalises the first letter and every letter after a punctuation mark. Every other letter is converted to lower case. Simply prints everything else.

# Answer
> 3 votes
# Retina, 13 bytes

```
.+
$T
\b .
$L

```

Try it online!

## Explanation

General approach is to convert every word to title-case, then un-convert the words that shouldn't have been converted

`.+` Matches the entire string, `$T` converts it to title case (every word lowercase with an uppercase first character

`\b .` \- `\b` Matches the position between a word-character and a non-word character (i.e. the end of a word without a full stop) followed by a space and any other character `.`

`$L` converts this to lowercase

# Answer
> 3 votes
# perl -p, 33 bytes

```
$_=lc=~s/(^|\pP)\s*\K\pL/uc$&/erg

```

Try it online!

This lowercases the string, then upper cases any letter following either the beginning of the string, or after a punctuation character (skipping any whitespace in between). This does turn a string `"foo, bar, baz"` into `"Foo, Bar, Baz"`, but that's how I read the requirement about all punctuation.

# Answer
> 3 votes
# Python 3, 117 bytes

```
import re
f=lambda s:''.join(map(lambda p:re.sub(r'[a-z]',lambda m:m[0].upper(),p.lower(),1),re.split(r'([.?!])',s)))

```

Try it online!

For some reason, I made a solution that handles a few extra test cases that OP may or may not have cared about :) This is much longer than the current shortest Python solution, but I'd be sad to just throw this code away, so here it is!

Extra test cases:

```
"a.b.c" //  "A.B.C"
(no space after punctuation)

"hello.  goodbye" // "Hello.  Goodbye"
(more than one space after punctuation)

"I'M A ROBOT" // "I'm a robot"
(punctuation other than sentence terminator)

```

Commented solution:

```
f = (
  lambda string:
    ''.join(map(

      # Capitalize first letter in part
      lambda part: re.sub(
        r'[a-z]',
        lambda match: match[0].upper(),
        part.lower(),
        1
      ),

      # Split on punctuation
      re.split(r'([.?!])',string)

    ))
)

```

# Answer
> 3 votes
# Go, 192 bytes

```
import(y"bytes";."regexp";u"unicode")
type k=[]byte
func f(s k)k{return MustCompile(`\w[\w ]+`).ReplaceAllFunc(s,func(b k)k{return append(k{byte(u.ToUpper(rune(b[0])))},y.ToLower(b[1:])...)})}

```

A port of @dingledooper's answer.

Attempt This Online!

# Answer
> 2 votes
# Retina 0.8.2, 19 bytes

```
T`L`l
T`l`L`^.|\W .

```

Try it online! Link includes test cases. Explanation:

```
T`L`l

```

Lowercase everything.

```
T`l`L`^.|\W .

```

Uppercase the first character and any character that follows a non-word character and a space. It might not be the world's best heuristic but it works on the test case.

# Answer
> 2 votes
# Red, 81 bytes

```
func[s][parse lowercase s[any[any" "p: change skip(p/1 - 32)thru["."|"!"|"?"]]]s]

```

Try it online!

# Answer
> 2 votes
# Vim, ~~20~~ 19 bytes

*Saved 1 byte by using `~` to toggle casing instead of `vU`.*

```
v$uqq~/[.!?]
w@qq@q

```

Try it online!

Explanation:

```
v$u                 # Selects whole line and changes it to lowercase
   qq               # Starts recording macro q
     ~              # Toggles uppercase on current character
      /[.!?]        # Jumps to next . ! or ?
            w       # Jumps to next non-whitespace character
             @q     # Calls macro q recursively
               q@q  # Ends macro q and calls it

```

# Answer
> 2 votes
# Japt, 14 bytes

```
v r"^.|%W ."_u

```

Try it

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


title: The Double's Base

text:
# Question
Title: The Double's Base
# Background

IEEE 754 Double-precision floating-point format is a way to represent real numbers with 64 bits. It looks like the following:

A real number `n` is converted to a `double` in the following manner:

1. The sign bit `s` is 0 if the number is positive, 1 otherwise.
2. The absolute value of `n` is represented in the form `2**y * 1.xxx`, i.e. a *power-of-2* times a *base*.
3. The exponent `e` is `y` (the power of 2) plus 1023.
4. The fraction `f` is the `xxx` part (fractional part of the base), taking the most significant 52 bits.

Conversely, a bit pattern (defined by sign `s`, exponent `e` and fraction `f`, each an integer) represents the number:

```
(s ? -1 : 1) * 2 ** (e - 1023) * (1 + f / (2 ** 52))

```

# Challenge

Given a real number `n`, output its 52-bit fraction part of the `double` representation of `n` as an integer.

# Test Cases

```
0.0        =>                0
16.0       =>                0
0.0625     =>                0
1.2        =>  900719925474099 (hex 3333333333333)
3.1        => 2476979795053773 (hex 8cccccccccccd)
3.5        => 3377699720527872 (hex c000000000000)
10.0       => 1125899906842624 (hex 4000000000000)
1234567.0  =>  798825262350336 (hex 2d68700000000)
1e-256     => 2258570371166019 (hex 8062864ac6f43)
1e+256     => 1495187628212028 (hex 54fdd7f73bf3c)

-0.0       =>                0
-16.0      =>                0
-0.0625    =>                0
-1.2       =>  900719925474099 (hex 3333333333333)
-3.1       => 2476979795053773 (hex 8cccccccccccd)
-3.5       => 3377699720527872 (hex c000000000000)
-10.0      => 1125899906842624 (hex 4000000000000)
-1234567.0 =>  798825262350336 (hex 2d68700000000)
-1e-256    => 2258570371166019 (hex 8062864ac6f43)
-1e+256    => 1495187628212028 (hex 54fdd7f73bf3c)

```

You can check other numbers using this C reference which uses bit fields and a union.

Note that the expected answer is the same for `+n` and `-n` for any number `n`.

# Input and Output

Standard rules apply.

Accepted input format:

* A floating-point number, at least having `double` precision internally
* A string representation of the number in decimal (you don't need to support scientific notation, since you can use `1000...00` or `0.0000...01` as input)

For output, a rounding error at the least significant bit is tolerable.

# Winning Condition

This is , so the lowest bytes in each language wins.

# Answer
> 8 votes
# C (gcc), ~~42~~ 30 bytes

```
long f(long*p){p=*p&~0UL>>12;}

```

Takes a pointer to a *double* as argument and returns a *long*.

Requires 64-bit longs and gcc (undefined behavior).

*Thanks to @nwellnhof for -2 bytes!*

Try it online!

# Answer
> 6 votes
## Haskell, ~~27~~ 31 bytes

```
(`mod`2^52).abs.fst.decodeFloat

```

`decodeFloat` returns the significand and the exponent, but for some reason the former is 53 bit in Haskell, so we have to cut one bit off.

Try it online!

# Answer
> 5 votes
# MATL, 10 bytes

```
IZ%52W\0YA

```

Try it online!

### Explanation

```
        % Implicit input
IZ%     % Cast to uint64 without changing underlying byte representation
52W     % Push 2^52
\       % Modulus
0YA     % Convert to decimal. Gives a string. This is needed to avoid
        % the number being displayed in scientific notation
        % Implicit display

```

# Answer
> 5 votes
# Python 3, ~~54~~ 50 bytes

```
f=lambda x:int(x.hex().split('.')[1].split('p')[0],16)

```

Try it online!

With Kirill's suggestion:

```
f=lambda x:int(x.hex()[4+(x<0):].split('p')[0],16)

```

Try it online!

# Answer
> 5 votes
# x86\_64 machine language for Linux, 14 bytes

```
0:       66 48 0f 7e c0          movq   %xmm0,%rax
5:       48 c1 e0 0c             shl    $0xc,%rax
9:       48 c1 e8 0c             shr    $0xc,%rax
d:       c3                      retq

```

Try it online!

EDIT: Thanks to @Bubbler

# Answer
> 4 votes
## JavaScript (ES7), ~~52~~ 50 bytes

```
f=n=>n?n<0?f(-n):n<1?f(n*2):n<2?--n*2**52:f(n/2):0
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>0
```

Not using `Math.floor(Math.log2(n))` because it's not guaranteed to be accurate. Edit: Saved 2 bytes thanks to @DanielIndie.

# Answer
> 3 votes
# Perl 5 `-pl`, 28 bytes

```
$_=-1>>12&unpack Q,pack d,$_

```

Try it online!

The 1e-256 and 1e256 test cases are off but that's because Perl 5 converts huge or tiny floating point strings inexactly.

# Answer
> 2 votes
# JavaScript (ES7), ~~98~~ 76 bytes

*Saved 22 (!) bytes thanks to @Neil*

More verbose than Neil's answer, but I wanted to give it a try with typed arrays.

```
(n,[l,h]=new Uint32Array(new Float64Array([n]).buffer))=>(h&-1>>>12)*2**32+l

```

Try it online!

# Answer
> 2 votes
# C (gcc) macro, 49 bytes

```
-DF(x)=x?ldexp(frexp(fabs(x),(int[1]){})-.5,53):0

```

Try it online!

Returns a `double` but assuming IEEE precision, it won't have a fractional part. Also handles negative numbers now.

# Answer
> 2 votes
# T-SQL, 80 bytes

```
SELECT CAST(CAST(n AS BINARY(8))AS BIGINT)&CAST(4503599627370495AS BIGINT)FROM t

```

The input is taken from the column `n` of a table named `t`:

```
CREATE TABLE t (n FLOAT)
INSERT INTO t VALUES (0.0),(1.2),(3.1),(3.5),(10.0),(1234567.0),(1e-256),(1e+256)

```

SQLFiddle

# Answer
> 2 votes
## Hoon, 25 bytes

```
|*(* (mod +< (pow 2 52)))

```

Create a generic function that returns the input mod `2^52`.

Calling it:

```
> %.  .~1e256
  |*(* (mod +< (pow 2 52)))
1.495.187.628.212.028

```

# Answer
> 2 votes
# Stax, ~~19~~ 14 bytes

```
üâïc-Hò~÷]ó┬ó♪

```

Run and debug it

Unpacked, ungolfed, and commented, the code looks like this.

```
|a      absolute value
{HcDw   double until there's no fractional part
@       convert to integer type
:B      convert to binary digits
D52(    drop the first digit, then pad to 52
:b      convert back number

```

Run this one

# Answer
> 2 votes
# APL (Dyalog), 38 bytes

```
{0=⍵:0⋄(2*52)×¯1+×∘2⍣(1≤⊣)÷∘2⍣(1>⊣)|⍵}

```

Try it online!

# Answer
> 1 votes
# Rust, 21 bytes

```
|p|p.to_bits()&!0>>12

```

Pretty much copied C solution. Takes an `f64` argument.

Try it online!

# Answer
> 1 votes
# Forth (gforth), 42 bytes

Assumes floats are double by default and cells are 8 bytes in length (as is the case on my computer and TIO)

```
: f f, here float - @ $fffffffffffff and ;

```

Try it online!

## Explanation

```
f,             \ take the top of the floating point stack and store it in memory
here float -   \ subtract the size of a float from the top of the dictionary
@              \ grab the value at the address calculated above and stick it on the stack
$fffffffffffff \ place the bitmask (equivalent to 52 1's in binary) on the stack
and            \ apply the bitmask to discard the first 12 bits

```

# Forth (gforth) 4-byte cell answer, 40 bytes

Some older forth installations default to 4-byte cells, instead

```
: f f, here float - 2@ swap $FFFFF and ;

```

## Explanation

```
f,             \ take the top of the floating point stack and store it in memory
here float -   \ subtract the size of a float from the top of the dictionary
2@             \ grab the value at the address above and put it in the top two stack cells
swap           \ swap the top two cells put the number in double-cell order
$fffff         \ place the bitmask (equivalent to 20 1's in binary) on the stack
and            \ apply the bitmask to discard the first 12 bits of the higher-order cell

```

# Answer
> 1 votes
# Go, 68 bytes

```
import."math"
func d(n float64)uint64{return Float64bits(n)<<12>>12}

```

Can't do the `&-1` trick because Go disallows overflows.

Attempt This Online!

# Answer
> 0 votes
# Ruby, 39 bytes

```
->n{[n].pack(?D).unpack(?Q)[0]&~-2**52}

```

Try it online!

# Answer
> 0 votes
# Java 8 or later, 38 bytes

```
x->Double.doubleToLongBits(x)&-1L>>>12

```

Try it online!

# Answer
> 0 votes
# Aarch64 machine language for Linux, 12 bytes

```
0:   9e660000        fmov x0, d0
4:   9240cc00        and  x0, x0, #0xfffffffffffff
8:   d65f03c0        ret

```

To try this out, compile and run the following C program on any Aarch64 Linux machine or (Aarch64) Android device running Termux

```
#include<stdio.h>
const char f[]="\0\0f\x9e\0\xcc@\x92\xc0\3_\xd6";
int main(){
  double io[] = { 0.0,
                  1.2,
                  3.1,
                  3.5,
                 10.0,
            1234567.0,
               1e-256,
               1e+256,
                 -0.0,
                 -1.2,
                 -3.1,
                 -3.5,
                -10.0,
           -1234567.0,
              -1e-256,
              -1e+256 };

  for (int i = 0; i < sizeof io / sizeof*io; i++) {
    double input = io[i];
    long output = ((long(*)(double))f)(io[i]);

    printf("%-8.7g => %16lu (hex %1$013lx)\n", input, output);
  }
}

```

# Answer
> 0 votes
# Julia 0.4, 30 bytes

```
x->reinterpret(UInt,x)<<12>>12

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 18 bytes

```
Ä[ÐïQ#·}b0₃×«À52£C

```

Port of *@recursive*'s Stax answer.

Try it online or verify all test cases.

Alternatively:

```
_+Ä[DbD53∍©›#·}®¦C

```

Try it online or verify all test cases.

Alternatively (by porting *@LucaCiti*'s Python answer in the legacy version of 05AB1E):

```
Ä".hex()"«.E„.p¡Hà

```

Try it online or verify all test cases.

**Explanation:**

```
Ä             # Get the absolute value of the (implicit) input-float
 [            # Start an infinite loop:
  Ð           #  Triplicate the current value
   ï          #  Cast the top to an integer
    Q         #  Check if the top two values are the same†
     #        #  If they are: stop the infinite loop
  ·           #  Double the current float
 }b           # After the loop: convert the integer to a binary string
   0₃×«       # Append 95 trailing 0s
              # (95 is the smallest single-byte constant >= 52)
       À      # Rotate it once towards the left, so the leading 1 becomes trailing
        52£   # Only keep the first 52 bits
           C  # Convert it from a binary string to a base-10 integer
              # (which is output implicitly as result)

```

```
_             # Check if the (implicit) input-float is 0
 +            # Add it to the (implicit) input-float so it becomes 1
  Ä           # Convert it to its absolute value
[             # Start an infinite loop:
 D            #  Duplicate the current value
  b           #  Convert its integer part to a binary string
   D          #  Duplicate this string
    53∍       #  Extend/shorten it to size 53
       ©      #  Store this result in variable `®`
        ›     #  Check if it's larger than the binary string
         #    #  If it is: stop the infinite loop
 ·            #  Double the current float
}®            # After the loop: push binary string `®` which we've saved
  ¦           # Remove its leading 1
   C          # Convert it from a binary string to a base-10 integer
              # (which is output implicitly as result)

```

```
Ä             # Get the absolute value of the (implicit) input-float††
 ".hex()"«    # Append string ".hex()"
          .E  # Evaluate and execute it as Python code
„.p¡          # Split it on both the "." and "p"
    H         # Convert each inner part from a hexadecimal string to an integer
     à        # Push the maximum of this list
              # (which is output implicitly as result)

```

† If 05AB1E didn't had this bug and the input format is also guaranteed to not contain any additional trailing `0` besides `#.0` (e.g. `12.0` is a valid input, but `12` or `12.10` aren't), the `DïQ` could have been `¤_` \- which checks if the float contains a trailing zero.

†† Unlike the Python answer, `.hex()` doesn't work on negative values in the legacy version of 05AB1E, unless I add parenthesis around it (e.g. `-1.0.hex()` doesn't work, but `1.0.hex()` and `(-1.0).hex()` both do: try it online), which is why the `Ä` was necessary in the third program.

---
Tags: code-golf
---


title: An Ant on a Cube

text:
# Question
Title: An Ant on a Cube
An ant walks along the edges (not faces) of a wireframe cube. Each vertex it encounters presents it with a fork from which two new edges branch off. The ant chooses which way to turn -- `left` or `right`. These direction are relative to the ant, who is facing the vertex and is outside the cube. Your goal is to determine, from the sequence of `left`/`right` choices the ant took, whether it ends at the same position that it started.

For example, if the ant turns left four times (`left left left left`), it will have traversed a square counterclockwise and ended at the same place it started. But, if it goes `left left left left right`, it will end on a different spot on the cube. Also, if it goes `left right right right left`, it ends on its starting edge but facing the opposite vertex, which does not count as the same position.

The ant's path might repeat edges, including the edge it started at, but what matters is where it ends after the whole sequence.

Write a *named function* that takes in the ant's sequence of turns and outputs whether the ant is back at its start position after the sequence. Assigning an unnamed function to a variable is enough to make it a named function.

(Edit: If your language can't make a named function, it can instead implement the function with inputs and outputs through STDIN/printing or the stack. If that's not possible, make it a snippet in which the input and output are saved in variables.)

**Input**

A sequence of `left`/`right` decisions of length `0` to `31` inclusive, represented in a format of your choice. This might be a string of letters `R`/`L`, a list of numbers `1`/`-1`, or an array of Booleans. Nothing cheesy like having them be method names or strings useful for your code.

Please post the test cases in your format if it's different from the test cases below.

**Output**

`True`/`False`, `0`/`1`, or the analogues in your language.

**Winning criteria**

Fewest bytes wins. Remember, you need to give a named function. You can have code outside the function, but those bytes count too. Your function should behave correctly if called multiple times.

**Test cases**

`True` cases (one per line, second one is empty list):

```
1 1 1 1

-1 -1 -1 -1
1 -1 1 -1 1 -1
1 1 -1 -1 1 1 -1 -1
-1 1 1 -1 -1 1 1 -1
1 1 1 -1 -1 -1 -1 1
1 -1 -1 1 -1 -1
1 1 1 1 -1 -1 -1 -1 1 -1 -1 1 -1 -1
-1 -1 -1 1 -1 -1 1 1 -1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

```

`False` cases (one per line):

```
1
1 1
1 1 1
-1 1
1 -1 -1 -1 1
1 -1 -1 1 1
-1 1 -1 1
1 1 1 1 -1
-1 -1 1 -1 1 -1 -1 1
1 -1 1 1 1 1 -1 -1 -1 1 1 -1 -1 -1

```

Here's the same test cases with `L`'s and `R`'s.

`True` cases:

```
RRRR

LLLL
RLRLRL
RRLLRRLL
LRRLLRRL
RRRLLLLR
RLLRLL
RRRRLLLLRLLRLL
LLLRLLRRLRLRRRRRRRRRRRRRRRRR

```

`False` cases:

```
R
RR
RRR
LR
RLLLR
RLLRR
LRLR
RRRRL
LLRLRLLR
RLRRRRLLLRRLLL

```

**Extra credit challenge**

Same thing, but with a dodecahedron rather than a cube. See Hunt the Wumpus for ideas.

# Answer
> 22 votes
# GolfScript, 24 chars (19 for function body only)

Math FTW!

```
{3,.@{[+~@\{@}*~]}/=}:f;

```

Test this solution online.

This function takes as input a binary array (0 for left, 1 for right) and returns 1 for true and 0 for false.

Conceptually, it works by rotating the *cube* so that the ant always maintains the same position and orientation, and checking whether the cube finally ends up in the same orientation as it began in.

In particular, we can represent the left and right turns as two linear maps in three dimensions, where a left turn corresponds to a 90° rotation around the *x* axis, i.e. the map (*x*, *y*, *z*) → (*x*, *z*, −*y*), and a right turn corresponds to a 90° rotation around the *y* axis, i.e. the map (*x*, *y*, *z*) → (*z*, *y*, −*x*).

At the beginning of the function, we simply set up a three-element vector containing the distinct positive values (1, 2, 3), apply the sequence of rotation maps to it, and check whether the resulting vector equals the initial one.

(In fact, to save a few chars, I actually transform the coordinates so that the initial vector is (0, 1, 2) and the maps are (*x*, *y*, *z*) → (*x*, *z*, −1−*y*) and (*x*, *y*, *z*) → (*z*, *y*, −1−*x*), but the end result is the same.)

Ps. Thanks to proud haskeller for spotting the bug in the original version of this solution.

---

# Perl, 58 chars

As requested in the comments, here's the same solution ported to Perl. (This version actually uses the untransformed coordinates, since the transformation saves no chars in Perl.)

```
sub f{@a=@b=1..3;@a[$_,2]=($a[2],-$a[$_])for@_;"@a"eq"@b"}

```

Test this solution online.

---

# Bonus: Ant on a Dodecahedron (GolfScript, 26 chars)

```
{5,.@{{2*2%[~\]}*(+}/=}:f;

```

Test this solution online.

Like the ant-on-a-cube function above, this function takes as input a binary array (0 for left, 1 for right) and returns 1 if the ant ends up at the same position and orientation as it started in, or 0 otherwise.

This solution uses a slightly more abstract representation than the cube solution above. Specifically, it makes use of the fact that the rotational symmetry group of the dodecahedron is isomorphic to the alternating group A5, i.e. the group of even permutations of five elements. Thus, each possible rotation of the dodecahedron (that maps edges to edges and vertices to vertices) can be uniquely represented as a permutation of a five-element array, with consecutive rotations corresponding to applying the corresponding permutations in sequence.

Thus, all we need to do is find two permutations *L* and *R* that can represent the left and right rotations. Specifically, these permutations need to be 5-cycles (so that applying them five times returns to the original state), they must not be powers of each other (i.e. *R**L**n* for any *n*), and they need to satisfy the relation (*LR*)5 = (1), where (1) denotes the identity permutation. (In effect, this criterion states that the path `LRLRLRLRLR` must return to the original position.)

Fixing the *L* permutation to be a simple barrel shift to the left, i.e. mapping (*a*, *b*, *c*, *d*, *e*) → (*b*, *c*, *d*, *e*, *a*), since it can be implemented in GolfScript in just two chars (`(+`), we find that there are five possible choices for the *R* permutation. Out of those, I chose the mapping (*a*, *b*, *c*, *d*, *e*) → (*c*, *e*, *d*, *b*, *a*), since it also has a relatively compact GolfScript implementation. (In fact, I implement it by first interleaving the elements with `2*2%` to obtain (*a*, *c*, *e*, *b*, *d*), then swapping the last two elements with `[~\]`, and finally applying the *L* permutation unconditionally to move *a* to the end.)

The online demo link above includes some test cases of valid paths on a Dodecahedron that return to the origin, such as:

```
           # empty path
1 1 1 1 1  # clockwise loop
0 0 0 0 0  # counterclockwise loop
1 0 0 0 0 1 1 0 0 0 0 1  # figure of 8
1 0 1 0 1 0 1 0 1 0      # grand circle
1 0 0 0 1 0 0 0          # loop around two faces
1 0 0 0 1 1 1 0 1 0 1 0 0 0 1 1 1 0 1 0  # Hamilton cycle

```

# Answer
> 7 votes
# Python, 68

Takes a list of 1 and -1. Based on 3D rotations: checks if the point (3,2,1) ends up at the same position after applying a series of rotations. There are two possible rotations, corresponding to 1 and -1. Each one is done by permuting two coordinates and changing the sign of one of them. The exact coordinates to change and which sign to permute is not important.

```
def f(l):
 p=[3,2,1]
 for d in l:p[d],p[0]=-p[0],p[d]
 return[3,2]<p

```

EDIT: this is actually mostly the same solution as "Perl, 58".

# Answer
> 5 votes
# Mathematica

Inspired by Ilmari Karonen's solution. The rotational symmetry group of a cube is isomorphic to S4.

## Cube, 51 bytes

```
Fold[Part,r=Range@4,{{2,3,4,1},{3,4,2,1}}[[#]]]==r&

```

Takes a list of `1`s and `-1`s as input.

Try it online!

## Dodecahedron, 55 bytes

```
Fold[Part,r=Range@5,{{2,3,4,5,1},{3,5,4,2,1}}[[#]]]==r&

```

Takes a list of `1`s and `-1`s as input.

Try it online!

# Answer
> 5 votes
# C (gcc), ~~118~~ ~~116~~ ~~107~~ 105 bytes

-2 bytes thanks to ceilingcat

```
f(char*s){char*p,n[]="@ABCDEFG",y;for(;*s;s++)for(p=n;*p;*p++^=*s^82?y%2+1:4-(y&2))y=*p/2^*p;y=n[2]==66;}

```

Try it online!

Suppose we gave the cube the following coordinates:

```
            (1,1,1)       (1,1,0)
          G +--------------+ C
           /|             /|
          / |            / |
         /  |    (0,1,0)/  |
(0,1,1) +--------------+ D |
      H |   |          |   |
        |   |          |   |
        | F +----------|---+ (1,0,0)
        |  /(1,0,1)    |  / B           x
        | /            | /           y /
        |/             |/            |/
      E +--------------+ A      z ---*
        (0,0,1)       (0,0,0)

```

If we start on corner D, then moving to C or H can be thought of as rotating the cube around us instead. Moving right would mean rotating counter-clockwise around the Z axis, and moving left would mean rotating clockwise around the X axis. These are the only two rotations we need to care about. Since each rotation is exactly 90 degrees, we can imagine the corners "sliding" along the edges. For moving right, this means A -\> B, B -\> C, C -\> D, D -\> A with the other side doing E -\> F etc. For moving left, we instead get A -\> E, E -\> H etc.

Since each corner only slides along an edge, that means only one of the dimensions of each point changes for each rotation. When B moves to C, only its y component changes, and when H moves to D, only its z component changes, and so on. Furthermore, since the coordinates are restricted to 0 and 1, we can think of each point as a binary number, with the appropriate bit flipped upon movement.

We can see that for a movement to the right, A and C flip their x's, while D and B flip their y's. If we change perspective to look on that side of the cube head on, and ignore the z component (which does not change for this rotation anyway) we get:

```
D (0,1)         C (1,1)
 +-------------+
 |             |
 |             |
 |             |
 |             |
 |             |
 |             |
 +-------------+
A (0,0)         B (1,0)

```

A pattern emerges: For the points that flip their x, x == y, while the opposite is true for the points flipping their y's. This holds for the other type of rotation, but with z instead of x.

In other words:

```
Right
    if (x == y) x = !x
    if (x != y) y = !y

Left
    if (z == y) z = !z
    if (z != y) y = !y

```

Now we can easily go through all the rotations, and at the end see if the final D matches our initial D.

Storing each point as a single number is a given, but in C, assigning a char array is that much more compact than an int array. We take care to choose characters whose lower three bits match 000..111, making it possible to just ignore the rest of the bits. Flipping the coordinates is simply a matter of XOR'ing with the appropriate bitmask.

# Answer
> 4 votes
## Python - 110, 150

Takes in a list of integers with `-1` for turn left, `1` for turn right.

**Cube, 110:**

```
def f(l):
    c,p='07'
    for d in l:a="100134462634671073525275"[int(c)::8];c,p=a[(a.index(p)+d)%3],c
    return'1'>c

```

**Test:**

```
l=map(int,'1 1 1 1'.split())
print f(l)

```

**Dodecahedron, 150:**

```
def f(l):
    c,p='0J'
    for d in l:a="I5H76E8BBA8F76543100JI0J21D3A5C7E9CJI2132H4GF94C6D98AHGBEDGF"[int(c,36)::20];c,p=a[(a.index(p)+d)%3],c
    return'1'>c

```

# Answer
> 4 votes
# Marbelous 188

Shameless theft of Ilmari Karonen's algorithm for the purpose of showing off a new language.

This script expects a string of 0x00 for left and 0x01 for right on stdin, followed by a 0x0A (newline). It outputs "0" for a failed case and "1" for a success.

```
......@5@3FF
@0@1@2\\]]@5
010203@4=A@4
&0&0&0&0/\
MVMVMVMV..
@0@1@2@3..!!
:MV
}2}2}1}0}1}0}3
&0&1&0&1~~~~<A@P
{0{1{1{0&1&0=0&1
}0}1}2@P{2{2&030
=1=2=3&2FF}3..//
&2&2&231&2{3
\/\/\/&2!!..//

```

example run:

```
# echo -e "\x0\x0\x0\x1\x0\x0\x1\x1\x0\x1\x0\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1" | marbelous.py ant-on-a-cube.mbl
1

```

# Answer
> 4 votes
# Python 2, 57 bytes

```
f=lambda l:reduce(lambda n,x:n%4*64+n/4*16**x%63,l,27)<28

```

Try it online!

This uses the permutation representation

```
0: abcd -> dabc
1: abcd -> dcab

```

where left and right (0 and 1) correspond to length-4 cycles on 4 elements. We iterate over the input applying the indicated permutation, and check if the outcome equals the initial value.

We start `a,b,c,d` as the four-element list `0,1,2,3`. We compact them into a single base-4 number `n=abcd`, with initial value `n=27` corresponding to `0123` in base 4. We instantiate each the permutation arithmetically on `n`.

Since both results start with `d`, we can do `n%4` to extract `d`, then `n%4*64` to move it into the right position `d___`. The other digits are `abc`, extracted as `n/4`. We need to insert them into the lower three place values.

For direction `x=0`, we insert `abc` as is, and for `x=1`, we rotate them as `cab`. The rotation can be achieved as `*16%63`, which takes `abc` to `abc00` to `cab`. (The `%63` would go wrong on `a==b==c==3`, but these value aren't possible.) Since just doing `%63` is a no-op, the direction-dependent expression `*16**x%63` gives `abc` or `cab` as required.

---

# Python 2, 55 bytes

```
f=lambda l:reduce(lambda n,x:n^(n*8%63|7*8**x),l,10)<11

```

Try it online!

# Answer
> 3 votes
# Haskell, 104 103 ~~99~~ ~~97~~ 96 / ~~67~~ 64 chars

I feel the equivalent of right/left would be a datatype Direction like so:

```
Direction = R | L

```

so I assumed in my answer that they were available.
**edit:** actually realized that booleans would lead to shorter code. True represents a left turn, and False represents a right turn (although, technically, the code would work the same if it was flipped; it's symmetric)

96 characters:

```
m[p,l,r]b|b=[p%l,7-r-l,r]|0<1=[p%r,l,7-r-l]
p%x|odd$div p x=p-x|0<1=p+x
g l=foldl m[0..2]l<[0,2]

```

g is a function that given a list of Direction would return weather of not the ant got back to its place.

**explanation of representation of position:** the position of the ant is coded as a three tuple of integers. the first integer represents the vertex that the ant is heading to. the first bit represents if the vertex is at the up/down half, the second is the left/right half, and the third is the back/front half. this is done so that moving from a vertex to a neighbor vertex can be done by flipping one bit.

the second integer is the amount that the ant's vertex would change if it would go left. for example, if the ant was at vertex 3, and the second integer was 4, than after turning left the vertex would be 7. note this would always be a power of 2, because exactly one bit is flipped by moving one vertex.

the third integer is the same, but for going right; i know this is can be calculated by the first two, but i don't know how to. if you got an idea, please tell me.

something to note is that when turning left, the third integer would stay the same, and the second would become the one between 1 2 and 4 that wasn't either the second integer or the third, which happens to be the same as 7 - second integer - third integer.

i chose this way of representing position because (as was just stated in the previous paragraph) it was trivial to compute the next position.

**explanation of functions:**

the (%) function is the function that takes the current vertex and the amount to change it, and changes it. it gets to the bit that is going to change and flips it (in a very numeric way).

the m function is a function that takes the position of the ant, and the direction, and returns the new position by using the note we noted earlier.

then the m function is combined using foldl (which is sort of like `reduce` in javascript, but a bit more expressive) to create the function g, the answer to this question.

---

# Haskell, 64 characters

inspired by @alphaalpha's answer, here is it's version ported to haskell:

```
m[a,b,c,d]p|p=[b,c,d,a]|0<1=[b,d,a,c]
g l=foldl m[0..3]l<[0,1,3]

```

---

**edit:** I now feel incredibly stupid because of lmari Karonen's answer. maybe i'll port his answer to haskell.  **another edit:** not feeling as stupid as his answer is was wrong
**edit:** switched from actually using tuples to using lists as their `Ord` instance and the `[ ... ]` syntactic sugar makes it shorter

# Answer
> 3 votes
# APL (Dyalog Unicode), 22 bytes (Adám's SBCS)

```
f←{x∊(-@3∘⌽⌽)/⍵,x←⊂⍳3}

```

Try it online!

H.PWiz suggested that reversing the steps doesn't make a difference, and that resulted in -2 bytes.

Well, this is embarrassing, since it was intended to be way shorter than GolfScript. At least I tried to.

The function is named `f`, and, in the test cases, `1` represents a left turn (boolean true) and `0` represents a right turn (boolean false).  represents the empty list.

# Answer
> 3 votes
# Haskell, 53 bytes

```
f=(<28).foldl(\n x->mod n 4*64+mod(div n 4*16^x)63)27

```

Try it online!

Same logic as my Python answer, even thought `mod` and `div` are longer to write.

---

**Haskell, 58 bytes**

```
r=[1..3]
f=(==r).foldl(\[x,y,z]->(!!)[[x,-z,y],[-z,y,x]])r

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog), 21 bytes

```
f←{x≡(↓∪⊢∘⌽)/⍵,x←⊂⍳4}

```

Try it online! (Using the testing environment from Erik the Outgolfer's answer)

I take left and right as `1` and `2`. This uses the following permutations of `abcd`:

```
1 : bcda
2 : cdba

```

I apply the permutations corresponding to `1` and `2` to `⍳4 : 1 2 3 4`, and check if it is unchanged

# Answer
> 3 votes
# Bash, 71 65 bytes

```
f()(a=1234;for i;{ a=`tr 1-4 4$[$i?123:312]<<<$a`;};((a==1234));)

```

Try it online!

Like many previous answers, uses a representation of the group of rotations of the cube generated by 1234-\>4123 and 1234-\>4312. Uses numbers instead of letters so that I can use a ternary operator with an arithmetic expansion. Expects its input as 0's and 1's separated by spaces, and outputs via exit code.

6 bytes saved thanks to @manatwork's comment!

# Answer
> 3 votes
# brainfuck, 119 bytes, 137 bytes

Uses the fact that the rotation group of the cube is isomorphic to \\$S\_4\\$. Brainfuck has no functions at all, named or otherwise, so this is a full program that takes input through STDIN and outputs to STDOUT. (If you insist on a variable, pretend the value of the cell the program ends on is a variable.)

### Cube, 119 bytes

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

```

Try it online!

```
++++>+++>++>+    Initialize tape as 4 3 2 1

>,[              For each input byte:

  +++[->+++<]       Add 3 and multiply by 3; if input is R, this will be 255

  <<<<[->>>>+<<<<]  Move first number to end (BCDA)

  >[>]<+[           If input wasn't R:

    [-]                Zero input cell (which is now negative 18)

    <[->+<]            Move previously moved number one slot further (BCD_A)

    <<<[->>>+<<<]      Move first number into vacated slot (CDBA)

  >[>]]

,]

<[[<]>[->]<[>>]<]     Determine whether tape is still 4 3 2 1

<[>>-<]               If not: subtract 1 from output cell

-[----->+<]>--.       Create "1" in output cell and output

```

### Dodecahedron, 137 bytes

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

```

Try it online!

The only differences between the two programs are the setup and permutations. The left permutation used here is `DCAEB`, which seemed to be the golfiest conjugate available.

# Answer
> 2 votes
# PARI/GP

Based on my answer to Detect round trips on a dodecahedron.

## Cube, 35 bytes

```
f(s)=t=x;[t=1/Mod(t+c,3)|c<-s];t==x

```

Attempt This Online!

Takes a list of `1`s and `-1`s.

The rotational symmetry group of a cube is isomorphic to \\$PSL(2,3)\\$ (the projective special linear group). Here `L` and `R` correspond to the rational functions \\$\frac{1}{x+1}\\$ and \\$\frac{1}{x-1}\\$ respectively.

---

## Dodecahedron, 37 bytes

```
f(s)=t=x;[t=Mod(t^c+1,5)^c|c<-s];t==x

```

Attempt This Online!

Takes a list of `1`s and `-1`s.

The rotational symmetry group of a dodecahedron is isomorphic to \\$PSL(2,5)\\$. Here `L` and `R` correspond to the rational functions \\$x+1\\$ and \\$\frac{x}{x+1}\\$ respectively.

# Answer
> 1 votes
# Jelly, 14 bytes

```
3RðW;ṙN1¦ṚƊ/⁼⁸

```

Try it online!

`1` = left turn, `0` = right turn. Based on my Dyalog solution.

Unfortunately, Jelly doesn't have named functions. If I can't use an implicit input and need to assume it's in a variable, this same-length version will do:

```
3RµW;®ṙN1¦ṚƊ/⁼

```

It assumes the input is in the register (©/®).

# Answer
> 1 votes
# Python 3, 111 bytes

```
def f(s):
 u,f,r,l,b,d='WGROBY'
 for c in s:
  if'R'==c:u,f,d,b=b,u,f,d
  else:u,l,d,r=l,d,r,u
 return'WG'==u+f

```

Try it online!

There are a few ways I can think to shave off a few bytes, but I'll just leave it like this, since this approach isn't anywhere near competitive anyway. Happy to hear about other tweaks, though!

* -5: Take a boolean array as input, so `if'R'==c:` can be just `if c:`
    + -1: Or just change `if'R'==c:` to `if'L'<c:`
* -1: Change the lettering scheme from `WGROBY` to `ABCDEF` so `'WG'==u+f` can be `'AC'>u+f`

# Answer
> 0 votes
# Perl - 120, 214

Takes an array (list) of booleans.

Cube (120):

```
sub e{$a=$b=0;for$c(@_){$_=(13,62,53,40,57,26,17,'04')[$b];$d=s/$a/($b-1)%8/e;($a,$b)=($b,substr($_,$c^$d,1))}return!$b}

```

Dodecahedron (214):

```
sub e{$a=$b='00';for$c(@_){$_=('01041102090307040500061807160308091502101114121019131714151016081706131819051200'=~/\d{4}/g)[$b];$d=s/$a/sprintf'%02d',($b-1)%20/e;($a,$b)=($b,substr($_,($c^$d)*2,2));}return!($b+0)}

```

---
Tags: code-golf
---


title: Compute the Fabius Function

text:
# Question
Title: Compute the Fabius Function
The Fabius function is an example of a function that is infinitely differentiable everywhere, yet nowhere analytic.

One way to define the function is in terms of an infinite number of random variables. Specifically, given a sequence of independent random variables \\$\\{U\_n\\}\\$, where each \\$U\_n\\$ is uniform on the interval \\$\[0,2^{-n}\]\\$, the Fabius function \\$f\\$ is defined on \\$\[0,1\]\\$ as the cumulative distribution function of their sum \\$\displaystyle\sum\_{i=1}^\infty U\_i\\$ :

# Task

Given a number \\$x\in\[0,1\]\\$, compute \\$f(x)\\$. Your answer should be accurate to within \\$2^{-16}\approx0.00001526\\$ on the given test cases.

## Test cases

```
x       f(x)
0       0
0.163   0.012220888930835
0.3     0.129428260311965
0.5     0.5
0.618   0.733405658665583
0.75    0.930555555555556
1       1

```

# Answer
> 8 votes
# Python, 94 bytes (@att)

```
lambda x:B.c[int(x*4**9)]/8**57
from numpy import*
B,*A=a=1,1.
exec('A*=2;B*=poly1d(A)*a;'*18)

```

Attempt This Online!

## Python, 99 bytes

```
lambda x:B.c[int(x*4**9)]/max(B.c)
from numpy import*
B,*A=a=1,1.
for i in a*9:A*=2;B*=poly1d(A)*a

```

Attempt This Online!

### -13 thanks @att

### Python, 133 bytes

```
lambda x:interp(x,r_[:2:len(B)+0j],B/max(B))
from numpy import*
A=a=poly1d([1,0])
B=prod([((A:=A*A)/(a-1))[0]*(a+1)for i in[0]*17]).c

```

Attempt This Online!

Brute-force computation of the convolution of the given uniform densities. Uses polynomials to get convolution through the `*` symbol. Two little tricks: 1) x^n / (x-1) generates (discarding the residual 1) the "flat" polynomials we need 2) convolution with a constant is essentially prefix sum up to the middle, saving us a `cumsum`.

# Answer
> 3 votes
# PARI/GP, 56 bytes

-1 byte thanks to @att,

```
x->sum(i=0,x<<=20,(-1)^sumdigits(x\1-i,2)*i^20)/20!/4^95

```

Attempt This Online!

Returns a fraction.

Based on this answer on Mathematics SE found by mousetail:

$$\begin{align} F(x)&=\lim\_{n\to\infty} F\_n(x)\\ F\_n(x)&=\frac{2^{n(n+1)/2}}{n!}\\,\sum\_{y\in D\_{n,x}}(-1)^{s(y)}\big(x-y\big)^n \end{align}$$

where \\$D\_{n,x}\\$ is the set of all dyadic numbers in \\$\[0,x\]\\$ of the form \\$m2^{-n}\\$ for integers \\$m\\$, and \\$s(y)\\$ is the sum of the binary digits of \\$y\\$.

It seems that \\$n=20\\$ is sufficient for this challenge.

# Answer
> 2 votes
# Pyth, 41 39 bytes

```
J*hK20]ZV*^2KQ=JsM._XZJ^_1sjN2;ceJ^2sUK

```

Try it online!

Note that in the try it online link, I have decreased the accuracy from 20 to 15 so that it finishes running in time. You'll have to take my word that I've tried it on my machine and the above code meets the given accuracy requirement.

This program essentially does N summations along the Thue–Morse sequence. This can be thought of as a sort of "discrete integral", in which case the fact that \\$f'(x)=2f(2x)\\$ tells us that each time we do this, we get our function back but with half the interval, half the magnitude, but twice the accuracy. We can easily deal with the magnitude at the end, and by starting with \\$2^N\\$ terms of the sequence, we end with the range from 0 to 1 with whatever accuracy we desire, No floating point or overflow errors occur along the way since all of this is done on python ints. \\$N=20\\$ is about right to hit the accuracy required.

# Answer
> 1 votes
# APL (Dyalog Classic), 27 bytes

```
{⊃(⌊⍵×8*7)↓(+\⊢,-)⍣22÷8*70}

```

Try it online!

As noted by CursorCoercer, the identity \\$f'(x)=2f(2x)\\$ holds when \\$0\<x\<\frac12\\$, and can be used to characterize a unique extension of \\$f\\$ to \\$\[0,4\]\\$. Specifically, noting the symmetry of \\$f\\$ about \\$x=0.5\\$, we have \\$f(x)=f(2-x)\\$ for \\$x\in\[1,2\]\\$, then \\$f(x)=-f(x-2)\\$ when \\$x\in\[2,4\]\\$.

From here, we can iterate \\$\displaystyle f(x)=\int\_0^{2x}f(t)\\,dt\\$ until we attain the desired precision:

```
          ÷8*70     start: 2^-210
                      one sample of an approximate-f on [0,2],
                      times a multiplicative factor.
(     )⍣22          repeat (22x) until precision goal reached:
   ⊢                  from n samples on [0,2],
    ,-                append its negation
                        => 2n samples on [0,4]
 +\                   cumulative sum
                        take the discrete integral.
                        the introduced multiplicative term of
                        1/∆x is cancelled by the start value.
                        => 2n samples on [0,2] of a better
                           approximation

⊃(⌊⍵×8*7)↓          index into the samples

```

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


# Question
Title: Outputting ordinal numbers (1st, 2nd, 3rd)
I would like to generate (as a return result of a function, or simply as the output of a program) the ordinal suffix of a positive integer concatenated to the number.

Samples:

```
1st
2nd
3rd
4th
...
11th
12th
13th
...
20th
21st
22nd
23rd
24th

```

And so on, with the suffix repeating the initial 1-10 subpattern every 10 until 100, where the pattern ultimately starts over.

The input would be the number and the output the ordinal string as shown above.

What is the smallest algorithm for this?

# Answer
> 35 votes
## Perl, 37 + 1 characters

```
s/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg

```

This is a regexp substitution that appends the appropriate ordinal suffix to any numbers in `$_` that are not already followed by a letter. To apply it to file input, use the `p` command line switch, like this:

```
perl -pe 's/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg'

```

This is a complete Perl program that reads input from stdin and writes the processed output to stdout. The actual code is 37 chars long, but the `p` switch counts as one extra character.

### Sample input:

```
This is the 1 line of the sample input...
...and this is the 2.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
101 102 103 104 105 106 107 108 109 110

```

### Output:

```
This is the 1st line of the sample input...
...and this is the 2nd.
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
11th 12th 13th 14th 15th 16th 17th 18th 19th 20th
21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th
101st 102nd 103rd 104th 105th 106th 107th 108th 109th 110th

```

Numbers already followed by letters will be ignored, so feeding the output again through the filter won't change it. Spaces, commas and periods between numbers are not treated specially, so they're assumed to separate numbers like any other punctuation. Thus, e.g. `3.14159` becomes `3rd.14159th`.

### How does it work?

* First, this is a global regexp replacement (`s///g`). The regexp being matched is `1?\d\b`, where `\d` matches any digit and `\b` is a zero-width assertion matching the boundary between an alphanumeric and a non-alphanumeric character. Thus, `1?\d\b` matches the last digit of any number, plus the previous digit if it happens to be `1`.
* In the substitution, which is evaluated as Perl code due to the `/e` switch, we take the matched string segment (`$&`) and append (`.`) to it the suffix obtained by using `$&` itself as an integer index to the list `(0,st,nd,rd)`; if this suffix is zero or undefined (i.e. when `$&` is zero or greater than three), the `||` operator replaces it with `th`.

---

**Edit:** If the input is restricted to a single integer, then this 35 character solution will suffice:

```
s/1?\d$/$&.((0,st,nd,rd)[$&]||th)/e

```

# Answer
> 47 votes
# Python 2, 49 bytes

```
lambda n:`n`+'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4]

```

An anonymous function. A full program would be counted at 55 bytes.

`'tsnrhtdd'[i::4]` encodes the suffixes `th st nd rd` for values of `i` from 0 to 3. Given this, all we need is a way to map the values of `n` to the index of the corresponding suffix, `i`. A straightforward expression that works is `(n%10)*(n%10<4 and not 10<n%100<14)`. We can easily shorten this by dropping the first set of parentheses and observing that `n%5` gives the same results as `n%10` for the values of `n` with the special suffixes. With a bit of trial and error, one may also shorten `not 10<n%100<14` to `n%100^15>4`, which can be chained with the other conditional to save even more bytes.

# Answer
> 13 votes
## Python, 68 characters

```
i=input()
k=i%10
print"%d%s"%(i,"tsnrhtdd"[(i/10%10!=1)*(k<4)*k::4])

```

# Answer
> 13 votes
# Mathematica ~~39~~ 45 bytes

Note: In recent versions of Mathematica, asking for the `nth` part of `p`, where `p` is undefined, generates an error message, but returns the correct answer anyway. I've added `Quiet` to prevent the error message from printing.

```
Quiet@StringSplit[SpokenString[p[[#]]]][[2]]&

```

**Usage**

```
Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &[31]

```

> 31st

```
Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &/@Range[21]

```

> {"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st"}

---

**How it works**

`SpokenString` writes out an any valid Mathematica expression as it might be spoken. Below are two examples from the documentation for SpokenString,

```
SpokenString[Sqrt[x/(y + z)]]

```

> "square root of the quantity x over the quantity y plus z" \*)

```
SpokenString[Graphics3D[Sphere[{{0, 0, 0}, {1, 1, 1}}]], "DetailedGraphics" -> True]

```

> "a three-dimensional graphic consisting of unit spheres centered at 0, 0, 0 and 1, 1, 1"

---

Now, for the example at hand,

```
Quiet@SpokenString[p[[#]]] &[31]

```

> "the 31st element of p"

Let's represent the above string as a list of words:

```
StringSplit[%]

```

> {"the", "31st", "element", "of", "p"}

and take the second element...

```
%[[2]]

```

> 31st

# Answer
> 12 votes
# Javascript (ES6) ~~50~~ 44 Bytes

```
a=>a+=[,"st","nd","rd"][a.match`1?.$`]||"th"

```

### Notes

* takes imput as a string
* Removed 6 bytes, thanks @user81655

# Answer
> 9 votes
## Ruby, 60

It's not as good as the Perl entry, but I figured I'd work on my Ruby skills.

```
def o(n)n.to_s+%w{th st nd rd}[n/10%10==1||n%10>3?0:n%10]end

```

Function takes one integer argument, `n`, and returns a string as the ordinal form.

Works according to the following logic:
If the tens digit is a 1 or the ones digit is greater than 3 use the suffix 'th'; otherwise find the suffix from the array \['th', 'st', 'nd', 'rd'\] using the final digit as the index.

# Answer
> 6 votes
## Javascript, ~~68~~ 71

```
function o(n){return n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th')}

```

Joint effort with ItsCosmo.

EDIT: Wasn't working properly with numbers \> 100

# Answer
> 6 votes
# JavaScript, 64 characters (ES3) or 47 characters (ES6)

### ES3 (64 characters):

`function(n){return n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'}`

### ES6 (47 characters):

`n=>n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'`

### Explanation

The expression `n % 100 >> 3 ^ 1` evaluates to 0 for any positive `n` ending with digits `08``15`. Thus, for any `n mod 100` ending in `11`, `12`, or `13`, the array lookup returns `undefined`, leading to a suffix of `th`.

For any positive `n` ending in other digits than `08``15`, the expression `n % 100 >> 3 ^ 1` evaluates to a positive integer, invoking the expression `n % 10` for array lookup, returning `st`,`nd`, or `rd` for `n` which ends with `1`, `2`, or `3`. Otherwise, `th`.

# Answer
> 5 votes
## Haskell, ~~95~~ 100 chars

```
h=foldr g"th".show
g '1'"th"="1st"
g '2'"th"="2nd"
g '3'"th"="3rd"
g '1'[x,_,_]='1':x:"th"
g a s=a:s

```

Testing:

```
*Main> map h [1..40]
["1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13t
h","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th",
"25th","26th","27th","28th","29th","30th","31st","32nd","33rd","34th","35th","36
th","37th","38th","39th","40th"]

```

Must be loaded with -XNoMonomorphismRestriction.

# Answer
> 5 votes
# J -  ~~44~~  41 char

Nothing in J? This is an outrage!

```
(":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)

```

Explained (note that `1` is boolean true in J and `0` is false):

* `100&|` \- First, reduce the input modulo 100.
* `10(|*|~:-~)` \- In this subexpression, `|` is the input mod 10 and `-~` is the input (mod 100) minus 10. You don't get many trains as clean as this one in J, so it's a treat to see here!
    + `~:` is not-equals, so `|~:-~` is false if the tens digit is 1 and true otherwise.
    + `*` is just multiplication, so we're taking the input mod 10 and multiplying by a boolean, which will zero it out if false. The result of this is "input mod 10, except 0 on the tens".
* `4|4<.` \- Min (`<.`) the above with 4, to clamp down larger values, and then reduce modulo 4 so that they all go to zero.
* `th`st`nd`rd{::~` \- Use that as an index into the list of suiffixes. Numbers ending in X1 or X2 or X3, but not in 1X, will find their suffix, and everything else will take the 0th suffix `th`.
* `":,` \- Finally, take the original input, convert it to a string (`":`), and append the suffix.

Usage is obvious, though as-is the verb can only take one ordinal, not a list.

```
   (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 112         NB. single use
112th
   (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 1 2 3 4 5   NB. doing it wrong
|length error
|       (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)1 2 3 4 5
   NB. i.5 10   makes a 5x10 grid of increasing integers
   NB. &.>      to operate on each integer separately, and box the result after
   (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)&.> i.5 10   NB. all better
+----+----+----+----+----+----+----+----+----+----+
|0th |1st |2nd |3rd |4th |5th |6th |7th |8th |9th |
+----+----+----+----+----+----+----+----+----+----+
|10th|11th|12th|13th|14th|15th|16th|17th|18th|19th|
+----+----+----+----+----+----+----+----+----+----+
|20th|21st|22nd|23rd|24th|25th|26th|27th|28th|29th|
+----+----+----+----+----+----+----+----+----+----+
|30th|31st|32nd|33rd|34th|35th|36th|37th|38th|39th|
+----+----+----+----+----+----+----+----+----+----+
|40th|41st|42nd|43rd|44th|45th|46th|47th|48th|49th|
+----+----+----+----+----+----+----+----+----+----+

```

Alternative 41 char solution showing off a couple logical variants:

```
(":;@;st`nd`rd`th{~3<.10(|+3*|=-~)100|<:)

```

Previously I had an overlong explanation of this 44 char hunk of junk. `10 10#:` takes the last two decimal digits and `/@` puts logic between them.

```
(":,th`st`nd`rd{::~10 10(]*[(~:*])4>])/@#:])

```

# Answer
> 4 votes
## Golfscript, 34 characters

```
~.10/10%1=!1$10%*.4<*'thstndrd'2/=

```

# Answer
> 4 votes
# Javascript, ~~75~~ 60

With the new arrow notation:

```
o=(s)=>s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th")

```

*Old version, without arrow notation (75 chars):*

```
function o(s){return s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th")}

```

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~38~~ 36 bytes

Thanks to ngn for fixing a bug while maintaining byte count.

Anonymous tacit prefix function. Requires `⎕IO` (**I**ndex **O**rigin) set to `0`, which is default on many systems. Even works for 0!

```
⍕,{2↑'thstndrd'↓⍨2×⊃⍵⌽∊1 0 8\⊂10↑⍳4}

```

Try it online!

`{``}` anonymous lambda;  is argument:

`⍳4` first four **ɩ**ndices; `[0,1,2,3]`

`10↑` take first ten elements from that, padding with zeros: `[0,1,2,3,0,0,0,0,0,0]`

enclose to treat as single element; `[[0,1,2,3,0,0,0,0,0,0]]`

`1 0 8\` expand to one copy, a prototypical copy (all-zero), eight copies;
`[[0,1,2,3,0,0,0,0,0,0],`
`[0,0,0,0,0,0,0,0,0,0],`
`[0,1,2,3,0,0,0,0,0,0],`
`[0,1,2,3,0,0,0,0,0,0],`
⋮ (5 more)
`[0,1,2,3,0,0,0,0,0,0]]`

**ϵ**nlist (flatten);
`[0,1,2,3,0,0,0,0,0,0,`
`0,0,0,0,0,0,0,0,0,0,`
`0,1,2,3,0,0,0,0,0,0,`
`0,1,2,3,0,0,0,0,0,0,`
⋮ (50 more)
`0,1,2,3,0,0,0,0,0,0]`

`⍵⌽` cyclically rotate left as many steps as indicated by the argument

pick the first number (i.e. the argument-mod-100'th number)

multiply two by that (gives `0`, `2`, `4`, or `6`)

`'thstndrd'↓⍨`drop that many characters from this string

`2↑` take the first two of the remaining characters

`⍕,` concatenate the stringified argument to that

# Answer
> 4 votes
# , ~~79~~ 76 bytes

Since there is no R solution yet... no tricks here, basic vector indexing, golfed down 3 chars thanks to Giuseppe. Previously tried index: `[1+(x%%10)-(x%%100==11)]` and `[1+(x%%10)*(x%%100!=11)]`.

```
function(x)paste0(x,c("th","st","nd","rd",rep("th",6))[1+x%%10*!x%%100==11])

```

Try it online!

With `substr`, 79 bytes:

```
function(x,y=1+2*min(x%%10-(x%%100==11),4))paste0(x,substr("thstndrdth",y,y+1))

```

Try it online!

# Answer
> 4 votes
Bash (Cardinal to ordinal) **91** Bytes:

```
function c(){ case "$1" in *1[0-9]|*[04-9])"$1"th;;*1)"$1"st;;*2)"$1"nd;;*3)"$1"rd;;esac }

```

# Answer
> 3 votes
## PowerShell, 92

```
process{"$_$(switch -r($_){"(?<!1)1$"{'st'}"(?<!1)2$"{'nd'}"(?<!1)3$"{'rd'}default{'th'}})"}

```

Works with one number per line of input. Input is given through the pipeline. Making it work for only a single number doesn't reduce the size.

# Answer
> 3 votes
## PHP, 151

I know that this program is not comparable to the others. Just felt like giving a solution.

```
<?$s=explode(' ',trim(fgets(STDIN)));foreach($s as$n){echo$n;echo(int)(($n%100)/10)==1?'th':($n%10==1?'st':($n%10==2?'nd':($n%10==3?'rd':'th')))."\n";}

```

# Answer
> 3 votes
# K - 44 char

It so happens that this is exactly as long as the J, and works in almost the same way.

```
{x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:}

```

Explained:

* `x$:` \- First, we convert the operand `x` into a string, and then assign that back to `x`. We will need its string rep again later, so doing it now saves characters.
* `.:'` \- Convert (`.:`) each (`'`) digit back into a number.
* `-2#0,` \- Append a 0 to the front of the list of digits (in case of single-digit numbers), and then take the last two.
* `{y*(y<4)*~1=x}.` \- Use the two digits as arguments `x` and `y` to this inner function, which returns `y` if `y` is less than 4 and `x` is not equal to 1, otherwise 0.
* ``th`st`nd`rd@` \- Index the list of suffixes by this result.
* `x,$` \- Convert the suffix from symbol to string, and append it to the original number.

Usage:

```
  {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:} 3021
"3021st"
  {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:}' 1 2 3 4 11 12 13 14  /for each in list
("1st"
 "2nd"
 "3rd"
 "4th"
 "11th"
 "12th"
 "13th"
 "14th")

```

# Answer
> 3 votes
# PHP, 98 bytes

```
function c($n){$c=$n%100;$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];}

```

The 11-13 bit is killing me here. Works for any integer `$n >= 0`.

For any integer `$n`:

# PHP, 103 bytes

```
function c($n){$c=abs($n%100);$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];}

```

# Answer
> 3 votes
# Javascript ES6, 52 chars

```
n=>n+(!/1.$/.test(--n)&&'snr'[n%=10]+'tdd'[n]||'th')

```

# Answer
> 3 votes
# C#, 62 bytes

```
n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd");

```

Full program and verification:

```
using System;

namespace OutputOrdinalNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,string>f= n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd");

            for (int i=1; i<=124; i++)
                Console.WriteLine(f(i));
        }
    }
}

```

# Answer
> 3 votes
# Mathematica 29 + 5 = 34 bytes

```
SpokenStringDump`SpeakOrdinal

```

+5 bytes because `Speak` function must be called before using this built-in.

**Usage**

```
SpokenStringDump`SpeakOrdinal[1]

```

> `"1st "`

```
SpokenStringDump`SpeakOrdinal[4707]

```

> `"4,707th "`

# Answer
> 3 votes
# Java 7, ~~91~~ 81 bytes

```
String d(int n){return n+(n/10%10==1|(n%=10)<1|n>3?"th":n<2?"st":n<3?"nd":"rd");}

```

Port from *@adrianmp*'s C# answer.

Old answer (**91 bytes**):

```
String c(int n){return n+((n%=100)>10&n<14?"th":(n%=10)==1?"st":n==2?"nd":n==3?"rd":"th");}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(int n){
    return n + ((n%=100) > 10 & n < 14
                ?"th"
                : (n%=10) == 1
                   ? "st"
                   : n == 2
                      ? "nd"
                      : n == 3
                         ? "rd"
                         :"th");
  }

  static String d(int n){
    return n + (n/10%10 == 1 | (n%=10) < 1 | n > 3
                 ? "th"
                 : n < 2
                    ? "st"
                    : n < 3
                       ? "nd"
                       :"rd");
  }

  public static void main(String[] a){
    for(int i = 1; i < 201; i++){
      System.out.print(c(i) + ", ");
    }
    System.out.println();
    for(int i = 1; i < 201; i++){
      System.out.print(d(i) + ", ");
    }
  }
}

```

**Output:**

```
1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th,
1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th,

```

# Answer
> 3 votes
# Vyxal, 6 bytes

```
∆o2NȯJ

```

Try it Online!

# Answer
> 1 votes
# OCaml

I'm pretty new to OCaml, but this is the shortest i could get.

```
let n x =
   let v = x mod 100 and string_v = string_of_int x in
   let z = v mod 10 in
   if v=11 || v=12 || v=13 then string_v^"th"
   else if v = 1 || z = 1 then string_v^"st" else if v = 2 || z = 2 then string_v^"nd" else if v = 3 || z = 3 then string_v^"rd" else string_v^"th";;

```

I created a function n that takes a number as a parameter and does the work. Its long but thought it'd be great to have a functional example.

# Answer
> 1 votes
Python 2.7, 137 chars

```
def b(n):
 for e,o in[[i,'th']for i in['11','12','13']+list('4567890')]+[['2','nd'],['1','st'],['3','rd']]:
  if n.endswith(e):return n+o

```

`n` should be a string

I know I'm beaten by the competition here already, but I thought I'd provide my idea anyways

this just basically generates a list of key, value pairs with number (as a string) ending `e` and the ordinal `o`. It attempts to match 'th' first (hence why I didn't use a dictionary), so that it won't accidentally return 'st', for example, when it should be 'th'. This will work for any positive integer

# Answer
> 1 votes
### Scala 86

```
def x(n:Int)=n+{if(n%100/10==1)"th"else(("thstndrd"+"th"*6).sliding(2,2).toSeq(n%10))}

```

Scala 102:

```
def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".take(n+1)%5*2.drop(n%5*2))else n+"th"

```

102 as well:

```
def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".sliding(2,2).toSeq(n%10))else n+"th"

```

ungolfed:

```
def x (n: Int) =
  n + { if (((n % 100) / 10) == 1) "th"
        else (("thstndrd"  + ("th"  * 6)).sliding (2, 2).toSeq (n % 10))
      }

```

# Answer
> 1 votes
# C: 95 characters

A ridiculously long solution:

```
n;main(){scanf("%d",&n);printf("%d%s",n,n/10%10-1&&(n=n%10)<4&&n?n>2?"rd":n<2?"st":"nd":"th");}

```

It needs to be mangled more.

# Answer
> 1 votes
## Haxe, 83 chars

```
function o(n:Int){return ['th','st','nd','rd'][n%100>20||n%100<4?n%10>3?0:n%10:0];}

```

Based on the javascript version, fixed for n \> 100 as well.

# Answer
> 1 votes
# C - 95 83 characters

```
main(n,k){scanf("%d",&n);k=(n+9)%10;printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th");}

```

Degolfed:

```
main(n,k)
{
    scanf("%d",&n);
    k=(n+9)%10; // xx1->0, xx2->1, xx3->2
    printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th");
}

```

We could do `k=(n-1)%10` instead of adding 9, but for n=0 we would get an incorrect behaviour, because in C `(-1)%10` evaluates to -1, not 9.

# Answer
> 1 votes
# Javascript, 75

```
function s(i){return i+'thstndrd'.substr(~~(i/10%10)-1&&i%10<4?i%10*2:0,2)}

```

# Answer
> 1 votes
# Oracle SQL 11.2, 101 bytes

```
SELECT:1||DECODE(ROUND(MOD(:1,100),-1),10,'th',DECODE(MOD(:1,10),1,'st',2,'nd',3,'rd','th'))FROM DUAL

```

# Answer
> 1 votes
# Python, ~~88~~ 84 bytes

```
lambda x:x+((('th','st','nd','rd')+('th',)*6)[int(x[-1])]if('0'+x)[-2]!='1'else'th')

```

Ungolfed:

```
def y(x):
    return x + (('th', 'st', 'nd', 'rd') + ('th', ) * 6)[int(x[-1])] if ('0' + x)[-2] != '1' else 'th')

```

`lambda x` defines an anonymous function with parameter `x`. `((('th','st','nd','rd')+('th',)*6)[int(x[-1])]` defines a tuple of the endings for numbers less than 10, the `0-th` element is for `0`, and so forth. the `if ('0'+x)[-2] != '1'` checks if there is `11`, `12`, or a `13` to fix, and adds then `else 'th'` adds `th` instead of `st`, `rd`, or `nd`.

# Answer
> 1 votes
# Scala 2.11.7, 151 Chars

```
def o(x:Int*)=x map{
case a if(a%10)==1&&a%100!=11=>a+"st"
case b if(b%10)==2&&b%100!=12=>b+"nd"
case c if(c%10)==3&&c%100!=13=>c+"rd"
case e=>e+"th"
}

```

Usage

```
   o(1,2,3,4) -> ArrayBuffer("1st", "2nd", "3rd", "4th")

```

# Answer
> 1 votes
# Common Lisp, 63

```
(format t"~a~a"i(let((x(format()"~:r"i)))(subseq x(-(length x)2))))

```

Input is `i`. There's probably a more clever way to golf this.

# Answer
> 1 votes
# Pyth, 33 bytes

```
+Q@.>+c"stndrd"2*]"th"7 1?qh`Q\1Z

```

Try it online!

# Answer
> 1 votes
# Procedural Footnote Language, 39 bytes

```
[1]
[PFL1.0]
[1] [ORD:[INPUT]]
[PFLEND]

```

The `BODY` section of the document contains a reference to footnote `[1]`; footnote `[1]` contains the `[ORD]`inal representation of the `[INPUT]`.

# Answer
> 1 votes
# JavaScript (Node.js), 51 bytes

credit to @KevinCruijssen for improving the answer

```
n=>n+=[,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th'

```

Try it online!

---

# Explanation :

```
n =>                      // input
    n+=[,'st','nd','rd']     // the array of suffices add everything to n
        [~~(n/10%10)-1?n%10:0] // the full magic
    || 'th'               // works for everything except 1 , 2 , 3 just like what you want

```

---

# Answer
> 1 votes
# Julia 0.6, 68 bytes

```
f(x,m=x%10,p=x%100-m)="$x$(["th","st","nd","rd"][m>3||p==10?1:m+1])"

```

Try it online!

Straightforward remainder rules in Julia.

# Answer
> 1 votes
# 05AB1E, 21 bytes

```
т%T‰ć≠*4ªß…thŠØ3ôsè¨«

```

Try it online or verify a few more test cases at once.

**Explanation:**

Mostly ported from a sub-section of this answer of mine, except with additional leading `т%`.

```
т%                     # Take modulo-100 on the (implicit) input-integer
  T‰                   # Take the divmod-10 ([n//10,n%10]) on that
    ć                  # Extract the head: n//10
     ≠                 # Check that it's NOT equal to 1 (0 if 1; 1 otherwise)
      *                # Multiply the [n%10] by this
       4ª              # Append a 4 to this list: [n%10*(n//10!=1),4]
         ß             # Pop and push the smallest number in this list
          …thŠØ        # Push dictionary string "th standards"
               3ô      # Split it into parts of size 3: ["th ","sta","nda","rds"]
                 sè    # Index the calculated minimum into this list
                       # (modular 0-based, so both 0 and 4 will index into "th ")
                   ¨   # Remove the last character
                    «  # And append it to the (implicit) input-integer
                       # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `…thŠØ` is `"th standards"`.

# Answer
> 1 votes
# APL(NARS), 38 chars, 76 bytes

```
(⍕,{((⍳3)⍳10∣⍵×3≠⌊√⍵)⊃'snrt',¨'tddh'})

```

test:

```
  h←(⍕,{((⍳3)⍳10∣⍵×3≠⌊√⍵)⊃'snrt',¨'tddh'})
  h¨0..19
 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th
  h¨20..31
 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 31st
  ⎕fmt h¨100..104
┌5───────────────────────────────────────────┐
│┌5─────┐ ┌5─────┐ ┌5─────┐ ┌5─────┐ ┌5─────┐│
││ 100th│ │ 101st│ │ 102nd│ │ 103rd│ │ 104th││
│└──────┘ └──────┘ └──────┘ └──────┘ └──────┘2
└∊───────────────────────────────────────────┘

```

# Answer
> 1 votes
# FEU, 41 bytes

```
m/1.$/\0th/1$/1st/2$/2nd/3$/3rd/\d$/\0th/

```

Try it online!

# Answer
> 1 votes
# C, 87 bytes (correct teen handling)

This C solution is longer than the current shortest 83 byte C solution posted, but as of writing, that 83 byte solution is incorrect and prints numbers like 11st, 12nd, and 13rd.

Here is my solution, which correctly handles teen numbers:

```
main(n){scanf("%d",&n);printf("%d%s",n,"th\0st\0nd\0rd"+(n%10<4&&n/10%10-1?n%10*3:0));}

```

Degolfed:

```
main(n) {
    scanf("%d", &n);
    printf("%d%s", n, "th\0st\0nd\0rd" + (n%10 < 4 && n/10%10 - 1 ? n%10*3 : 0));
}

```

# Answer
> 1 votes
# Bash, 58 bytes

Just a modification of @stephanmg's post in Bash. Output is on STDERR as in "command not found".

```
case $1 in
*1?|*[04-9])$1th;;*1)$1st;;*2)$1nd;;*)$1rd
esac

```

Try it online!

This program completely relies on the limitation that the input is a non-negative decimal integer.

# Answer
> 1 votes
# Vyxal, 23 bytes

```
₀%:4<?₀ḭċ∧*4«∨¦İk√«/$i+

```

Try it Online!

##### Explanation:

```
₀%:4<?₀ḭċ∧*4«∨¦İk√«/$i+    # full program

₀%:                         # push input mod 10 twice
   4<                       # less than 4
     ?₀ḭ                    # input floor div 10
        ċ                   # != 1
         ∧*                 # and both bools, then multiply by initial mod 10
            4«∨¦İk√«/       # "thstndrd" split into 4 parts
                      $i    # indexed by input mod 10
                        +   # concat

```

# Answer
> 1 votes
# Vyxal, 14 bytes

```
ÞoÞ∞ZƛhṘ2ẎṘntp

```

Try it Online!

```
ÞoÞ∞Z          # Zip ordinals with positive integers
     ƛ         # Over each
      hṘ2ẎṘ    # Get the last two characters of the ordinal
           ntp # Append the number

```

# Answer
> 1 votes
# brainfuck, 313 bytes

This was painful. Setup could probably be golfed better. May write a half-decent explanation later.

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

```

Try it online!

# Answer
> 1 votes
# Go, ~~173~~ 110 bytes

```
import."fmt"
func o(n int){s,k:="th",n%10
if k>0&&k<4&&n/10%10!=1{s=[]string{"st","nd","rd"}[k-1]}
Print(n,s)}

```

Attempt This Online!

* -47 bytes from using slice indexing (by @Steffan)
* -14 bytes from outputting to STDOUT (by @Steffan)
* -2 bytes from removing duplicate `n%10`.

### Old answer, 173 bytes

```
import."fmt"
func o(n int)string{s:=Sprint(n)
switch n%100{case 11,12,13:s+="th"
default:switch n%10{case 1:s+="st"
case 2:s+="nd"
case 3:s+="rd"
default:s+="th"}}
return s}

```

Attempt This Online!

# Answer
> 0 votes
# Scratch, idk bytes

I tried to convert it to sb syntax, but it did not work

Try it!

Please comment if you know a way to golf, or byte-count this

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