# Question
Title: Convert 1, 2, 3, 4, 5, 6, 7, 8, and 9 to "one", "two", "three", etc
# Winner: professorfish's bash answer! An entire 9 bytes! Wow!

You may continue to submit your answer, however you can no longer win. Original post kept for posterity:

---

Your goal is to convert a **whole** number between 1-9 into the word it represents.

* You will not need to worry about decimals
* The user will input a number. Assume that they will never enter anything 10 or higher
* The user must type the number at some point, **however** the method the program reads it does not matter. It can be with stdin, reading a text file, etc, however the user must press the 9 button on their keyboard (for example) at some point
* It is not case sensitive (ie, "one", "One", "oNe", "OnE", etc are all acceptable)
* HTTP/etc requests are allowed, **however** any code executed by the server the request is made to counts towards the byte count of your final code (e.g. if I had a C++ program make a HTTP request, the PHP code used in the HTTP request counts)
* Anything that can compile and run is acceptable

---

* This contest **has ended** on June 27th, 2014 (7 days from posting).
* This is a , so the shortest code wins

# Answer
# Bash (with bsdgames), 9

```
number -l

```

Reads from standard input.

I don't know why there's a utility for this, but whatever.
> 20 votes

# Answer
## Python 2, 64

```
print' ottffssennwhoiieiieoruvxvgn  ere ehe  e   nt'[input()::9]

```

This is what the string looks like with some extra whitespace (try reading vertically):

```
o t t f f s s e n
n w h o i i e i i
e o r u v x v g n
    e r e   e h e
    e       n t

```

As explained in the comments below, `[input()::9]` starts at the given index and selects every ninth subsequent character.
> 132 votes

# Answer
# Common Lisp - 22 bytes

Here's a general one (not just for one-ten):

```
(format nil"~R"(read))

```

Oh, you want ordinals (first, second, ... three-hundredth...)? Ok!

```
(format nil"~:R"(read))

```
> 18 votes

# Answer
# BASH 51

So I made another one using my second idea plus some help from others:

```
set one two three four five six seven eight nine

$X

```

Where 'X' is the number you want.

---

# BASH 48 (67)

**67 with `\n` line breaks**

I'm not sure if this totally counts, because it's reading from a file, but:

`sed -n Xp a`

Where "X" is the input and where `a` is a file with:

```
one
two
three
four
five
six
seven
eight
nine

```

The file is 36 chars, and the bash command is 13.

How it works:

> Each line in the file is numbered, starting with 1. So 'one' is on the 1st line, 'two' on the 2nd. The command, `sed -n 'Xp' a` says, "Please print what's listed on line 'X' of file 'a'" `sed` is a Unix stream editor. `-n` means be silent, or only essentially ignore everything else. `Xp` means print what's on line 'X'.
> 16 votes

# Answer
### C# - 127 ( 86 / 46)

If you only take the executable part...

```
Console.Write(((HourOfDay)Console.Read()-48));

```

and if `HourOfDay` would have been part of the the System namespace you would need 46 chars. Unfortunately it sits in `System.DirectoryServices.ActiveDirectory` which makes it 86...the other noise spoils it.

This is compileable and runnable from the commandline (127 chars):

```
using System;class P{static void Main(){Console.Write((System.DirectoryServices.ActiveDirectory.HourOfDay)Console.Read()-48);}}

```

if saved to a file called cg2.cs

```
csc cg2.cs /r:System.DirectoryServices.dll  && cg2

```

**How does this work?**

`HourOfDay` is an enum type so we can use names instead of magic constants. Enum types have a ToString() implementation that gives you the name of the value. You can cast an int to an enum. Console.Read() reads a character from the input stream represented as an integer. typing '1' gives 49, substract 48 to get 1, cast/box to `HourOfDay` to return 'One'.

Take a look at the Powershell version of this same trick
> 16 votes

# Answer
# Befunge 98, ~~116~~ ~~105~~ 103 bytes

```
&1-       v
vvvvvvvvvj<
"""""""""
etnxereoe
nheivuewn
igvsiorto
nie"ffh""
"es ""t
 ""   "
>>>>>>>>>4k,@

```

Befunge was not made for this...

Explanation:

```
&1-           ;Grab the input number (`n`) and subtract 1 from it
&1-       v   ;Start moving downwards
          <   ;Start moving leftwards
         j    ;Jump `n - 1` characters to the left.
vvvvvvvvvj    ;Redirect each of the possible locations to jump to, sending the IP down.

        "     ;If `n` was 1, push `o, n, e` onto the stack (`o` is at the bottom)
        e
        n
        o
        "

       "      ;If `n` was 2, push `t, w, o` onto the stack
       o
       w
       t
       "

    *
    *
    *

"             ;If `n` was 9, push `n, i, n, e` onto the stack
e
n
i
n
"

>>>>>>>>>     ;Collect all the different possible positions the IP could be in, and send it right
>>>>>>>>>4k,  ;Print the top 5 chars. If there are less than 5, the rest are null characters. This is allowed
            @ ;End of program

```
> 14 votes

# Answer
# Javascript 68

Atob / btoa can be a poor's man compressing tool  ~~(but if you want to try this in console, you cannot copy from the formatted text you see at once. Go to 'edit' and copy from the source panel)~~

Markdown editor does not like some of the characters in this answer: some characters get lost at saving. Still, I think it's an editor problem, not mine. The lost characters are perfectly valid 8 bit unicode chars.
(Or else I'm wrong, if this issue was already debated in meta, let me know) Here is the version with offending characters escaped, each sequence \xNN should count 1

```
alert(btoa("×C§{Dð£Dáç´\x16\x8b«ÐX¯{D¢ÇD\x9e½éô\x12(!·Cb\x9dí").split(0)[prompt()])

```

**Simple Test**

In firefox console:

```
[0,1,2,3,4,5,6,7,8,9]
.map(x=>x +',' btoa("×C§{Dð£Dáç´\x16\x8b«ÐX¯{D¢ÇD\x9e½éô\x12(!·Cb\x9dí").split(0)[x])

```
> 11 votes

# Answer
# Javascript 73

```
alert('0one0two0three0four0five0six0seven0eight0nine'.split(0)[prompt()])

```

# 69

```
alert(btoa("ôéÞõ5õ1ëxO_¢êý|ÞöÈ±õ'xß^hSôØ§{Ý").split(9)[prompt()])

```
> 9 votes

# Answer
# Perl, 55

```
$_=(nine,eight,seven,six,five,four,three,two,one)[-$_]

```

It is run with option `-p` (+1 byte), e.g.:

```
perl -pe '$_=(nine,eight,seven,six,five,four,three,two,one)[-$_]'

```

Input is expected in STDIN and output is written to STDOUT.

The code just generates an array and selects the right element. Option `-p` takes care of reading the input line into `$_` and prints the result in `$_`.

**Variations:**

* With trailing new line (+3):

```
$_=(nine,eight,seven,six,five,four,three,two,one)[-$_].$/

```

or (same byte count):

```
s/./(nine,eight,seven,six,five,four,three,two,one)[-$&]/e

```

**Update:**

* Using bare words instead of `qw[...]` (thanks Zaid).
* Negative index saves a byte (thanks aragaer).
> 8 votes

# Answer
## Oracle SQL - 46

```
select to_char(to_date(&1,'j'),'jsp')from dual

```

Demonstration

This does include a standard loophole, I admit, but the SQL is shorter than Golfscript; I couldn't resist!

It works by (ab)using Oracle's datetime format models. `TO_DATE(n, 'j')` converts a number into a Julian day, the number of days since January 1, 4712 BC. `TO_CHAR(<date>, 'jsp')` converts this back into the integer (though as a string). The `sp`, is a format element suffix that spells the number. This'll actually work with quite a lot of numbers.

The `&1` is a substitution variable that'll only work with clients that accept it, for instance SQL\*Plus.
> 7 votes

# Answer
# CJam, ~~45~~ 43 bytes

```
"^AM-^L8M-xM-^L^US^_M-^WrM-rM- 1M-s^CHM-|M-X^HE,M-qM-^EM-q4"256bKb'ef+'j/li=

```

The above uses ^ and M- notation, since some characters are unprintable.

At the cost of 9 more bytes, unprintable characters can be avoided:

```
" one two three four five six seven eight nine"S/li=

```

Try it online.

### How it works

```
" Convert the string into an integer by considering it a base-256 number.                ";

"^AM-^L8M-xM-^L^US^_M-^WrM-rM- 1M-s^CHM-|M-X^HE,M-qM-^EM-q4"256b

" Convert the integer from above into an array by considering it a base-20 number.       ";

Kb

" Add the ASCII character code of “e” to all elements of that array. This casts to char. ";

'ef+

" So far, we've pushed the string “jonejtwojthreejfourjfivejsixjsevenjeightjnine”.       ";

" Split the the above string where the character “j” occurs.                             ";

'j/

" Read an integer from STDIN and push the corresponding substring.                       ";

li=

```

### Example

```
$ base64 -d > convert.cjam <<< IgGMOPiMFVMfl3LyoDHzA0j82AhFLPGF8TQiMjU2YktiJ2VmKydqL2xpPQ==
$ wc -c convert.cjam
43 convert.cjam
LANG=en_US cjam convert.cjam <<< 5
five

```
> 6 votes

# Answer
# GolfScript, 51 bytes

```
~'
one
two
three
four
five
six
seven
eight
nine'n/=

```

It's a simple lookup table. The input is evaluated (`~`), an array of the values is created, and the index is found.

Try it here
> 5 votes

# Answer
# bash say (OS X): ~~3~~ 8

"Your goal is to convert a whole number between 1-9 into the word it represents"

Last time I checked, spoken words are words as well. Previous attempt (accepts no input)

~~`say 4`~~

Edit, must be able to read input:

```
say|read

```

Type any number and the word comes out. I know the end date is due, but in my opinion I should have won the contest.

Example audio file: four.aiff
> 5 votes

# Answer
# Python 2.x - ~~65~~ 64

Not as good as @grc 's answer, but certainly more legible :-)

```
'one two three four five six seven eight nine'.split()[input()-1]

```

One less char, thanks to @flornquake

```
'nine eight seven six five four three two one'.split()[-input()]

```
> 4 votes

# Answer
# Perl, 60 bytes

```
$_=(ZOneTwoThreeFourFiveSixSevenEightNine=~/.[a-z]*/g)[$_]

```

Requires the `-p` switch (two bytes).

### Example

```
$ perl -p convert.pl <<< 5
Five

```

### How it works

* `-p` reads from STDIN and saves the result in `$_`.
* `=~/.[a-z]*/g` splits the preceding bareword into substrings of one (uppercase) letter followed by any number of lowercase letters.
* `(…)` collects the substrings into an array.
* `[$_]` retrieves the substring corresponding to the user input.
* `$_=…` saves the result in `$_`.
* `-p` prints the value of `$_`.
> 4 votes

# Answer
# Bash + coreutils, 64

# Non-competitive compression concept

```
xxd -p<<<TàPnàõ:àsÀ~®@ãCN|tr 0-9a-d \\ng-inor-x|sed -n $1p

```

Some of the exotic characters here may not render well, so this script may be reconstructed from its base64 representation:

```
base64 -d <<< eHhkIC1wPDw8VOCLUIJu4PWWDzrgc8B+rkDjEoBDTnx0ciAwLTlhLWQgXFxuZy1pbm9yLXh8c2VkIC1uICQxcA==

```

### Example output

```
$ ./n.sh 1
one
$ ./n.sh 9
nine
$

```

### Explanation

It occurred to me that the string `one two three four five six seven eight nine` contains only the letters `efghinorstuvwx` and a space separator - 15 character values in total. Thus each character can potentially be represented in 4 bits, or 2 characters per 1 byte. We can use the hex representation of a byte as an easy way to split each byte into two hex digits. We can then transform the hex digits back to the letters we require using `tr` or similar. As luck would have it, `rstuvwx` are consecutive, so may be expressed as `r-x` to `tr`. The encoding is arranged such that `e` and `f` are left as-is, and that the words are line-break separated, so we can use `sed` to ouptut just the line we need.

This decoding process ends up using a fair amount of extra space, so makes this answer non-competitive as a shell-script-style answer, but may be a useful concept in other languages.
> 4 votes

# Answer
## DOS Batch - 162 Chars (incl' line breaks)

This answer was inspired by @grc's Python answer, although I did have something similar in mind.

```
@setlocal enabledelayedexpansion
@set s="ottffssennwhoiieiieoruvxvgn  ere ehe  e   nt
@set /a c=%1
@set z=!s:~%c%,1!
@if _%z%==_ exit /b
@echo %z%
@%0 %c%+9

```

Usage:

\[Filename\] \[number\]

For example, if the code is in a file called speak.bat, and you want to see the number "five", you would run it as:

`speak 5`

Also, the output is top-to-bottom, not left-to-right! So instead of

> five

you will see

> f
> i
> v
> e
> 3 votes

# Answer
# (pure) Bash, 64

Takes input as its first argument, assuming valid input.

```
v=(o one two three four five six seven eight nine)
echo ${v[$1]}

```

Creates an array `v`, then accesses the element specified on the input. Since arrays are zero-indexed, I had to add a 0th element as a placeholder. Alternatively (thnx @DennisWilliamson for pointing this out):

```
v=(one two three four five six seven eight nine)
echo ${v[$1-1]}

```
> 3 votes

# Answer
# Perl 36 (58 standalone)

```
use Number::Spell;say spell_number<>

```

Or, without additional modules:

```
say qw(one two three four five six seven eight nine)[<>-1]

```
> 3 votes

# Answer
## Java 7 - 185

```
class Num{
public static void main(String[] args) {
    System.out.print("ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".split(",")[(new java.util.Scanner(System.in)).nextInt()-1]);
    }}

```
> 3 votes

# Answer
# C 111

```
#include <stdio.h>
int main(){printf("%.5s","one  two  threefour five six  seveneightnine"+5*(getchar()-'1'));}

```

The length here is carefully engineered so I can interpret it as binary and convert *that* to decimal. At only 7 characters, I'm confident I have a winner!
> 3 votes

# Answer
## VBScript 98 80 75

```
msgbox split(" one two three four five six seven eight nine")(inputbox(""))

```
> 2 votes

# Answer
# PHP, ~~93~~ ~~73~~ 68 bytes

```
<?=explode(' ','one two three four five six seven eight nine')[1-1];

```

Try it Online!
> 2 votes

# Answer
# Ruby 64

```
p %w?one two three four five six seven eight nine?[$*[0].to_i-1]

```
> 2 votes

# Answer
# J - ~~68 or 60~~ 57 or 53 bytes

Interactive version (stdin):

```
>one`two`three`four`five`six`seven`eight`nine{~<:".1!:1]1

```

Function version:

```
f=:one`two`three`four`five`six`seven`eight`nine>@{~<:

```

Explanation:

```
f=:one`two`three`four`five`six`seven`eight`nine>@{~<:
                                                   <: Decrease by one
                                                 {~   Get the correct string
                                               >@     Unbox

```

`".(1!:1)1` reads a string and converts it to integer
> 2 votes

# Answer
## Powershell - 91 74

```
[Enum]::ToObject([System.DirectoryServices.ActiveDirectory.HourOfDay],[Console]::Read()-48)

```

Found out how to cast to remove the Enum and ToObject call:

```
[System.DirectoryServices.ActiveDirectory.HourOfDay]([Console]::Read()-48)

```

**How does this work?**

HourOfDay is an enum type so we can use names instead of magic constants. Enum types have a ToString() implementation that gives you the name of the constant value. You can cast an int to an enum. Console.Read() reads a character from the input stream represented as an integer. typing '1' gives 49, substract 48 to get 1, cast to HourOfDay to return 'One'.

Because powershell does a ToString on all objects being written to the output stream and doesn't need the fluff to turn this into an executable this all that is needed besides powershell...
> 2 votes

# Answer
**In AppleScript ; 123 chars.**

```
{"one","two","three","four","five","six","seven","eight","nine"}'s item((display dialog""default answer"")'s text returned)

```

This script takes the input in a dialog. Then it gives the output in AppleScript’s *result*.

*Example :*

* Input : `6`
* Output : `"six"`

Here is a nicer version :

```
set l to {"one","two","three","four","five","six","seven","eight","nine"}
set n to text returned of (display dialog "?" default answer "")
display dialog (l's item n) buttons ("OK") default button 1

```

This version displays the output in a nice dialog.

*Example :*

* Input : `9`
* Output : `nine`

*\[ Answer edited ; slightly improved the dialog for the input ; still 124 chars. Answer edited again ; now 1 char less ! \]*
> 2 votes

# Answer
# CJam - 50

This is a plain ASCII solution that uses HTTP requests (this is allowed in the question):

```
"aj21.com/"r+g

```

On the server there are 9 plain-text files named 1, 2, ..., 9, each containing the corresponding word.

Total size: 14 + 3 ("one") + 3 ("two") + 5 + 4 + 4 + 3 + 5 + 5 + 4 = 50.
It can be golfed more by using a shorter domain.

The online interpreter doesn't support HTTP requests, so the program needs to be run using the java interpreter.
> 2 votes

# Answer
# Batch - 86

Far shorter than the other batch answer, and actually surprisingly competitive.

```
for /f "tokens=%1" %%1 in ("one two three four five six seven eight nine") do echo>%%1

```

Used as `filename.bat number`, and the output is in the form of a file with the name of the correct number.
> 2 votes

# Answer
## BASH 9

shameless Linux-replica of cousincoicane's answer

```
spd-say 1

```

speaks out one
> 2 votes

# Answer
# GolfScript, 50 bytes

I wanted to see if I could beat Quincunx's 51-byte self-contained GolfScript solution. Turns out that, with enough tricks, yes, I can — by one byte.

Since one of the tricks I'm using is the use of bytes outside the printable ASCII range, the resulting program is cannot be directly pasted here. Instead, I'm providing a hex dump of it; users on Unixish systems can use `xxd -r` to reconstruct the actual 50-byte GolfScript program from the hex dump:

```
0000000: 7e6e 270b 97eb 442f e166 9894 9f00 c63c  ~n'...D/.f.....<
0000010: 8128 73a3 9b55 5065 a9fb f06a 2727 ff16  .(s..UPe...j''..
0000020: 277b 6261 7365 7d2f 2b6e 2f3d 7b39 392b  '{base}/+n/={99+
0000030: 7d25                                     }%

```

The basic trick used to generate this program is simple: I compress the long string literal that makes up most of Quincunx's code by subtracting 99 (the ASCII code of the letter `c`) from the character values, interpreting the resulting values as a number in base 22 (enough to encode the letters up to `x`) and then re-encode the resulting number in base 255 to produce the unprintable byte string that makes up most of the first half of my program. The rest of the program then reverses this process, decoding the string back into something printable.

(Since the lowest letter actually present in the number names is `e`, I could've shortened the byte string further by subtracting 101 from the ASCII codes and using base 20. However, subtracting 101 would've mapped the letter `o` to a newline, which I'm using as the number delimiter because it's conveniently available as the built-in constant `n` in GolfScript. Working around that would cost me more than the one byte that using a lower base would save. Using the offset 99 leaves the newline corresponding to the letter `m`, which is conveniently absent from the number names.)

Here's a de-golfed version of the program:

```
~       # eval the input, turning it into a number
n       # push a newline onto the stack; we'll need it later

# this is the byte string encoding the number names:
"\x0B\x97\xEBD/\xE1f\x98\x94\x9F\x00\xC6<\x81(s\xA3\x9BUPe\xA9\xFB\xF0j"

# convert the encoded string from base 255 to base 22
# (and, incidentally, from a string to an array):
"\xFF\x16" {base}/

+       # prepend the newline pushed earlier to the array, re-stringifying it
n/      # split the resulting string at newlines
=       # pick the substring corresponding to the input number
{99+}%  # add 99 to the character values in the chosen substring

```
> 2 votes

# Answer
# Jelly, 35 bytes

```
ị“¡5ç“¡Ḃḥ“¡Ị¿“Ɱ9“ƁẆ“¡⁹)“¡°Ṗ“z⁷“¡'Ṡ»

```

Try it online!

Explanation:

```
 “¡5ç“¡Ḃḥ“¡Ị¿“Ɱ9“ƁẆ“¡⁹)“¡°Ṗ“z⁷“¡'Ṡ» List of numbers 1-9 as words.
ị                                   xth element of y.

```
> 2 votes

# Answer
# APL, 54 bytes

```
⎕⊃↓9 5⍴'ONE  TWO  THREEFOUR FIVE SIX  SEVENEIGHTNINE '

```
> 2 votes

# Answer
## Tcl, 61

Number entered as command line argument

```
lindex {- one two three four five six seven eight nine} $argv

```
> 1 votes

# Answer
# F# - 101

```
printf"%s"["one";"two";"three";"four";"five";"six";"seven";"eight";"nine"].[System.Console.Read()-49]

```

For a newline but 108 bytes, change `printf` to `printfn`.

It's a naïve solution that just fetches the given index of that hardcoded list. I would have loved to use base64 encoding and/or a regex to split a string into an array (so the elements would be separated with  instead of `";"`), but both of those would just make the solution longer, due to namespaces. Why can't they just be in `System` like everything else? :'(
> 1 votes

# Answer
# Racket / R5RS Scheme: ~~71~~ 68

```
(vector-ref'#(z one two three four five six seven eight nine)(read))

```

*It runs in the REPL of R6RS and R7RS with base library loaded too.*
> 1 votes

# Answer
I know I'm not going to win but I just want to participe...

**C++11 172**

```
   #include <iostream>
    int main(){ auto a = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };printf("%s", *(a.begin() + getchar() - '0' - 1));}

```

**Javascript - ~~79 - 69~~ 68**: (run on dev console)

~~\["one", "two", "three", "four","five","six","seven","eight","nine"\]\[prompt()-1\]~~

~~"one,two,three,four,five,six,seven,eight,nine".split(',')\[prompt()-1\]~~

```
",one,two,three,four,five,six,seven,eight,nine".split(',')[prompt()]

```
> 1 votes

# Answer
# C++11 - 133

My answer in C++:

```
#include<iostream>
main(){char*n[]={"one","two","three","four","five","six","seven","eight","nine"};std::cout<<n[std::cin.get()-'1'];}

```

The total amount of bytes is 133.
> 1 votes

# Answer
## Objective-C - 154 bytes

This one is kind of cheating a little bit because Objective-C has a built in class just for this but I don't see anything in the rules that says I can't do that so here it is!

```
int i;
scanf("%d",&i);
NSNumberFormatter *f=[[NSNumberFormatter alloc] init];
[f setNumberStyle:5];
NSString *s=[f stringFromNumber:@(i)];
NSLog(@"%@",s);

```
> 1 votes

# Answer
**Ruby 68**

```
v=%w(one two three four five six seven eight nine);p v[gets.to_i-1]

```

Would love tips on how to get it down further!
> 1 votes

# Answer
# Shell, 42 bytes

```
cat $1

```

This relies on files in the current directory, one for each digit. The lengths of the files are included in the score:

```
ubuntu@ubuntu:~/n$ ls -l
total 40
-rw-rw-r-- 1 ubuntu ubuntu 3 Jun 22 11:39 1
-rw-rw-r-- 1 ubuntu ubuntu 3 Jun 22 11:40 2
-rw-rw-r-- 1 ubuntu ubuntu 5 Jun 22 11:40 3
-rw-rw-r-- 1 ubuntu ubuntu 4 Jun 22 11:40 4
-rw-rw-r-- 1 ubuntu ubuntu 4 Jun 22 11:41 5
-rw-rw-r-- 1 ubuntu ubuntu 3 Jun 22 11:41 6
-rw-rw-r-- 1 ubuntu ubuntu 5 Jun 22 11:41 7
-rw-rw-r-- 1 ubuntu ubuntu 5 Jun 22 11:41 8
-rw-rw-r-- 1 ubuntu ubuntu 4 Jun 22 11:41 9
-rwxrwxr-x 1 ubuntu ubuntu 6 Jun 22 11:42 n.sh
ubuntu@ubuntu:~/n$

```

Example Output:

```
$ ./n.sh 4
four$
$ ./n.sh 7
seven$
$

```
> 1 votes

# Answer
## Apple Swift : 143

Not a winner, but my first Code-Golf, so hello everyone!

```
for i in 1..C_ARGC{print(["zero","one","two","three","four","five","six","seven","eight","nine"][String.fromCString(C_ARGV[Int(i)]).toInt()!])}

```

What I like about this is that the lookup table is defined in place in `print` so I could shave a few chars by removing the variable definition for it.

Accepts any number of input arguments, provided that they are separeted with spaces.
> 1 votes

# Answer
## R, 67 characters

```
scan(t='one two three four five six seven eight nine',w='')[scan()]

```

First part creates a vector containing the names, second part subset it according to user input (indices are 1-based in R).
> 1 votes

# Answer
# PowerShell (71)

```
PS > "one,two,three,four,five,six,seven,eight,nine".split(",")[$(read-host)]

```

Works for valid inputs.
> 1 votes

# Answer
## Javascript, ~~94~~ ~~92~~ 84 bytes

```
alert(['one','two','three','four','five','six', 'seven','eight','nine'][prompt()-1])

```
> 1 votes

# Answer
# C - ~~93~~ ~~91~~ ~~89~~ 88 bytes (thanks Cool Guy)

```
main(x){scanf("%d",&x);write(1,5*--x+"one  two  threefour five six  seveneightnine",5);}

```

Old version with arguments instead of `scanf`:

```
main(int c,char**a){write(1,"one  two  threefour five six  seveneightnine"+*a[1]*5-245,5);}

```

# Cryptic version (?):

This one is somewhat longer but at least no space is wasted on spaces (only tabs and newlines ... and one space in function header).

```
main(int c,char**a){
    *a="039018342675onetwosixfourfivenineseveneightthree";
    c=*(*a+*a[1]-46)-39;
    write(1,c/3*(c-9)-*(*a+c/3-3)+60+*a,c/3);
}

```

Magic sequence `018342675` can be calculated as `x+=6*!(x%3)-1;x%=9;` but in the end I decided to use strings for everything.

Yet another version (different arrangement of numbers, easier to calculate position):

```
main(int c,char**a){
    *a="038146257onefourseventwofiveeightsixninethree";
    c=*(*a+*a[1]-49)-45;
    write(1,*a+c*4+!(c%3)-4,3+c%3);
}

```
> 1 votes

# Answer
# sed 90

It's really a trivial program (the brute force method); I wouldn't have bothered, except that it beats a surprising number of answers here.

```
s/9/nine/
s/8/eight/
s/7/seven/
s/6/six/
s/5/five/
s/4/four/
s/3/three/
s/2/two/
s/1/one/

```
> 1 votes

# Answer
# Powershell 63

```
(-split"X one two three four five six seven eight nine")[$args]

```

(The default delimiter in Powershell is whitespace)
> 1 votes

# Answer
**Python 3 + Japanese - 34 characters (52 bytes)**

Not sure if this counts:

```
print('九八七六五四三二一'[-int(input())])

```

Numbers were taken from:

http://en.wikipedia.org/wiki/Japanese\_numerals
> 1 votes

# Answer
# Sclipting (34)

```
껆뭮뉒롴덶묬덆둲뉖넬뉦뭵댢롦늗뉥껇꽩뎂롳뉗뉥닢롥늖덨덂롮늖멥壹坼⓶掘

```

---

This is very straight-forward. Remember the user input is first on the stack.

`껆뭮뉒롴덶묬덆둲뉖넬뉦뭵댢롦늗뉥껇꽩뎂롳뉗뉥닢롥늖덨덂롮늖멥`

* Push the string `",one,two,three,four,five,six,seven,eight,nine"`

* Retrieve the first character from that string (but leave the string on the stack)

* Regular expression string-split. Result: `["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]`

* Swap the top two elements (so the input is now on top)

* Get *n*th element from the list, leaving only the result on the stack.
> 1 votes

# Answer
**In Java (7 and newer) ; 116 chars**

```
public class A{public static void main(String[] a){System.out.print(Character.getName(48+Integer.parseInt(a[0])));}}

```

This program takes the input number as command-line argument, and outputs the letters in the console.

*Example :*

* Input : `4`
* Output : `DIGIT FOUR`
> 1 votes

# Answer
**In AppleScript ; 53 chars.**

```
say(display dialog""default answer"")'s text returned

```

Here is a nicer version :

```
set n to text returned of (display dialog "?" default answer "")
say n

```

This script takes the input in a dialog. Then it tells the output to the user. The user does not even have to read ! This solution works even for people who are unable to read.
> 1 votes

# Answer
# Haskell 75

I know I'm a little late to the party, but thought I might as well:

```
fmap(words"_ One Two Three Four Five Six Seven Eight Nine"!!)readLn>>=print

```
> 1 votes

# Answer
## Racket 159 bytes

```
(string-join(map(λ(x)(list-ref(list"zero""one""two""three""four""five""six""seven""eight""nine")(string->number(string x))))(string->list(number->string n))))

```

Ungolfed:

```
(define(f n)
  (string-join
   (map (λ (x)
          (list-ref [list "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"]
                    (string->number(string x))))
        (string->list (number->string n)))))

```

Testing:

```
(f 10357)

```

Output:

```
"one zero three five seven"

```

17 bytes can be saved if number is sent enclosed in double quotes:

```
(define(f n)
  (string-join
   (map (λ (x)
          (list-ref [list "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"]
                    (string->number(string x))))
        (string->list n))))

(f "10357")
"one zero three five seven"

```
> 1 votes

# Answer
# Wolfram, 11

There is a function for that of course: `IntegerName`
> 1 votes

# Answer
# Factor, 11 bytes

a builtin: `number>text`.
> 1 votes

# Answer
# Lexurgy, 79 bytes

```
a:
{\1,\2,\3,\4,\5,\6,\7,\8,\9}=>{one,two,three,four,five,six,seven,eight,nine}

```

Simple substitution.
> 1 votes

# Answer
# Vyxal, 2 bytes

```
∆ċ

```

Try it Online!

Builtin.
> 1 votes

# Answer
**POSIX SHELL: 68**

Similar to Eric's Bash, without the bashisms (using set to mimick an array using $@) and eval to handle indirection (in bash this could just be `echo ${!A}` without the eval)

```
A=$1
set one two three four five six seven eight nine
eval echo \$$A

```
> 0 votes

# Answer
# Rebol - 58

```
pick[one two three four five six seven eight nine]do input

```

Example from Rebol console:

```
>> pick[one two three four five six seven eight nine]do input
9
== nine

```
> 0 votes

# Answer
# Python

here is a simple answer. In python, if you have a key-val mapping pair, you use a dict. this program waits for an input, (0-9) and converts it

```
n={
1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',0:'zero'}
print n.get(int(raw_input()))

```
> 0 votes

# Answer
## Ruby - 66

```
$><<%w[a one two three four five six seven eight nine][gets.to_i]

```
> 0 votes

# Answer
# Zozotez Lisp: ~~122~~ 78

```
((\(1 2 3 4 5 6 7 8 9)(p(e(r))))'one'two'three'four'five'six'seven'eight'nine)

```

*Zozotez is a LISP-1 interpreter written in Extended BrainFuck. It's only data types are symbols and cons and supports first class functions and macros*
> 0 votes

# Answer
# Extended BrainFuck: 130

```
{z(-))}{b&z)<(-}+>,49-(-(-(-(-(-(-(-((-)<-|<nine<&z<(-|<eight<&b
|<seven<&b|<six<&b|<five<&z)<(-|<four<&b|<three<&b|<two<&b|<one<&z

```

*EBF is a superset of BrainFuck but it has not it's own runtime. It compiles to pure BrainFuck.*
> 0 votes

# Answer
**Forth (gforth)**

```
36 base ! nine eight seven six five four three two one 0

```

Usage:

```
1 pick . ONE  ok
2 pick . TWO  ok
3 pick . THREE  ok
4 pick . FOUR  ok
5 pick . FIVE  ok
6 pick . SIX  ok
7 pick . SEVEN  ok
8 pick . EIGHT  ok
9 pick . NINE  ok

```

where `ok` is printed by the interpreter. In fact, I do not know how to count characters in this. One might even say that this is not a program.
> 0 votes

# Answer
## swipl: 104 bytes

```
get_char(C),number_codes(X,[C]),nth0(X,[o,one,two,three,four,five,six,seven,eight,nine,ten],Y),write(Y).

```

## Brainfuck: 672 bytes

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

```
> 0 votes

# Answer
## Haskell : 89

```
do x<-readLn;print$[[],"one","two","three","four","five","six","seven","eight","nine"]!!x

```
> 0 votes

# Answer
# PHP 5.5 (62)

```
<?=[0,one,two,three,four,five,six,seven,eight,nine][$argv[1]];

```

If you read from standard input it goes up to 66 characters.

```
<?=[0,one,two,three,four,five,six,seven,eight,nine][fgetc(STDIN)];

```
> 0 votes

# Answer
# Bash, 64

```
d=(z one two three four five six seven eight nine)
echo ${d[$1]}

```

Takes the first argument as a number and uses it as an array index to print the corresponding word.
> 0 votes

# Answer
# Python 34 / 28

For this code to work, you have to install `num2words` module. Also thanks to @undergroundmonorail for his suggestion.

```
import num2words
num2words(input())

```

If `input()` is not necessary , and user is allowed to enter number directly into code, then

```
import num2words
num2words(3)

```

will also work.
> 0 votes

# Answer
# C, ~~92~~ 89 bytes Japanese(Hiragana , Katakana)

Hiragana (ひらがな)

```
h(n){char*h="いちに　さんし　ご　ろくななはちきゅ";printf("%.6s%s",h+--n*6,n^9?"":"う");}

```

Katakana (カタカナ)

```
k(n){char*k="イチニ　サンシ　ゴ　ロクシチハチキュ";printf("%.6s%s",k+--n*6,n^9?"":"ウ");}

```

http://sp.cis.iwate-u.ac.jp/sp/lesson/j/doc/numbers.html

ideone it!
> 0 votes

# Answer
# ///, ~~80~~ 79 bytes

```
/_/\/\///0/zero_1/one_2/two_3/three_4/four_5/five_6/six_7/seven_8/eight_9/nine/

```

Append the number at the end of the code (this is ///'s input).
> 0 votes

# Answer
# Sprects, 61 bytes

```
#<INPUT>#9nine#8eight#7seven#6six#5five#4four#3three#2two#1one#0zero

```

Replace `<INPUT>` with the number, because Sprects does not have any other form of input (bytecount is without the "input".)
> 0 votes

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


# Question
Title: Write a program that is valid after circular character shift
Potentially very difficult, but I've seen some amazing things come out of this site.

The goal is to write a program, in any language, that does whatever you want. The catch is that the program must be valid after **any** circular shift of the characters.

A circular character shift is very similar to a Circular Shift. Some examples my clear things up.

For the program `int main() { return 0; }`

shifting to the left by 6 characters yields: `in() { return 0; }int ma`

shifting to the left by 1 character yields: `nt main() { return 0; }i`

shifting to the right by 10 character yields: `eturn 0; }int main() { r`

However, this program obviously doesn't comply with the rules.

# Rules

* Any language
* Winner is decided by up-vote count
* Solutions which do the same thing, or completely different things for each rotation, will receive 100 virtual up-votes to their score.

**UPDATE** I think this has gone on long enough. The winner, with the most votes (virtual votes included) is Mark Byers. Well done!

# Answer
Use the right language for the task. In this case, that's **Befunge**.

This language naturally allows rotations because:

* All commands are a single character.
* The control wraps around when it reaches the end of the program, starting again from the beginning.

This Befunge program prints the exact same output ("Hello") regardless of how many "circular character shifts" you use:

```
86*01p75*1-02p447**1-03p439**04p439**05p455**1+06p662**07p75*1-08p645**2-09p69*4+019+p57*029+p59*1-039+p555**1-049+p88*059+p86*01p75*1-02p447**1-03p439**04p439**05p455**1+06p662**07p75*1-08p645**2-09p69*4+019+p57*029+p59*1-039+p555**1-049+p88*059+p645**2-00p645**2-00p

```

It runs on Befungee. It requires that the board is increased (not the 80 character default). It can be run like this:

```
python befungee.py -w400 hello.bef

```

It works by first dynamically generating and storing a program that prints "Hello" and then overwriting the first byte to redirect the control into the newly written program. The program is written twice so that if a byte is not written correctly the first time, it will be corrected the second time.

The idea could be extended to produce any program of arbitrary complexity.
> 31 votes

# Answer
## Brainf\*ck

Choose the right tool for the job -- an adage that's never been more relevant than this job right here!

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.+.>++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++.++++++++++++++.>++++++++++.+

```

The unshifted program you see here simply prints `SHIFT` (plus a newline). Abitrarily circular shifts will produce various other outputs, though it will always output six ASCII characters.
> 22 votes

# Answer
## Commodore 64 BASIC

`?` is short for `PRINT`, and `:` is a statement separator, so:

```
?1:?2:?3:          // prints 1, 2, and 3
:?1:?2:?3          // prints 1, 2, and 3
3:?1:?2:?          // adds a program line 3 :PRINT1:PRINT2:PRINT
?3:?1:?2:          // prints 3, 1, and 2
:?3:?1:?2          // prints 3, 1, and 2
2:?3:?1:?          // adds a program line 2 :PRINT3:PRINT1:PRINT
?2:?3:?1:          // prints 2, 3, and 1
:?2:?3:?1          // prints 2, 3, and 1
1:?2:?3:?          // adds a program line 1 :PRINT2:PRINT3:PRINT

```

Longer variations are, of course, possible:

```
?1:?2:?3:?4:?5:?6:?7:?8:?9:?10:?11:

```

etc...
> 12 votes

# Answer
### Golfscript

This program prints some digits that always sum up to 2, regardless of how the program is shifted:

```
10 2 base
0 2 base1
 2 base10
2 base10
 base10 2
base10 2
ase10 2 b
se10 2 ba
e10 2 bas

```

The first line prints `1010` (10 in binary), the second line prints `02` and all the other lines print `2`.

**Update:**

The program can be tested here. *Please note that I've added `n`s at the end of each row only for formatting the output; these can be removed and the program still works.*
> 11 votes

# Answer
Ruby, probably one of the shortest possible solutions:

```
p

```

And another slightly longer and more interesting one:

```
;;p";p;";p

```
> 10 votes

# Answer
Unary Answer:

```
000000 ... 00000

```

^44391 Zeros

Cat program. No matter how you rotate, it's the same program.
> 8 votes

# Answer
# x86 16 bit binary

Manually constructed with the help of these ( ) tables, nasm and ndisasm. This will always return without a crash or infinite loop, because no bytes are jumps or change the stack and it is filled with NOPs to end with a single byte `ret` instruction in any case.

In most cases this will output `FOO` or a substring of that. If `AX` is broken, this will call a random int 10 (this changed the cursor blinking speed in one of my tests), but it usually does not result in a crash.

To try out, put the hexdump in a file and use `xxd -r foo.hex > foo.com`, then run in a dos environment (I used dosbox).

Here is a hex dump of this file:

```
0000000: b846 0d90 90fe c490 9090 bb05 0090 9043  .F.............C
0000010: 43cd 1090 b84f 0d90 90fe c490 9090 bb05  C....O..........
0000020: 0090 9043 43cd 1090 b84f 0d90 90fe c490  ...CC....O......
0000030: 9090 bb05 0090 9043 43cd 1090 9090 c3    .......CC......

```

And some interesting disassembled offsets:

## +0

```
00000000  B8420D            mov ax,0xd42
00000003  90                nop
00000004  90                nop
00000005  FEC4              inc ah
00000007  90                nop
00000008  90                nop
00000009  90                nop
0000000A  BB0500            mov bx,0x5
0000000D  90                nop
0000000E  90                nop
0000000F  43                inc bx
00000010  43                inc bx
00000011  CD10              int 0x10
00000013  90                nop
00000014  B84F0D            mov ax,0xd4f
00000017  90                nop
00000018  90                nop
00000019  FEC4              inc ah
0000001B  90                nop
0000001C  90                nop
0000001D  90                nop
0000001E  BB0500            mov bx,0x5
00000021  90                nop
00000022  90                nop
00000023  43                inc bx
00000024  43                inc bx
00000025  CD10              int 0x10
00000027  90                nop
00000028  B84F0D            mov ax,0xd4f
0000002B  90                nop
0000002C  90                nop
0000002D  FEC4              inc ah
0000002F  90                nop
00000030  90                nop
00000031  90                nop
00000032  BB0500            mov bx,0x5
00000035  90                nop
00000036  90                nop
00000037  43                inc bx
00000038  43                inc bx
00000039  CD10              int 0x10
0000003B  90                nop
0000003C  90                nop
0000003D  90                nop
0000003E  C3                ret

```

(for the examples below, the rest of the binary is still valid)

## +1

```
00000000  42                inc dx
00000001  0D9090            or ax,0x9090
00000004  FEC4              inc ah
00000006  90                nop

```

## +2

```
00000001  0D9090            or ax,0x9090
00000004  FEC4              inc ah
00000006  90                nop

```

## +6

```
00000000  C4909090          les dx,[bx+si-0x6f70]
00000004  BB0500            mov bx,0x5
00000007  90                nop
00000008  90                nop
00000009  43                inc bx
0000000A  43                inc bx
0000000B  CD10              int 0x10

```

## +11

```
00000000  050090            add ax,0x9000
00000003  90                nop
00000004  43                inc bx
00000005  43                inc bx
00000006  CD10              int 0x10

```

## +12

```
00000000  00909043          add [bx+si+0x4390],dl
00000004  43                inc bx
00000005  CD10              int 0x10

```

## +18

```
00000000  1090B84F          adc [bx+si+0x4fb8],dl
00000004  0D9090            or ax,0x9090
00000007  FEC4              inc ah
00000009  90                nop

```

(other offsets are just repetitions of the above)

## +58

```
00000000  10909090          adc [bx+si-0x6f70],dl
00000004  C3                ret

```
> 8 votes

# Answer
### PHP

Here you go, a valid PHP program:

```
Is this still funny?

```
> 6 votes

# Answer
### Scala

A nested quotes:

```
""""""""""""""""""""""""""""""""

```

### ~~C++/Java/C#/~~Scala

Comment:

```
///////////////////////////////////

```

Empty command:

```
;;;;;;;;;;;;;;;

```

### Bash

Comment, Whitespace and Shell builtin combination:

```
#

:

```

### Sed

Standalone valid commands:

`p` `P` `n` `N` `g` `G` `d` `D` `h` `H`

A combination of the above:

`p;P;n;N;g;G;d;D;h;H;`

### AWK

To print every line of the file:

```
1

```

or

```
//

```

Don't print anything:

```
0

```

### Perl

```
abcd

```
> 6 votes

# Answer
# J

First, a script to check valid rotations of a program `s`:

```
check =: 3 :'((<;(". :: (''Err''"_)))@:(y |.~]))"0 i.#y'

```

For example, the program `+/1 5` (sum of 1 and 5) gives:

```
 check '+/1 5'
┌───────┬───┐
│┌─────┐│6  │
││+/1 5││   │
│└─────┘│   │
├───────┼───┤
│┌─────┐│Err│
││/1 5+││   │
│└─────┘│   │
├───────┼───┤
│┌─────┐│Err│
││1 5+/││   │
│└─────┘│   │
├───────┼───┤
│┌─────┐│6  │
││ 5+/1││   │
│└─────┘│   │
├───────┼───┤
│┌─────┐│6  │
││5+/1 ││   │
│└─────┘│   │
└───────┴───┘

```

Then, a boring, valid program:

```
check '1x1'
┌─────┬───────┐
│┌───┐│2.71828│ NB. e^1
││1x1││       │
│└───┘│       │
├─────┼───────┤
│┌───┐│       │ NB. Value of variable x11
││x11││       │
│└───┘│       │
├─────┼───────┤
│┌───┐│11     │ NB. Arbitrary precision integer
││11x││       │
│└───┘│       │
└─────┴───────┘

```
> 5 votes

# Answer
# dc

dc programs are easily valid in any rotation. For example:

```
4 8 * 2 + p  # 34
8 * 2 + p 4  # stack empty / 10
...

```
> 2 votes

# Answer
# k

```
.""

```

Evaluates an empty string

```
"."

```

Returns a period character

```
"".

```

Returns partial application of '.' (dyanic form) to an empty character list.
> 2 votes

# Answer
## Machine Code

How about Z80 / Intel 8051 machine code for NOP.

Sure it does No Operation, but it DOES take up a cycle or two... you can have as many or as few of them as you want.

And I disagree with **Ruby** answer above - I think a single byte 00h is shorter than a Ruby `p`.
> 1 votes

# Answer
### sh, bash

```
cc
cc: no input files

```

cc rotated is cc again, but it is not very friendly if called so naked.

```
dh
dh: cannot read debian/control: No such file or directory
hd

```

dh **debhelper** isn't very cooperative too, while **hexdump** just waits for input.

```
gs
sg

```

**Ghostscript** starts interactive mode, while **switch group** shows a usage message - a valid solution here, imho, too.

And here is the script to find candidates for such programs:

```
#!/bin/bash
for name in /sbin/* /usr/sbin/* /bin/* /usr/bin/*
do
    len=${#name}
    # len=3 => 1:2 0:1, 2:1 0:2
    # len=4 => 1:3 0:1, 2:2 0:2, 3:1 0:3
    for n in $(seq 1 $((len-1)))
    do
        init=${name:n:len-n}
        rest=${name:0:n}
        # echo $init$rest
        which /usr/bin/$init$rest 2>/dev/null >/dev/null && echo $name $init$rest $n
    done
done

```

If finds longer sequences too, like (arj, jar) or (luatex, texlua) which aren't valid after every shift, but only after some certain shifts, which I misread in the beginning, but there are few, so it is easy to filter them out by hand.
> 1 votes

# Answer
Trivial Python example:

```
"a""b""c""d""e""f""g""h""i""j""k""l""m""n""o""p""q""r""s""t""u""v""w""x""y""z""";print

```

May be shifted three chars over repeatedly to reveal more and more of the alphabet.
> 0 votes

# Answer
# Python

```
123456789.0

```

Just evaluate some numbers
> 0 votes

# Answer
**dc** is already used, but the following program **always outputs the same**, no matter the rotation :D

```
d

```

ouputs

```
dc: stack empty

```
> 0 votes

# Answer
# APL, 1 byte

Prints empty array. If the program should print something clearly visible:

```
⍬⍬

```

Prints a nested array, consisting of two empty arrays:

```
┌┬┐
│││
└┴┘

```

In addition, I tried to come up with a program that does something radically different with each shift.

`*1⍝` Prints 2.718281828
`1⍝*` Prints 1
`⍝*1` Prints nothing

However, the question arises whether the last line can be considered a program that does something, because it is just a comment that does nothing.
> 0 votes

---
Tags: popularity-contest, source-layout
---


title: Next Special String

text:
# Question
Title: Next Special String
# Special String

We call a binary string \\$S\\$ of length \\$N\\$ special if :

* substring \\$S\[0:i+1\]\\$ is lexicographically strictly smaller than substring \\$S\[i+1:N\]\\$ for \\$ 0\leq i\leq N-2\\$,

> Note: \\$ S\[a:b\] \\$ is substring \\$S\[a\]S\[a+1\]...S\[b-1\]\\$

Given a binary string \\$T\\$ of length \\$N\\$ we are interested in the first special binary string of length \\$N\\$ that is lexicographically greater than \\$T\\$, if it doesn't exist print any consistent output.

assume : \\$ 2\leq N \leq 300\\$ (just to make it even more interesting)

Examples :

* \\$T\\$= \\$0101110000\\$ the next lexicographic special string is \\$0101110111\\$
* \\$T\\$= \\$001011\\$ the next lexicographic secial string is \\$001101\\$
* \\$T\\$= \\$011\\$ the next lexicographic special string doesn't exist print \\$-1\\$ (can print any consistent value)
* \\$T\\$= \\$001101110111111\\$ the next lexicographic special string is \\$001101111001111\\$
* \\$T\\$= \\$010000000000000\\$ the next lexicographic special string is \\$010101010101011\\$
* \\$T\\$= \\$01011111111111111111111111\\$ the next lexicographic special string is \\$01101101101101101101101111\\$

This is , so the shortest answer in bytes per language that can execute in restricted \\$ O(n^4)\\$ time complexity (here \\$n\\$ is the length of string) wins.

Copyable Test case :

```
  0101110000 -> 0101110111

  001011 -> 001101

  011 -> -1(can print any consistent value)

  001101110111111 -> 001101111001111

  010000000000000 -> 010101010101011

  01011111111111111111111111 -> 01101101101101101101101111

```

Sandbox

# Answer
# Python, 91 bytes (@tsh)

```
f=lambda s,j=0:f(max(s,f"{int(s[:j]+s[:-j]or s,2)+1:0{len(s)}b}"),j+1)if s[j:]else(s<"1")*s
```

Attempt This Online!

### Previous Python, 98 bytes

```
f=lambda s,j=0:f(f"{max(t:=int(s,2),t&-1<<n-j|(t>>j)+1):0{n}b}",j+1)if((n:=len(s))>j)else(s<"1")*s
```

Attempt This Online!

Returns empty string for failure.

### How?

The basic idea is to fix all the requirements from left to right: If s\[:i\]\>=s\[i:\] increase s\[i:\] just enough to make it the larger operand. If i\<n/2 we just need to replace the first i digits of s\[i:\] with those of s (and fill with zeros to the end). If i\>=n/2 we need to replace s\[i:\] with the first n-i digits of s and add 1.

However, to streamline the logic we do the second branch all the time. This should be ok if we knew that another correction will happen before or at position 2i. But if nothing happens before 2i then at 2i we have essentially the same comparison as we had at i (at least for the i most significant bits).
> 9 votes

---
Tags: code-golf, string, restricted-time, restricted-complexity
---


title: Nth Ngonal Numbers

text:
# Question
Title: Nth Ngonal Numbers
Most of us are probably familiar with the concept of triangular and square numbers. However, there are also pentagonal numbers, hexagonal numbers, septagonal numbers, octagonal numbers, etc. The Nth Nagonal number is defined as the Nth number of the sequence formed with a polygon of N sides. Obviously, N \>= 3, as there are no 2 or 1 sided closed shapes. The first few Nth Ngonal numbers are 0, 1, 2, 6, 16, 35, 66, 112, 176, 261, 370, 506, 672, 871.... This is sequence A060354 in the OEIS.

## Your Task:

Write a program or function that, when given an integer n as input, outputs/returns the Nth Nagonal number.

## Input:

An integer N between 3 and 10^6.

## Output:

The Nth Nagonal number where N is the input.

## Test Case:

```
25 -> 6925
35 -> 19670
40 -> 29680

```

## Scoring:

This is , lowest score in bytes wins!

# Answer
> 13 votes
# Neim, 1 byte

¯\\\_(ツ)\_/¯

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~7~~ 6 bytes

Saved 1 byte thanks to *Neil*

```
<ÐP+>;

```

Try it online!

**Explanation**

```
<        # push input-1
 Ð       # triplicate
  P      # product of stack
   +     # add input
    >    # increment
     ;   # divide by 2

```

# Answer
> 5 votes
# Jelly, 5 bytes

```
c3×3+

```

Try it online!

Computes choose(n, 3) × 3 + n.

This translates quite readily to 05AB1E:

# 05AB1E, 5 bytes

```
3c3*+

```

Try it online!

# Answer
> 4 votes
# PowerShell, ~~34~~ 28 bytes

```
param($n)$n*($n*$n-3*$n+4)/2

```

Try it online!

Closed-form solution golfed from the OEIS page. Used FOIL for another 6 byte savings.

# Answer
> 4 votes
# Japt, ~~9~~ 8 bytes

```
´U+³ z Ä

```

Try it

* 1 byte saved thanks to ETH

---

## Explanation

Decrement (`´`) the input (`U`), add the input cubed (`³`) to that, floor divide by 2 (`z`) and add 1 (`Ä`).

# Answer
> 4 votes
# Pyke, 6 bytes

```
t3^+he

```

Try it here!

```
t      - Decrement.
 3^    - Raise to the power of 3.
   +   - Add the input.
    h  - Increment.
     e - Floor Halve.

```

# Answer
> 3 votes
# Python 2, 23 bytes

```
lambda n:(~-n)**3-~n>>1

```

Try it online!

# Answer
> 3 votes
# MATL, 7 bytes

```
t3Xn3*+

```

Luis Mendo's suggestion, which is a little clearer.

```
    (implicit input)
t                         duplicate
 3Xn                      n choose 3
    3*                    multiply by 3
      +                   add
(implicit output)

```

Try it online!

```
t:3XNn+

```

Try it online!

Both solutions port Lynn's algorithm

```
(implicit input)
t                         duplicate
 :                        range (1...n)
  3XN                     push 3, compute all 3-combinations of the range
     n                    number ( equal to 3*choose(n,3) )
      +                   add
(implicit output)

```

# Answer
> 2 votes
# Python 2, ~~25~~ 24 bytes

* Saved one byte thanks to Neil; golfed `>>1` to `/2`.

```
lambda n:n*(n*n-3*n+4)/2

```

Try it online!

# Answer
> 2 votes
# Recursiva, 11 bytes

```
*Ha+-Sa*3a4

```

Try it online!

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

```
f=(n,k=n)=>k<2|n<3?k:f(n-1,k)+f(3,k-1)

```

Recursion FTW (or maybe only for seventh...)

# Answer
> 2 votes
# Mathematica, 14 bytes

shorter than built-in!!!

```
(#^2-3#+4)#/2&

```

Try it online!

and 3 bytes shorter with Martin Ender's help

# Answer
> 2 votes
# Cubix, ~~20~~ 17 bytes

Saved 3 bytes porting Emigna's answer.

```
Iu(:^\:**p+u@O,2)

```

Try it online!

```
    I u
    ( :
^ \ : * * p + u
@ O , 2 ) . . .
    . .
    . .

```

### original answer:

```
Iu-2^\:*p*qu@O,2+p*:

```

Try it online!

Expands to the cube

```
    I u
    - 2
^ \ : * p * q u
@ O , 2 + p * :
    . .
    . .

```

which implements the `(n*(n-2)^2+n^2)/2` approach.

# Answer
> 1 votes
# Ohm v2, 3 bytes

```
DÆ¤

```

Try it online!

# Answer
> 1 votes
# Mathematica, 20 bytes

```
#~PolygonalNumber~#&

```

# Answer
> 1 votes
# Pyth, 7 bytes

```
+*3.cQ3

```

**Try it here!**

Uses Lynn's algorithm.

# Answer
> 1 votes
# dc, 13 bytes

```
dd2-2^*r2^+2/

```

A fairly straightforward implementation of the first formula listed on the OEIS page.

```
# Commands           # Stack Tracker (tm)
# Begin with input   # n
d                    # n n
d                    # n n n
2-                   # n-2 n n
2^                   # (n-2)^2 n n
*                    # n*(n-2)^2 n
r                    # n n*(n-2)^2
2^                   # n^2 n*(n-2)^2
+                    # n*(n-2)^2+n^2
2/                   # (n*(n-2)^2+n^2)/2 # matches first formula
# End with output on stack

```

# Answer
> 1 votes
# Japt, 7 bytes

```
à3 *3+U

```

**Try it here!**

First, it was a comment on Shaggy's answer, but they told me I should post it myself.

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
ÅU

```

Try it online!

### How?

¯\\\_(ツ)\_/¯

# Answer
> 1 votes
# HOPS, 17 bytes

```
{n*(n*n-3*n+4)/2}
```

Attempt This Online!

Using the generating function given on OEIS by R. J. Mathar:

# HOPS, 23 bytes

```
x*(1-2*x+4*x^2)/(1-x)^4
```

Attempt This Online!

Or using the exponential generating function given on OEIS by Paul Barry:

# HOPS, 24 bytes

```
(exp(x)*(x+x^3/2)).*{n!}
```

Attempt This Online!

-3 bytes thanks to alephalpha

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

```
{x*(((x*x)-(3*x))+4)%2}

```

Try it online!

Having to add parenthesis because K parses from right-to-left.

# Answer
> 0 votes
# Jelly, 6 bytes

```
’*3+‘H

```

Try it online!

Uses Emigna's algorithm inspired by Neil.

# Answer
> 0 votes
# cQuents 0, 16 bytes

```
#|1:A(AA-3A+4)/2

```

Try it online!

# Answer
> 0 votes
# Java 8, 18 bytes

```
n->n*(n*n-3*n+4)/2

```

Try it here.

The approach used by most other answers is the shortest in Java. For funsies I also ported two other answers:

Port of Mr. Xcoder's Python 2 answer (**29 bytes**):

```
n->(int)Math.pow(n-1,3)-~n>>1

```

Try it here.

Port of Lynn's Jelly answer (with manual calculation of `a choose b`) (**76 bytes**):

```
n->c(n,3)*3+nint c(int t,int c){return t<c?0:c==t|c==0?1:c(--t,c-1)+c(t,c);}

```

Try it here.

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


title: Fill in the lakes

text:
# Question
Title: Fill in the lakes
Given the topography of land in ASCII picture format, figure out where lakes would go and fill them in. Assume an infinite amount of rain.

## example

**input**

```
         #
         ##
      # ####
#    #########
##  ###########
## #############   ####
## ##############  #####
################# #######
#########################
#########################

```

**output**

```
         #
         ##
      #@####
#@@@@#########
##@@###########
##@#############@@@####
##@##############@@#####
#################@#######
#########################
#########################

```

The input will contain only spaces and `#` marks. Each line will be the same length. The output should be the identical `#` pattern with spaces where water would accumulate filled in with `@` marks.

The bottom input row will always be all # marks. There will be no holes or overhangs in the land. Shortest code wins.

# Answer
> 9 votes
## sed -r, 27 24 (27 with `-r`)

24 (27):

```
:;s/(#|@) ( *#)/\1@\2/;t

```

27 (30):

```
:e;s/([#@]) ( *#)/\1@\2/;te

```

Competes with the better of the two perl solutions

# Answer
> 8 votes
## Perl, 25

```
s/# +#/$_=$&;y| |@|;$_/ge

```

# Answer
> 6 votes
## Perl (\>= v5.9.5), 24 chars

Run with `perl -p`:

```
1while s/#.*\K (?=\S)/@/

```

This requires Perl 5.9.5 or later to use the special escape `\K`.

# Answer
> 3 votes
## Windows PowerShell, 36 ~~74~~ ~~138~~

```
$input-replace'(?<!^ *) (?! *$)','@'

```

# Answer
> 3 votes
## Retina, 10 bytes

Retina is (much) newer than this challenge. But this solution is too neat not to post it:

```
T` `@`#.*#

```

Try it online.

This is simply a transliteration stage which replaces spaces with `@`, but the operation is restricted to matches of `#.*#`, i.e. characters which are surrounded by land on both sides.

# Answer
> 2 votes
## Ruby 1.8, 30 characters

```
#!ruby -p
gsub(/# +#/){$&.tr" ","@"}

```

If anyone has an idea why this doesn't work in Ruby 1.9 (tested with 1.9.2p0 and 1.9.2p204), even though the documentation says it should work, let me know!

# Answer
> 1 votes
# Python, ~~95~~ 92 bytes

```
for s in S.split('\n'):b=s.find('#');e=s.rfind('#');print s[:b]+s[b:e].replace(' ','@')+s[e:]

```

# Answer
> 1 votes
# 05AB1E, ~~17~~ 16 bytes

```
|εγć?D¨ð'@:sθJJ,

```

Try it online.

**Explanation:**

```
|            # Take all input-lines as list
 ε           # For each line:
  γ          #  Split the line into chunks of consecutive equal characters
             #   i.e. " ##   # " → [' ','##','   ','#',' ']
   ć         #  Split into head and the rest of the list
             #   i.e. [' ','##','   ','#',' '] → ['##','   ','#',' '] and ' '
    ?        #  Print this head
   D         #  Duplicate the rest of the list
    ¨        #  Remove the last element
             #   i.e. ['##','   ','#',' '] → ['##','   ','#']
     ð'@:    #  Replace every space with a "@"
             #   i.e. ['##','   ','#'] → ['##','@@@','#']
     sθ      #  Swap so the duplicated list is at the top, and take the last item as is
             #   i.e. ['##','   ','#',' '] → ' '
         JJ  #  Join the lists and individual items in the list together to a single string
             #   i.e. ['##','@@@','#'] and ' ' → "##@@@# "
           , #  Print with trailing new-line

```

# Answer
> 1 votes
# Pip, 15 bytes

```
aR:`#.*#`_TRs'@

```

Takes input as a multiline string via command-line argument: Try it online! (Alternately, specify the `-rn` flags and change the first `a` to `g`, and you can give input via stdin: Try it online!)

Same idea as the Retina answer: replace every match of the regex `#.*#` with the result of transliterating space to `@` in the match. Pip can't match Retina's terseness for a pure regex problem--but it's not everyday that you can tie with Jelly, after all.

# Answer
> 1 votes
# Vyxal, 20 bytes

```
□⟑Ġvṅḣ$₴:Ṫ\@Ḟ$¤ptJṅ,

```

Try it Online!

## How?

```
□⟑Ġvṅḣ$₴:Ṫ\@Ḟ$¤ptJṅ,
□                    # All inputs wrapped in a list
 ⟑                   # Open an apply lambda, apply for each:
  Ġvṅ                # Group consecutive identical characters
     ḣ               # Head extract, push a[0], a[1:]
      $              # Swap
       ₴             # Print without a trailing newline
        :Ṫ           # Duplicate and remove the last item
          \@Ḟ        # Replace all spaces with "@"
             $       # Swap
              ¤p     # Prepend an empty string for the case that the list is empty
                t    # Last item
                 J   # Join top two things on the stack together
                  ṅ  # Join by nothing
                   , # Print with trailing newline

```

# Answer
> 1 votes
# Javascript (ES6), 44 bytes

```
x=>x.replace(/# +#/g,s=>s.replace(/ /g,"@"))

```

# Answer
> 0 votes
# Python, 108 106 92 bytes

```
import re
n=1
while n: S,n=re.subn('# +#',lambda m:'#'+'@'*len(m.group(0)[2:])+'#',S)
print S

```

# Answer
> 0 votes
# Javascript, 107 bytes

```
var f=function(x){return x.replace(/# +#/g, function(x){return "#"+new Array(x.length-1).join("@")+"#";})};

```

Ungolfed:

```
var f = function(x) {
    return x.replace(/# +#/g, function(x){
        return "#" + new Array(x.length - 1).join("@") + "#";
    })
};

```

# Answer
> 0 votes
# Jelly, 15 bytes

```
Ỵ”@ẹ”#ṂrṀḟƲ$¦€Y

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Unicode), 28 bytes

```
'# +#'⎕R{'@'@(' '∘=)⍵.Match}

```

Try it online!

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


title: Tile stacking with ■ and □

text:
# Question
Title: Tile stacking with ■ and □
In this challenge you will receive as input a list of binary lists. The list represents a game board with each element representing a location on the board. The list at each location represents the tiles on the board, with a `0` being a white tile (□) and a `1` being a black tile (■). Each place can have any number of tiles and the order they appear in the list indicates how they are stacked, with the first element being the tile on the top of the stack and the last being on the bottom of the stack.

For example here's a input list and a graphical representation of the game board:

```
[[0,0,1],[],[1,1],[1],[],[1,0]]

□
□   ■     ■
■   ■ ■   □
-+-+-+-+-+-

```

On a turn of this game the player can move by choosing any one place on the board and picking up all the tiles from that place, without disrupting their order. Then the player must choose a direction, either left or right. Then starting from the place they chose to pick from, until they have no tiles left in their hand they repeatedly choose to either:

* Drop the tile at the bottom of the held stack at their current place.
* Move to the adjacent place in their chosen direction.

The player is not permitted drop any tiles out of bounds of the game board.

Here's an example turn:

```
□ □
■ ■ ■   ■ ■
■ □ □   □ ■
-+-+-+-+-+-

```

Pick up two tiles from the second place from the left and move to the right:

```
  □
  ■
  □

□
■   ■   ■ ■
■   □   □ ■
-+-+-+-+-+-

```

Drop 1 tile from the bottom back where it was picked up and move to the right:

```
    □
    ■

□
■   ■   ■ ■
■ □ □   □ ■
-+-+-+-+-+-

```

Drop no tiles and move to the right

```
      □
      ■

□
■   ■   ■ ■
■ □ □   □ ■
-+-+-+-+-+-

```

Drop two tiles and end.

```
□
■   ■ □ ■ ■
■ □ □ ■ □ ■
-+-+-+-+-+-

```

With that the goal of this game is simple. Using as few moves as possible arrange the board so that in every place the top tile is black.

Here is an example game:

```
□ □ □ □ □
■ ■ ■ ■ ■
-+-+-+-+-

  ■ □
  □ □ □ □
  ■ ■ ■ ■
-+-+-+-+-

  ■ □
  □ □ □
□ ■ ■ ■ ■
-+-+-+-+-

  ■ □
□ □ □
□ ■ ■ ■ ■
-+-+-+-+-

□
□ ■
□ □
□ ■ ■ ■ ■
-+-+-+-+-

■
□
□
□
□
□ ■ ■ ■ ■
-+-+-+-+-

```

Your task is take the starting board as input and determine the number of moves required to win.

You can assume that the board is at least 2 places wide (the outer list contains at least two lists) and that there are enough black tiles to cover every space on the board (i.e. it is possible to solve)

There are two arbitrary choices I have made. You may swap either, both or neither for the opposite choice:

* `0` is white. You may instead assume `0` is black and `1` is white.
* The first element is the tile on the top. You may instead assume the first element is the tile on the bottom and the last element is the tile on the top.

You may also use suitable substitutions for `0` and `1` such as `True` and `False`, `1` and `-1`, etc.

This is so the goal is to minimize the size of your source code as measured in bytes.

Brute force is fine, but I encourage you to try golf faster algorithms. Good golfs under self imposed constraints on time are always worth an upvote.

## Test cases

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

```

# Answer
> 6 votes
# Python 3, 237 bytes

```
g=lambda a,b,i,j:b and[*g(a[:i]+[[b[-1]]+a[i]]+a[i+1:],b[:-1],i,j),*g(a,b,i+j,j)]or[a]if-1<i<len(a)else[]
f=lambda*b:+all(min(a)<[1]for a in b)and-~f(*sum([g(a[:i]+[[]]+a[i+1:],c,i,j)for a in b for i,c in enumerate(a)for j in[1,-1]],[]))

```

Try it online!

Brute force answer.

# Answer
> 3 votes
# Python3, 714 bytes:

```
E=enumerate
def F(b):
 for i,a in E(b):
  for I,j in E(a):
   if j:yield(i,I,1)
   if 0==any(a[:I])and a[I]:yield(i,I,0)
S=lambda b:sum(i!=[]and i[0]for i in b)
def U(b,c,s,x,y,X,q,Q,h,R):
 B=eval(str(b));B[X]=B[x][:y]+B[X];B[x]=B[x][y:]
 if 0==h:c+=1;h=(X,y,X-x>=0)
 elif h[0]!=x or h[1]<y or(X-x>=0)!=h[2]:h=(X,y,X-x>=0);c+=1
 else:h=[X,h[1]-y,h[2]]
 if(R==[]or c<min(R))and(B,c)not in Q:
  if S(B)>s:q.insert(0,(B,c,h))
  else:q.append((B,c,h))
  Q.append((B,c))
def f(b):
 q,Q=[(b,0,0)],[(b,0)]
 R=[]
 while q:
  B,c,h=q.pop(0)
  if(s:=S(B))==len(B):R+=[c]
  for x,y,r in F(B):
   for X,Y in E(B):
    if x!=X and(Y==[]or Y[0]==0):
     U(B,c,s,x,y,X,q,Q,h,R)
     if r:U(B,c,s,x,y+1,X,q,Q,h,R)
 return min(R)

```

Try it online!

A little longer than it could be, but contains some optimizations.

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

```
f=(a,n=0)=>(F=(a,k)=>a.every(v=>v[0])|a.some((b,i,[...B],g)=>(B[i]=[],g=(d,q=b,x=i,A=B)=>q+q?A[x]&&g(d,q,x+d,A)|g(d,c=[...q],x,A.map(v=>x--?v:[c.pop(),...v])):k&&F(A,k-1))(1)|g(-1)))(a,n)?n:f(a,n+1)

```

Try it online!

### Commented

```
// outer recursive function with n = maximum number of moves
f = (a, n = 0) => (
  // inner recursive function with k = remaining number of moves
  F = (a, k) =>
    // success if all leading terms are 1
    a.every(v => v[0]) |
    // for each b[] at position i in a[]
    a.some((b, i, [...B], g) =>
      // let B[] be a copy of a[] with the i-th term set to []
      ( B[i] = [],
        // g is yet another recursive function taking:
        //   a direction d
        //   a vector q[], initially set to b[]
        //   a position x, initially set to i
        //   an array A[], initially set to B[]
        g = (d, q = b, x = i, A = B) =>
          // if q[] is not empty
          q + q ?
            // if A[x] is defined (i.e. we're not out of bounds)
            A[x] &&
            // do a recursive call where the position is updated
            g(d, q, x + d, A) |
            // do a recursive call where the position is unchanged and
            // the last element of q[] is added at the beginning of A[x]
            g(d, c = [...q], x, A.map(v => x-- ? v : [ c.pop(), ...v ]))
          // if q[] is empty
          :
            // if k is not equal to 0, process the next move
            k && F(A, k - 1)
      )
      // invoke g with d = 1 (moving to the right)
      (1) |
      // invoke g with d = -1 (moving to the left)
      g(-1)
    )
// initial call to F
// return n if successful, or try again with n + 1
)(a, n) ? n : f(a, n + 1)

```

---
Tags: code-golf, array, game
---


title: Output N in base -10

text:
# Question
Title: Output N in base -10
**Challenge:**

In the programming language of your choice, accept an **integer** as input in base 10, and output it in **the negadecimal notation**, which is also known as base -10

**Example algorithm:**

This is an algorithm taken from Wikipedia to convert base 10 to any negative base in VB.NET:

```
Function toNegativeBase(Number As Integer , base As Integer) As System.Collections.Generic.List(Of Integer)

    Dim digits As New System.Collections.Generic.List(Of Integer)
    while Number <> 0
        Dim remainder As Integer= Number Mod base
        Number = CInt(Number / base)

        if remainder < 0 then
            remainder += system.math.abs(base)
            Number+=1
        end if

        digits.Insert(0, remainder)
    end while

    return digits
end function

```

*Obviously, you can use any algorithm, as long as it fulfills the challenge*

**Example inputs / outputs:**

Input:

```
12

```

Output:

```
192

```

**Another example:**

Input:

```
2048

```

Output:

```
18168

```

**Rule:**

You must not use any built-in methods that solve this problem that exist in your programming language

This is a **code-golf**, so shortest code wins!

# Answer
## JavaScript (ES6), ~~51~~ ~~45~~ 37 bytes

```
f=n=>n&&n%10+((k=n<0)+f(k-n/10|0))*10

```

### Test cases

```
f=n=>n&&n%10+((k=n<0)+f(k-n/10|0))*10

console.log("12 -> " + f(12))
console.log("2048 -> " + f(2048))
```
> 12 votes

# Answer
# Japt, 11 bytes

```
_ì ìAn)¥U}a

```

Test it online!

### Explanation

```
_ì ìAn)¥U}a  // Implicit: U = input integer, A = 10
_        }a  // Return the smallest non-negative integer Z that returns a truthy value
             // when run through this function:
 ì           //   Convert Z to a list of its base 10 digits.
   ìAn)      //   Interpret this as a list of base -10 digits and convert to a base 10 integer.
       ¥U    //   Return (the result == U).
             // Implicit: output result of last expression

```
> 5 votes

# Answer
# Jelly, 9 bytes

```
Dḅ-10=ð1#

```

This is a brute-force inverse of negadecimal-to-integer conversion.

Try it online!

### How it works

```
Dḅ-10=ð1#  Main link. Argument: n

      ð    Combine the links to the left into a chain and start a new, dyadic
           chain with left and right argument n.
       1#  Repeatedly execute the chain with left argument k = n, n + 1, ... and
           right argument n until the first match is found.
D          Convert k to decimal.
 ḅ-10      Convert the result from base -10 to integer.
     =     Compare the result with n.

```
> 5 votes

# Answer
## Batch, 82 bytes

```
@set/a"d=%1%%10,n=%1/-10-(a=d>>4),d-=a*10
@if %n% neq 0 %0 %n% %d%%2
@echo %d%%2

```

Batch's division truncates to zero, so if the remainder is negative I need to add 1 (and also add 10 to the remainder) to compensate. The digits are then accumulated in `%2` until the result becomes zero.
> 4 votes

# Answer
# Pyth - 9 bytes

Lel it has the crying emoji in it.

```
fqQijT;_;

```

Test Suite.
> 3 votes

# Answer
# Python 3, 35 bytes

```
f=lambda n:n and n%10+f(0-n//10)*10

```

Python port of Arnauld's algorithm.

Alternatively, for 102 bytes a generic function using the algorithm of the original post:

```
def f(n,b,r=0):
 if n:
  r,n=n%b,n//b
  if r<0:r+=abs(b);n+=1
  return f(n,b,r)+str(r)
 else:return ""

```
> 3 votes

# Answer
# PHP, ~~71~~ 67 bytes

```
for(;$n=&$argn;$n=$g-$n/10|0)$d=($r=$n%10)+10*($g=$r<0).$d;echo+$d;

```

or 62 bytes for a port of Arnauld´s answer:

```
function n($n){return$n?$n%10+(($k=$n<0)+f($k-$n/10|0))*10:0;}

```
> 2 votes

# Answer
# Jelly, 10 bytes

```
:⁵NµÐĿ%⁵ṚḌ

```

Try it online!

### Background

Converting a list of non-negative from base **b** to integer can be achieved by left-folding by the function **x, y ↦ bx + y**. To convert and integer *to* base **b**, we must simply reverse that function, i.e., find an expression for **bx + y ↦ x, y**.

In Python (and, by extension, Jelly), the result of the modulo operator is always non-negative, so **(bx + y) % |b| = y**.

Also, integer division always rounds down, making sure that if **q = n / d** and **r = n % d**, the equality **n = qd + r** holds. If **s** is the sign of **b**, then **(sx)|b| + y = bx + y**, so **sx = (bx + y) / |b|** and, therefore, **s((bx + y) / |b|) = x.**

### How it works

```
:⁵NµÐĿ%⁵ṚḌ  Main link. Argument: n

   µ        Combine the links to the left into a monadic chain.
    ÐĿ      Iteratively apply the chain until the results are no longer unique.
            Collect all unique results in an array.
:⁵            Divide the previous return value (initially n) by 10.
  N           Negate; multiply the result by -1.
      %⁵    Take all results modulo 10.
        Ṛ   Reverse the results.
         Ḍ  Convert from base 10 to integer.

```
> 2 votes

# Answer
# SimpleTemplate, 147 bytes

This is a template language I've been working on.
By no means it is meant to be for golfing.
It even lacks complete basic math, but it allows to write tiny snippets of PHP directly.
This works around that issue.

```
{@setN argv.0}{@whileN}{@setM N}{@php$DATA[N]=($DATA[M]/-10)|0;$DATA[R]=$DATA[M]%-10}{@ifR is lower0}{@incby10 R}{@incN}{@/}{@setD R,D}{@/}{@echoD}

```

This throws a bunch of warnings.
The code is "compiled" into PHP.

Ungolfed, with trash whitespace:

```
{@set no argv.0}
{@while no}
    {@set temp_no no}
    {@php $DATA["no"] = ($DATA["temp_no"] / -10) | 0}
    {@php $DATA["remainder"] = $DATA["temp_no"] % 10}

    {@if remainder is lower than 0}
        {@inc by 10 remainder}
        {@inc no}
    {@/}
    {@set digits remainder, digits}
{@/}
{@echo digits}

```

If required, a set-by-step explanation can be added, but I believe that it is pretty straightforward.

---

**Disclaimer**:

The last commit, as of the time of writting this answer, was on 2017-01-07 20:36 UTC+00:00.
This works on commit 140e56ff38f45fa4fd40fd3ec382094e707b1bad from 2017-01-06 23:27 UTC+00:00.
That is the version used to run this answer.

The PHP code is available on https://raw.githubusercontent.com/ismael-miguel/SimpleTemplate/140e56ff38f45fa4fd40fd3ec382094e707b1bad/SimpleTemplate.php

I do recommend running this with the last version, but that one works fine for this question.

---

**How to run?**

Create a file with the code and run it like this:

```
<?php

    include 'path/to/SimpleTemplate.php';

    $template = new SimpleTemplate('<code>');

    $template->render(<number>);

```

The value will then be displayed on the screen.
> 2 votes

# Answer
# Mathematica, 49 bytes

```
d@0="";d@n_:=d[-Floor[n/10]]<>ToString[n~Mod~10];

```

Defines a function `d` taking one integer argument, and returning a string. A recursive algorithm—looks like the same algorithm in Arnauld's answer. It does work on negative numbers as well. (It returns the empty string intsead of "0" if the input is 0.) Note for Mathematica golfers: using `±` requires one extra set of parentheses and thus seems not to be any shorter.
> 1 votes

# Answer
# 05AB1E, 3 bytes

```
T(в

```

Try it online! This is not a builtin. It uses builtin base conversion, but not builtin negadecimal conversion.

```
T(в  # full program
  в  # base-10 digits of...
     # implicit input...
  в  # in base...
 (   # negative...
T    # 10
     # implicit output

```
> 1 votes

# Answer
# Vyxal, 4 bytes

```
₀Nτṅ

```

Try it Online!

Explanation:

```
  τ   # From base 10 to base
₀     # Ten
 N    # Negated
   ṅ  # Join by nothing
      # Implicitly print

```
> 1 votes

# Answer
# C, 68 bytes

```
main(f,a){f&&scanf("%d",&a);f=a?a%10+((f=a<0)+main(0,f-a/10))*10:0;}

```

Instead of printing the resulting number the program just returns it. Obviously this is Arnauld's answer, the only difference is that since C isn't an interpreted language I felt like I should make it a full program as opposed to just a function.
> 0 votes

# Answer
# Rust, 88 bytes

```
fn g(mut n:i32)->i32{let mut r=n%10;n/=-10;if r<0{r+=10;n+=1;}if n==0{r}else{r+g(n)*10}}

```

This is just a recursive version of the algorithm provided in the question.
> 0 votes

---
Tags: code-golf, math, base-conversion
---


title: Approximate Brun's Constant

text:
# Question
Title: Approximate Brun's Constant
Brun's constant is the value to which the sum of the reciprocals of twin prime pairs (`1/p` and `1/(p+2)` where `p` and `p+2` are both prime) converges. It is approximately `1.902160583104`.

Given a positive integer `N`, approximate Brun's constant by summing the reciprocals of the twin prime pairs where both primes in the pair are less than `N`, and output the approximation.

## Rules

* `N` will be a positive integer within the representable range for your language.
* The output must be as accurate as possible to the true value, within the limits of your language's floating-point implementation, ignoring any potential issues due to floating-point arithmetic inaccuracies. If your language is capable of arbitrary-precision arithmetic, it must be at least as precise as IEEE 754 double-precision arithmetic.
* Alternatively, an exact fraction may be output in any consistent, unambiguous format.
* If a prime appears in multiple twin prime pairs (e.g. `5`, part of both `(3, 5)` and `(5, 7)`), its reciprocal contributes to the sum each time.

## Test Cases

```
2 -> 0
6 -> 0.5333333333333333
10 -> 0.8761904761904762
13 -> 0.8761904761904762
100 -> 1.3309903657190867
620 -> 1.4999706034568274
100000 -> 1.67279958482774

```

# Answer
# Python 3, ~~78~~ ~~77~~ ~~75~~ ~~70~~ ~~68~~ 62 bytes

```
f=lambda n,k=3,m=1,j=0:k<n and-m%k*j*2/k+f(n,k+2,m*k**4,m%k/k)

```

*Thanks to @xnor for golfing off ~~2~~ 4 bytes and paving the way for 4 more!*

Try it online!

### Background

Recall that Wilson's theorem states that for all integers **k \> 1**,

where **a ≡ b (mod d)** means that **a - b** is evenly divisible by **d**, i.e., **a** and **b** have the same residue when divided by **d**.

In Wilson Theorems for Double-, Hyper-, Sub- and Super-factorials, the authors prove generalizations for double factorials, on which this answer builds. The double factorial of an integer **k ≥ 0** is defined by

Theorem 4 of the aforementioned paper states the following.

Elevating both sides of the congruences to the fourth power, we deduce that

for all odd primes **p**. Since **1!! = 1**, the equivalence holds also for **p = 2**.

Now, doing the same to Wilson's theorem reveals that

Since

it follows that

whenever **p** is prime.

Now, let **k** be an odd, positive, composite integer. By definition, there exist integers **a, b \> 1** such that **k = ab**.

Since **k** is odd, so are **a** and **b**. Thus, both occur in the sequence **1, 3, …, k - 2** and

where **|** indicates divisibility.

Summing up, for all odd integers **k \> 1**

where **p(k) = 1** if **k** is prime and **p(k) = 0** if **k** is composite.

### How it works

When the function **f** is called with a single argument, **k**, **m**, and **j** are initialized as **3**, **1**, and **0**.

Note that **((k - 2)!!)4 = 1!!4 = 1 = m**. In fact, the equality **m = ((k - 2)!!)4** will hold at all times. **j** is a *float* and will always be equal to **((k - 4)!!)4 % (k - 2) / (k - 2)**.

While \\$k \< n\\$, the right argument of `and` will get evaluated. Since \\$j = \frac{\mod(\left(\left(k - 4\right)!!\right)^4 , k - 2)}{k - 2}\\$, as proven in the first paragraph, \\$j = \frac{1}{k - 2}\\$ if \\$k - 2\\$ is prime and \\$j = 0\\$ if not. Likewise, since \\$\mod(m,k) = \left(\left(k - 2\right)!!\right)^4\\$ equals \\$1\\$ if \\$k\\$ is prime and \\$0\\$ if not, \\$\mod(-m,k) = k - 1\\$ if \\$k\\$ is prime and \\$\mod(-m , k) = 0\\$ if not. Therefore, `-m%k*j*2/k` evaluates to \\$\frac{2\left(k - 1\right)}{k\left(k - 2\right)} = \frac{\left(k - 2\right) + k}{k(k - 2)} = \frac{1}{k} + \frac{1}{k - 2}\\$ if the pair \\$\left(k - 2, k\right)\\$ consists of twin primes and to \\$0\\$ if not.

After computing the above, we add the result to the return value of the recursive call `f(n,k+2,m*k**4,m%k/k)`. \\$k\\$ gets incremented by \\$2\\$ so it only takes odd values‡†, we multiply \\$m\\$ by \\$k^4\\$ since \\$mk^4 = \left(\left(k - 2\right)!!\right)^4k^4 = \left(k!!\right)^4\\$, and pass the current value of \\$\frac{\mod(m,k)}{k}\\$ – which equals \\$\frac{1}{k}\\$ if the "old" \\$k\\$ is a prime and \\$0\\$ if not – as parameter \\$j\\$ to the function call.

Finally, once \\$k\\$ is equal to or greater than \\$n\\$, \\$f\\$ will return *False* and the recursion stops. The return value of \\$f(n)\\$ will be the sum of all \\$\frac{1}{k} + \frac{1}{k - 2}\\$ such \\$\left(k - 2, k\right)\\$ is a twin prime pair and \\$k \< n\\$, as desired.

---

The results from the *Background* paragraph hold only for odd integers. Since even integers cannot be twin primes, we can skip them safely.
> 26 votes

# Answer
# Jelly, ~~15~~ 14 bytes

```
’ÆRµ_2fµ+2;µİS

```

Try it online!

### How it works

```
’ÆRµ_2fµ+2;µİS  Main link. Argument: n

’               Decrement; yield n-1.
 ÆR             Prime range; yield all primes in [1, ..., n-1].
   µ            New chain. Argument: r (prime range)
    _2          Subtract 2 from all primes.
      f         Filter; keep all p-2 that appear in r.
       µ        New chain. Argument: t (filtered range)
        +2      Add 2 to all primes in s.
          ;     Concatenate with s.
           µ    New chain. Argument: t (twin primes)
            İ   Take the inverses.
             S  Sum.

```
> 7 votes

# Answer
# Jelly, ~~16~~ 14 bytes (with a little help from @Dennis)

```
’ÆRṡ2_/2+$$ÐḟFİS

```

Try it online!

While trying to improve my previous answer, I thought up a totally different algorithm, and it comes in somewhat shorter. I'm using a different post for it, as is the standard here for an answer that uses a different technique.

Dennis suggesting replacing `_/2+$$Ðḟ` with `Iċ¥Ðf2`; I'd completely forgotten about the possibility of a dyadic filter. As such, this algorithm now ties with the one that Dennis' answer used.

## Explanation

```
’ÆRṡ2Iċ¥Ðf2FİS
’                  Decrement.
 ÆR                Primes from 2 to the argument inclusive
                   (i.e. 2 to the original input exclusive).
   ṡ2              Take overlapping slices of size 2.
        Ðf         Keep only elements where the following is true:
       ¥           {the second parse of, which parses like this}
     Iċ   2          the differences (I) contain (ċ) 2
           F       Flatten.
            İ      Take 1/x {for every list element}.
             S     Sum.

```
> 5 votes

# Answer
# Brachylog, 17 bytes

```
{>I-₂:I{ṗ/₁}ᵐ}ᶠc+

```

Try it online!

This is the brand new version of Brachylog, with a shiny code page!

### Explanation

```
{            }ᶠ        Find all valid outputs of the predicate in brackets
               c+      Output is the sum of that list after flattening it

 >I                    Input > I
   -₂:I                The list [I-2, I]
       {   }ᵐ          Map:
        ṗ/₁              Must be prime and the output is its inverse

```
> 4 votes

# Answer
# MATL, 16 bytes

```
liqZqtd2=)t2+h/s

```

Try it online!

Consider input `13` as an example.

```
l     % Push 1
      %   STACK: 1
i     % Input N
      %   STACK: 1, 13
q     % Subtract 1
      %   STACK: 1, 12
Zq    % Primes up to that
      %   STACK: 1, [2 3 5 7 11]
t     % Duplicate
      %   STACK: 1, [2 3 5 7 11], [2 3 5 7 11]
d     % Consecutive differences
      %   STACK: 1, [2 3 5 7 11], [1 2 2 4]
2=    % Compare with 2, element-wise
      %   STACK: 1, [2 3 5 7 11], [0 1 1 0]
)     % Use as logical index to select elements from array
      %   STACK: 1, [3 5]
t     % Duplicate
      %   STACK: 1, [3 5], [3 5]
2+    % Add 2, element-wise
      %   STACK: 1, [3 5], [5 7]
h     % Concatenate horizontally
      %   STACK: 1, [3 5 5 7]
/     % Divide, element-wise
      %   STACK: [0.3333 0.2 0.2 0.1429]
s     % Sum of array. Implicitly display
      %   STACK: 0.8762

```
> 3 votes

# Answer
# 05AB1E, ~~19~~ 14 bytes (-5 @Emigna)

```
<LDpÏÍDpÏDÌ«zO

```

Try it online!
> 3 votes

# Answer
# Mathematica, ~~48~~ 47 bytes

*Thanks to JungHwan Min for saving 1 byte!*

```
If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}&

```

Unnamed function taking a positive integer as input and returning an exact fraction; for example, `If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}&[10]` returns `92/105`.

`If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]` tests whether both `i` and `i-2` are prime, returning the sum of their reciprocals if so and `0` if not. `~Sum~{i,#-1}&` then returns the sum of those contributions for all values of `i` less than the input.

Previous submission:

```
If[And@@PrimeQ@{i,g=i-2},1/i+1/g,0]~Sum~{i,#-1}&

```
> 2 votes

# Answer
## JavaScript (ES6), ~~67~~ 66 bytes

*Saved 1 byte thanks to @Arnauld*

```
f=n=>--n>1&&((p=x=>n%--x?p(x):x==1)(n)&&p(n-=2)&&1/n+++1/++n)+f(n)

```

Outputs `false` for test case `2`, which is allowed by default.

### Test snippet

```
f=n=>--n>1&&((p=x=>n%--x?p(x):x==1)(n)&&p(n-=2)&&1/n+++1/++n)+f(n)

g=n=>console.log("Input:",n,"Output:",f(n))

g(2)
g(6)
g(10)
g(13)
g(100)
g(620)
```
> 2 votes

# Answer
# Octave, 45 bytes

```
@(n)sum(all(isprime(m=[h=3:n-1;h-2]))*m'.^-1)

```

Explanation:

```
m=[h=3:n-1;h-2]             generate an concatenate two ranges 3:n-1 and 1:n-3
rec=m'.^-1                  transpose and reciprocal
idx=all(isprime(m))         create a logical [0 1 ..] array  if both ranges are prime set 1 else set 0
sum1 = idx * rec            matrix multiplication(extrat elements with logical index and sum along the first dimension)
sum(sum1)                   sum along the second dimension

```

Try It Online!
> 2 votes

# Answer
# Jelly, 19 bytes

```
’ÆRḊµ_Æp=2Tịµ_2;µİS

```

Try it online!

I have a feeling that this is improvable, but I can't immediately see how.

## Explanation

```
’ÆRḊµ_Æp=2Tịµ_2;µİS
 ÆR                  Generate all primes from 2 to n inclusive
’                    Subtract 1
   Ḋ                 Remove first element
’ÆRḊ                 Generate all primes from 3 to n-1 exclusive

     _Æp             Subtract the previous prime (i.e. calculate the prime gap)
        =2           Compare to 2
          Tị         Take elements of the input where the comparison is true
     _Æp=2Tị         Filter a list of primes to the latter halves of prime pairs

             _2      Subtract 2
               ;     Append
             _2;     Append the list to the list with 2 subtracted from it
                 İ   Take reciprocals
                  S  Sum
                 İS  Take the sum of the reciprocals

```

The `µ` connect all these portions together pipeline-style, with each taking the output of the one before as its input.
> 1 votes

# Answer
# Pyth - ~~22~~ ~~21~~ 17 bytes

I think that refactoring will help.

```
scL1sf.APM_MTm,tt

```

Test Suite.
> 1 votes

# Answer
# Julia 0.4, ~~48~~ 46 bytes

```
!n=sum(1./[(p=n-1|>primes)∩(p-2);p∩(p+2)])

```

Try it online!
> 1 votes

# Answer
# Perl 6, ~~59~~ 51 bytes

~~`{sum 1 «/»grep((*-(2&0)).is-prime,^$_).flatmap:{$_-2,$_}}`~~

```
{sum 1 «/»grep(*.all.is-prime,(-2..*Z ^$_)).flat}

```

`-2..* Z ^$_` zips the infinite list `-2, -1, 0, 1, ...` with the list `0, 1, ... $_-1` (`$_` being the argument to the function), producing the list `(-2, 0), (-1, 1), (0, 2), ..., ($_-3, $_-1)`. (Obviously none of these numbers less than 3 can be in a prime pair, but `3..* Z 5..^$_` is a few bytes longer, and none of the extra numbers are prime.)

The `grep` selects only those pairs where all (that is, both) numbers are prime, and the `flat` flattens them into a plain list of numbers.

`«/»` is the division hyperoperator; with the list on the right and `1` on the left, it turns the list of prime pairs into their reciprocals, which is then summed by `sum`.
> 1 votes

# Answer
# Clojure, 147 bytes

```
(fn[n](let[p #(if(> % 2)(<(.indexOf(for[a(range 2 %)](mod % a))0)0))](reduce +(for[a(range 2 n)](if(and(p a)(p(- a 2)))(+(/ 1 a)(/ 1(- a 2)))0)))))

```

And Clojure comes dead last, as usual.

Ungolfed:

```
; Returns the primality of a number.
(defn prime? [n]
  (if (> n 2)
    (< (.indexOf (for [a (range 2 n)] (mod n a)) 0) 0)))

; Calculates the actual Brun's Constant. ' (Stupid highlighter)
(defn brunsconst [n]
  ; Adds all of the entries together
  (reduce
    +
    ; For a in range(2, n):
    (for [a (range 2 n)]
      (let [b (- a 2)]
        ; If both a and a-2 are prime:
        (if (and (prime? a) (prime? b))
          ; Place (1/a + 1/a-2) on the array, else 0
          (+ (/ 1 a) (/ 1 b)) 0)))))

```
> 1 votes

# Answer
# APL NARS, 216 bytes, 108 chars

```
  r←z n;h;i;k;v
  i←0⋄n-←1⋄h←1+⍳n-1⋄→B
A:k←i⊃h⋄h←k∪(0≠k∣h)/h
B:→A×⍳(⍴h)≥i+←1
  r←+/÷(v-2),v←(h=1⌽h+2)/h

```

this would use the "Crivello di Eratostene" for find the sublist in 1..arg of request primes. Test:

```
  z¨2 6 10 13 100 620
0 0.5333333333 0.8761904762 0.8761904762 1.330990366 1.499970603
  z 100000
1.672799585

```
> 1 votes

# Answer
# Husk, 14 bytes

```
ṁ\Σfo=2F-Ẋefṗŀ

```

Try it online!

### Explanation

```
ṁ\Σfo=2F-Ẋefṗŀ
             ŀ   lowered range, 0..n-1
           fṗ    filter primes
         Ẋe      get each consecutive pair
   f   F-        filter where difference
    o=2          equals 2
  Σ              concat, list of pairs to flattened list
ṁ\               map 1/n and then sum

```
> 1 votes

# Answer
# Pari/GP, 50 bytes

```
n->forprime(p=s=0.,n,isprime(q=p-2)&&s+=1/p+1/q);s

```

Try it online!
> 1 votes

# Answer
# Vyxal `sḋ`, ~~13~~ 12 bytes

```
~æ2l'÷ε2=;fĖ

```

Try it online or verify all test cases.

Explanation:

```
~             # Filter the range 0 to n-1 by:
 æ            #   Is prime
  2l          # Get the overlapping groups of 2
    '    ;    # Filter those by:
     ÷ε       #   Absolute difference of the list
       2=     #   Equals 2
          f   # Flatten to make one list
           Ė  # Take the reciprocal of each
              # Sum with the s flag
              # Convert to decimal format with the ḋ flag

```
> 1 votes

# Answer
# Bash \+ GNU utilities, ~~86~~ 85 bytes

```
for((k=4;k<$1;k++,j=k-2)){ [ `factor $k $j|wc -w` = 4 ]&&x=$x+1/$k+1/$j;};bc -l<<<0$x

```

Try it online!

Constructs a large arithmetic expression and then feeds it to `bc -l` to evaluate it.

*Edit: Mistakenly left in a $(...) pair from an old version with nested command substitution; changed to backticks to save a byte.*
> 0 votes

---
Tags: code-golf, math, number-theory, primes, approximation
---


title: Find the Fenceposts

text:
# Question
Title: Find the Fenceposts
# Background

An atomic bomb has exploded near the fencepost factory! Since fenceposts are essential for the survival of our civilization, we must rescue as many as possible. We are sending radiation-resistant robots to search the area, and it is your task to program their artificial vision.

# Input

Your input is a rectangular grid of the characters `|-#`, representing two kinds of fencepost parts and rubble, given as a newline-delimited string. The fenceposts have been horribly maimed by the explosion, and some have even been fused together by the heat. We define a **candidate fencepost** to be either a horizontal pattern that starts and ends in `|` and has one or more `-`s between them (like `|-|` or `|---|` but not `||`), or a vertical pattern that starts and ends in `-` and has one or more `|`s between them (essentially a horizontal candidate fencepost rotated 90 degrees). An **actual fencepost** is a candidate fencepost which does not share any of its parts with another candidate fencepost.

# Output

Your output is the number of actual fenceposts in the input grid.

# Example

Consider the input grid

```
|#**|-|**#|##
#||--|||#
###|#|--#
###-|**|--|**
-#-|#-|#-
#---#-#-|
#-#-|#--|

```

There are 5 candidate fenceposts in this grid, but only 2 of them are actual fenceposts (shown in bold). Thus the correct output is `2`.

# Rules

You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

# Additional Test cases

Input:

```
##--
||##
-#|-
|#|#

```

Output: `0` (0 candidate fenceposts)

Input:

```
-##|-##--
#|#-|#||-
--|-#|#||
##||||-##
||#|--|-|
-#|-#--|#
|####|#-#

```

Output: `0` (5 candidate fenceposts)

Input:

```
#|--|---|-|#
####|##--||-
-|-##||#|---
-#|#-|-#-|||
#|-##--###|-
---#-||-#-##
#|---|###|-#
-|---#-#|#|#
|#--|####-|-

```

Output: `4` (8 candidate fenceposts)

Input:

```
-|-||---##|#
---|######-#
####-##|#--|
|||##|#-||||
####-#-||-#|
---#--|#-#--
-|#-####-##-
#||-|-|-###|
|-##||-||-#-

```

Output: `5` (7 candidate fenceposts)

Input:

```
|#-|#|#-###|#-#
----#####|#----
|#--#-##-#|##-|
|#-|#-|--##||--
||#-#---##|||##
#|#-|||-#-#--||
--#|-||#|--|#|#
-#-|###||-#--#|
-#||-|#-##||##|
|--|-|||-##|-#|

```

Output: `4` (9 candidate fenceposts)

Input:

```
||-|-|-##-#-#-|#--#-
-##|-#|-#-##-|#|--|-
||#---###||-|#|##|-#
#||-#-#-|---|#||#|##
-#-###-##-|-#-|-#||#
##-#--#||-----||-|##
-|--#-#-#|---#-#|#-#
###|-|#-#|-|###|#-|#
#||#-#|--|-||#------
||##|-||#-|--#|#-#-#
|#-|-#-|-|--##-#|||#
-|#--#||##---##|-##-
#|-|-|-||-||#-#-|##-
|-#|##|-|#|#|--||#--

```

Output: `9` (30 candidate fenceposts)

# Answer
> 3 votes
# Ruby, 266 ~~268~~ bytes

To get this started. Makes use of the fact that variables point to objects (a 1-char string for each element of the 2D array) to eliminate overlapping candidates.

Eg. if you execute `a="s";b=a`, both `a` and `b` point to the same string. `"test"=="test"` returns true, but `"test".equal?("test")` returns false, because we have created two different String objects.

```
->d{c=->d,f,v,u{i=0
r=[]
d.map{|y|j=0
e=[]
y.map{|x|f[j]||=[]
f[j][i]=x
x==v ?e[1]?r<<e+[x]&&e=[x]:e[0]?e=[x]:e<<x :x==u&&e[0]?e<<x :e=[]
j+=1}
i+=1}
r}
y=c[d.split.map(&:chars),f=[],?|,?-]+c[f,[],?-,?|]
y.count{|x|y.all?{|q|x.equal?(q)||!(q+x).uniq!(&:object_id)}}}

```

Test cases on ideone.

# Answer
> 1 votes
# Python3, 362 bytes:

```
E=enumerate
def P(b,c,X,Y,n,e):
 try:
  if(C:=b[(x:=c[-1][0]+X)][(y:=c[-1][1]+Y)])in[n,e]:
   K=c+[(x,y)]
   if C==n:yield from P(b,K,X,Y,n,e)
   elif len(c)>1:yield{*K}
 except:1
def f(b):c=[q for x,j in E(b)for y,k in E(j)for q in P(b,[(x,y)],*(k=='-',k!='-'),*['-','|'][::[1,-1][k=='-']])if k in['|','-']];return sum(all(not j&i for j in c if j!=i)for i in c)

```

Try it online!

---
Tags: code-golf, ascii-art, grid, counting
---