title: Convert to Suzhou numerals

text:
# Question
Title: Convert to Suzhou numerals
Suzhou numerals (蘇州碼子; also 花碼) are Chinese decimal numerals:

```
0 〇
1 〡 一
2 〢 二
3 〣 三
4 〤
5 〥
6 〦
7 〧
8 〨
9 〩

```

They pretty much work like Arabic numerals, except that when there are consecutive digits belonging to the set `{1, 2, 3}`, the digits alternate between vertical stroke notation `{〡,〢,〣}` and horizontal stroke notation `{一,二,三}` to avoid ambiguity. The first digit of such a consecutive group is always written with vertical stroke notation.

The task is to convert a positive integer into Suzhou numerals.

## Test cases

```
1          〡
11         〡一
25         〢〥
50         〥〇
99         〩〩
111        〡一〡
511        〥〡一
2018       〢〇〡〨
123321     〡二〣三〢一
1234321    〡二〣〤〣二〡
9876543210 〩〨〧〦〥〤〣二〡〇

```

**Shortest code in bytes wins.**

# Answer
# Jelly, 35 bytes

```
9Ḷ;-26ż“/Ẉ8‘+⁽ȷc¤ṃ@ɓD_2ỊŒgÄFị"+⁽-FỌ

```

Try it online!
> 1 votes

# Answer
# JavaScript, 81 bytes

```
s=>s.replace(/./g,c=>(p=14>>c&!p)|c>3?eval(`"\\u302${c}"`):'〇一二三'[c],p=0)

```

Try it online!

Using `14>>c` saves 3 bytes. Thanks to Arnauld.
> 8 votes

# Answer
# , 138 bytes

I'll bet there's an easier way to do this. Use `gsub` to get the alternating numeric positions.

```
function(x,r=-48+~x)Reduce(paste0,ifelse(58<~gsub("[123]{2}","0a",x),"123"["一二三",r],'0-9'["〇〡-〩",r]))
"~"=utf8ToInt
"["=chartr

```

Try it online!
> 8 votes

# Answer
# Retina, 46 bytes

```
/[1-3]{2}|./_T`d`〇〡-〩`^.
T`123`一二三

```

Try it online! Link includes test cases. Explanation:

```
/[1-3]{2}|./

```

Match either two digits 1-3 or any other digit.

```
_T`d`〇〡-〩`^.

```

Replace the first character of each match with its Suzhou.

```
T`123`一二三

```

Replace any remaining digits with horizontal Suzhou.

51 bytes in Retina 0.8.2:

```
M!`[1-3]{2}|.
mT`d`〇〡-〩`^.
T`¶123`_一二三

```

Try it online! Link includes test cases. Explanation:

```
M!`[1-3]{2}|.

```

Split the input into individual digits or pairs of digits if they are both 1-3.

```
mT`d`〇〡-〩`^.

```

Replace the first character of each line with its Suzhou.

```
T`¶123`_一二三

```

Join the lines back together and replace any remaining digits with horizontal Suzhou.
> 7 votes

# Answer
# Perl 5 `-pl -Mutf8`, ~~53~~ 46 bytes

*-7 bytes thanks to Grimy*

```
s/[123]{2}|./OS&$&/ge;y//〇〡-〰一二三/c

```

Try it online!

### Explanation

```
# Binary AND two consecutive digits 1-3 (ASCII 0x31-0x33)
# or any other single digit (ASCII 0x30-0x39) with string "OS"
# (ASCII 0x4F 0x53). This converts the first digit to 0x00-0x09
# and the second digit, if present, to 0x11-0x13.
s/[123]{2}|./OS&$&/ge;
# Translate empty complemented searchlist (0x00-0x13) to
# respective Unicode characters.
y//〇〡-〰一二三/c

```
> 6 votes

# Answer
# Java (JDK), 120 bytes

```
s->{for(int i=0,p=0,c;i<s.length;)s[i]+=(p>0&p<4&(c=s[i++]-48)>0&c<4)?"A䷏乚䷖".charAt(c+(p=0)):(p=c)<1?12247:12272;}

```

Try it online!

## Credits
> 5 votes

# Answer
# JavaScript (ES6),  ~~95 89~~  88 bytes

*Saved 6 bytes thanks to @ShieruAsakoto*

Takes input as a string.

```
s=>s.replace(i=/./g,c=>'三二一〇〡〢〣〤〥〦〧〨〩'[i=112>>i&c<4?3-c:+c+3])

```

Try it online!
> 4 votes

# Answer
# Python 3, 102 bytes

```
f=0
for i in input():f=i in'123'and 9-f;print(end='〇一二三〤〥〦〧〨〩〡〢〣'[int(i)+f])

```

Try it online!

mypetlion reminded me of a trivial golf. -4 bytes.
> 4 votes

# Answer
# Clean, ~~181~~ 165 bytes

All octal escapes can be replaced by the equivalent single-byte characters (and are counted as one byte each), but used for readability and because otherwise it breaks TIO and SE with invalid UTF-8.

```
import StdEnv
u=map\c={'\343','\200',c}
?s=((!!)["〇":s++u['\244\245\246\247\250']])o digitToInt
$[]=[]
$[h:t]=[?(u['\241\242\243'])h:if(h-'1'<'\003')f$t]
f[]=[]
f[h:t]=[?["一","二","三"]h: $t]

```

Try it online!

An encoding-unaware compiler is both a blessing and a curse.
> 2 votes

# Answer
# Red, 198 171 bytes

```
func[n][s: charset"〡〢〣"forall n[n/1: either n/1 >#"0"[to-char 12272 + n/1][#"〇"]]parse
n[any[[s change copy t s(pick"一二三"do(to-char t)- 12320)fail]| skip]]n]

```

Try it online!
> 2 votes

# Answer
# Jelly, 38 bytes

```
9Rż“øƓ“œ%“øƈ’;-25+⁽-EỌœị@DżD<4«Ɗ‘×¥\ƊƊ

```

Try it online!
> 2 votes

# Answer
# C, 131 bytes

```
f(char*n){char*s="〇〡〢〣〤〥〦〧〨〩一二三",i=0,f=0,c,d;do{c=n[i++]-48;d=n[i]-48;printf("%.3s",s+c*3+f);f=c*d&&(c|d)<4&&!f?27:0;}while(n[i]);}

```

Try it online!

Explanation: First of all - I'm using char for all variables to make it short.

Array `s` holds all needed Suzhou characters.

The rest is pretty much iterating over the provided number, which is expressed as a string.

When writing to the terminal, I'm using the input number value (so the character - 48 in ASCII), multiplied by 3, because all these characters are 3 bytes long in UTF-8. The 'string' being printed is always 3 bytes long - so one real character.

Variables `c` and `d` are just 'shortcuts' to current and next input character(number).

Variable `f` holds 0 or 27 - it says if the next 1/2/3 character should be shifted to alternative one - 27 is the offset between regular and alternative character in the array.

`f=c*d&&(c|d)<4&&!f?27:0` \- write 27 to f if c\*d != 0 and if they are both \< 4 and if f isn't 0, otherwise write 0.

Could be rewritten as:

```
if( c && d && c < 4 && d < 4 && f == 0)
f = 27
else
f = 0

```

Maybe there are some bytes to shave off, but I'm no longer able to find anything obvious.
> 2 votes

# Answer
# Perl 6 `-p`, ~~85~~ 61 bytes

*-13 bytes thanks to Jo King*

```
s:g[(1|2|3)<((1|2|3)]=chr $/+57;tr/0..</〇〡..〩一二三/

```

Try it online!
> 1 votes

# Answer
# Ruby `-p`, 71 bytes

```
$_=gsub(/[1-3]\K[1-3]/){|x|(x.ord+9).chr}.tr"0-<","〇〡-〩一二三"

```

Try it online!
> 1 votes

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

```
{,/(0N 3#"〇一二三〤〥〦〧〨〩〡〢〣")x+9*<\x&x<4}@10\

```

Try it online!

`10\` get list of decimal digits

`{` `}@` apply the following function

`x&x<4` boolean (0/1) list of where the argument is less than 4 and non-zero

`<\` scan with less-than. this turns runs of consecutive 1s into alternating 1s and 0s

`x+9*` multiply by 9 and add `x`

juxtaposition is indexing, so use this as indices in...

`0N 3#"〇一二三〤〥〦〧〨〩〡〢〣"` the given string, split into a list of 3-byte strings. k is not unicode aware, so it sees only bytes

`,/` concatenate
> 1 votes

# Answer
# Wolfram Language (Mathematica), 117 bytes

```
FromCharacterCode[12320+(IntegerDigits@#/. 0->-25//.MapIndexed[{a___,c=#2[[1]],c,b___}->{a,c,#,b}&,{0,140,9}+7648])]&

```

Try it online!

Note that on TIO this outputs the result in escaped form. In the normal Wolfram front end, it will look like this:
> 1 votes

# Answer
# C# (.NET Core), 107 bytes, 81 chars

```
n=>{var t="〇一二三〤〥〦〧〨〩〡〢〣";var b=0;return n.Select(k=>t[k+(b+=k>0&k<4?1:b)%2*9]);}

```

Try it online!

Saved 17 bytes thanks to @Jo King

# Old Answer

# ~~C# (.NET Core), 124 bytes, 98 chars~~

```
n=>{var t="〇一二三〤〥〦〧〨〩〡〢〣";var b=0<1;return n.Select(k=>{b=k>0&k<4?!b:0<1;return b?t[k]:t[k+9];});}

```

Try it online!

Takes input in the form of a List, and returns an IEnumerable. I don't know if this input/output is ok, so just let me know if it isn't.

# Explanation

How this works is that it transforms all the integers to their respective Suzhou numeral form, but only if variable `b` is true. `b` is inverted whenever we meet an integer that is one, two, or three, and set to true otherwise. If `b` is false, we turn the integer to one of the vertical numerals.
> 1 votes

# Answer
# C#, 153 bytes

```
n=>Regex.Replace(n+"",@"[4-90]|[1-3]{1,2}",x=>"〇〡〢〣〤〥〦〧〨〩"[x.Value[0]-'0']+""+(x.Value.Length>1?"一二三"[x.Value[1]-'0'-1]+"":""))

```

Try it online!
> 0 votes

# Answer
# Japt, 55 bytes

```
s"〇〡〢〣〤〥〦〧〨〩"
ð"[〡〢〣]" óÈ¥YÉÃ®ë2,1Ãc
£VøY ?Xd"〡一〢二〣三":X

```

Try it online!

It's worth noting that TIO gives a different byte count than my preferred interpreter, but I see no reason not to trust the one that gives me a lower score.

Explanation:

```
    Step 1:
s"〇〡〢〣〤〥〦〧〨〩"        Convert the input number to a string using these characters for digits

    Step 2:
ð                            Find all indexes which match this regex:
 "[〡〢〣]"                    A 1, 2, or 3 character
           ó    Ã            Split the list between:
            È¥YÉ              Non-consecutive numbers
                  ®    Ã     For each group of consecutive [1,2,3] characters:
                   ë2,1      Get every-other one starting with the second
                        c    Flatten

    Step 3:
£                              For each character from step 1:
 VøY                           Check if its index is in the list from step 2
     ?                         If it is:
      Xd"〡一〢二〣三"            Replace it with the horizontal version
                     :X        Otherwise leave it as-is

```
> 0 votes

# Answer
# , 104 bytes

```
function(x,`[`=chartr)"a-jBCD"["〇〡-〩一二三",gsub("[bcd]\\K([bcd])","\\U\\1","0-9"["a-j",x],,T)]

```

Try it online!

An alternative approach in R. Makes use of some Perl-style Regex features (the last `T` param in substitution function stands for `perl=TRUE`).

First, we translate numerals to alphabetic characters `a-j`, then use Regex substitution to convert duplicate occurrences of `bcd` (formerly `123`) to uppercase, and finally translate characters to Suzhou numerals with different handling of lowercase and uppercase letters.

Credit to J.Doe for the preparation of test cases, as these were taken from his answer.
> 0 votes

---
Tags: code-golf, number, unicode
---


title: Rotation invariant fingerprinting

text:
# Question
Title: Rotation invariant fingerprinting
Imagine we have some polyomino and would like to uniquely identify them, however the polyominos can be rotated, so blindly hashing them won't give us the same fingerprint for a piece and a rotation thereof (in general).

For example if we have the L-tetromino

```
x
x
xx

```

we would like it to have the same fingerprint as any of these:

```
         xx
  x       x      xxx
xxx  ,    x  or  x

```

**Note:** We only allow rotations on the plane (ie. they are one-sided polyominos) and therefore the following polyomino would be a different one:

```
 x
 x
xx

```

## Challenge

The task for this challenge is to implement a fingerprinting-function/program which takes an \\$m\times n\\$ Boolean/\\$0,1\\$-valued matrix/list of lists/string/.. encoding a polyomino and returns a string - the fingerprint of a polyomino. The fingerprint must be equal for all of the possible rotations (in general 4).

## Input / Output

* \\$m \geq 1\\$ and \\$n \geq 1\\$ (ie. no empty polyomino)
* you're guaranteed that \\$m,n\\$ are as small as possible (ie. all \\$0\\$ are trimmed to fit \\$m\\$ and \\$n\\$
* you're guaranteed that the input is
    + simply connected
    + has no holes
* output must be a string which is the same for each possible rotation of a polyomino

## Examples

**Here are some equivalence classes, for each class the fingerprint must be the same & for any two polyominos from two distinct classes they must differ.**

The rotations of the L-tetromino from the example:

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

```

The J-tetromino:

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

```

The unit polyomino:

```
[[1]]

```

A \\$5\times 1\\$ bar:

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

```

A \\$2\times 2\\$ corner:

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

```

W-pentomino:

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

```

# Answer
# Python 2, 48 bytes

```
f=lambda l,z=5:z and max(l,f(zip(*l)[::-1],z-1))

```

Try it online!

Takes the largest of the four rotations in terms of list comparison. Based on FlipTack's solution.

The code uses Python 2's ability to compare objects of different types. The base case value of `0` is harmless for `max` because it's smaller than any list. Also, `zip` produces a list of tuples while the input is a list of lists, but tuples are bigger than lists so the input list-of-lists is never a contender. This is why we rotate 5 times rather than 4, so that we get back to a tuplified version of the initial list. (Taking a list of tuples would also work, if that's an allowed form of input.)
> 7 votes

# Answer
# Python 3, 63 bytes

```
def f(m):M=[];exec("m=[*zip(*m[::-1])];M+=m,;"*4);return min(M)

```

Try it online!

Finds the rotation with the lexographical minimum, and prints that.

A lambda form comes in at the same byte count:

```
lambda m,M=[]:exec("m=[*zip(*m[::-1])];M+=m,;"*4)or min(M[-4:])

```

Try it online!
> 4 votes

# Answer
# Jelly, 5 bytes

```
ZU$ƬṂ

```

Try it online!

Full program.

Simply generates all possible rotations and picks the lexicographical minimum.

Note that singleton lists aren't wrapped in `[]` in the output. That doesn't matter, since the only case where singleton lists would exist in the input would be a vertical line (including the unit polyomino), which is the same as a horizontal line with the same size (where the ones aren't wrapped). The only case where the outer `[]` will not exist either is the unit polyomino.
> 2 votes

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

```
{a@*<a:3{+|x}\x}

```

Try it online!

min of rotations

`{` `}` function with argument `x`

`{+|x}` rotate, i.e. reverse (`|`) and transpose (`+`)

`3{` `}\` apply 3 times preserving intermediate results; this returns a list of the 4 rotations

`a:` assign to `a`

`<` ascend (compute the sort-ascending permutation)

`*` first

`a@` index `a` with that
> 2 votes

# Answer
# Clean, 136 bytes

```
import StdEnv,Data.List
r=reverse;t=transpose;f=flatten
$l=[if((a==b)==(c==d))'x''X'\\a<-f l&b<-f(r(map r l))&c<-f(r(t l))&d<-f(t(r l))]

```

Try it online!

Includes test verifier.
> 2 votes

# Answer
# Japt `-g`, 6 bytes

```
4Æ=zÃñ

```

Try it

```
           :Implicit input of 2d-array U
4Æ         :Map the range [0,4)
   z       :  Rotate U 90 degrees
  =        :  Reassign to U
    Ã      :End map
     ñ     :Sort
           :Implicit output of first element

```
> 1 votes

# Answer
# , 16 bytes

-2 bytes thanks to Shaggy

```
[:/:~|.@|:^:(<4)

```

Try it online!

# , 18 bytes

```
0{[:/:~|.@|:^:(<4)

```

Try it online!

Returns the first item in the list of the lexicograpically sorted rotations of the polyomino.

## Explanation:

```
            ^:(<4)  - do the verb on the left 4 times, storing all the steps
       |.@|:        - tranpose and reverse
    /:~             - sort up the 4 matrices
  [:                - cap the fork
0{                  - take the first matrix

```
> 1 votes

# Answer
# 05AB1E, ~~10~~ 8 bytes

```
3FÂø})Σ˜

```

-2 bytes thanks to *@Shaggy*.

Try it online or verify all test cases.

**Explanation:**

```
3F  }       # Loop 3 times
  Â         #  Bifurcate (short for Duplicate & Reverse) the top of the stack
            #  (which is the input-matrix implicitly the first iteration)
   ø        #  Transpose: swap rows/columns
     )      # After the loop, wrap everything on the stack in a list
      Σ˜    # Sort this list of matrices by their flattened array (and output implicitly)

```

NOTE: Taking the minimum with `ß` or `W` will implicitly flatten, so will output `0`. And sorting with `{` doesn't seem to work for a list of matrices, which is why I use `Σ˜` instead.
> 0 votes

---
Tags: code-golf, array, hashing, polyomino
---


title: Count down from "Infinity"

text:
# Question
Title: Count down from "Infinity"
Seems like an impossible task right? Well, it's actually not that hard. If we write the word `Infinity` as 8-bit binary ASCII code, we'll get:

```
01001001 01101110 01100110 01101001 01101110 01101001 01110100 01111001

```

This can be concatenated, and converted to the decimal value `5291279215216915577`. Now that's a number we can work with...

The way you'll count down is:

1. Output the original string as a decimal number (as shown above)
2. Remove leading 0s in its binary representation (if any)
3. Toggle the bits in the binary representation (1-\>0, 0-\>1)
4. Output the number in decimal
5. Repeat steps 2-4 as until you reach 0.

**Challenge:**

Create a program or function that takes a string as input, and outputs (on any suitable format) the numbers you'll get when performing the procedure above.

**Test case:**

I think the challenge will be fairly easy to understand, even though it's only one test case. I'll use `Inf` instead of `Infinity` to keep this fairly short.

```
Inf
4812390  (10010010110111001100110)
3576217  ( 1101101001000110011001)
618086   (   10010110111001100110)
430489   (    1101001000110011001)
93798    (      10110111001100110)
37273    (       1001000110011001)
28262    (        110111001100110)
4505     (          1000110011001)
3686     (           111001100110)
409      (              110011001)
102      (                1100110)
25       (                  11001)
6        (                    110)
1        (                      1)
0        (                      0)

```

```
Input: Inf
Output:
4812390, 3576217, 618086, 430489, 93798, 37273, 28262, 4505, 3686, 409, 102, 25, 6, 1, 0

```

```
Input: Infinity
Output:
5291279215216915577, 3932092821637860230, 679593196789527673, 473328307817319302, 103132444486104185, 40982743589751686, 31074850448176249, 4953946570787718, 4053252683953273, 450346943417222, 112603010004089, 28134478351238, 7049893737593, 1746199284614, 452823970937, 96931842950, 40507110521, 28212366214, 6147372153, 2442562438, 1852404857, 295078790, 241792121, 26643334, 6911097, 1477510, 619641, 428934, 95353, 35718, 29817, 2950, 1145, 902, 121, 6, 1, 0

```

Your code must support strings that can be represented as a binary number up to the limit of your language. All strings will only contain printable ASCII-characters from 32-126 (space to tilde).

---

## Leaderboard

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

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

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

# Answer
> 13 votes
# Jelly, ~~15~~ 10 bytes

-5 bytes thanks to @Dennis (convert directly from base 256 after ordinal cast)

```
Oḅ⁹µBCḄµÐĿ

```

**TryItOnline!**

### How?

```
Oḅ⁹µBCḄµÐĿ - Main link: s                     e.g. "Inf"
O          - cast to ordinals                 e.g. [73,110,102]
 ḅ⁹        - convert from base 256 to integer e.g. 4812390
   µ   µ   - monadic chain separations
    B      -     convert to binary
     C     -     complement
      Ḅ    -     convert to integer
        ÐĿ - loop until no longer unique and collect results

```

# Answer
> 11 votes
# Python 2, ~~89~~ ~~82~~ ~~77~~ ~~76~~ 75 bytes

```
n=0
for c in input():n=n<<8|ord(c)
while 1:print n;n^=2**n.bit_length()-n/n

```

Test it on Ideone.

### How it works

After initializing **n** to **0**, the second line performs the string-to-integer conversion specified in the challenges as follows.

In each step, **n** is shifted **8** units to the left, then bitwise **OR**-ed with the the code point of the next character **c**. For input **Inf**, this goes as follows.

```
n                                  0
a = n<<8                           0
b = 'I'                      1001001
n = a ^ b                    1001001
a = n<<8             100100100000000
b = 'n'                      1101110
n = a ^ b            100100101101110
a = n<<8     10010010110111000000000
b = 'f'                      1100110
n = a ^ b    10010010110111001100110

```

Now we're ready to generate the output. To invert the bits of **n**, we proceed as follows.

First, we compute the bits in **n**'s binary representation without leading zeroes. Let's call the result **k**. Then, we compute the **k**k power of **2**, which has **k+1** binary digits: a single **1**, followed by **k** **0**'s. We subtract **1** from the result, yielding a number composed of **k** ones, which we then XOR with **n** to invert its bits. For input **inf** this goes as follows.

```
n         4812390   10010010110111001100110
k              23
t = 2**k           100000000000000000000000
t -= 1              11111111111111111111111
n ^= t    3576217    1101101001000110011001
k              22
t = 2**k            10000000000000000000000
t -= 1               1111111111111111111111
n ^= t     618086      10010110111001100110
.
.
.
n               6                       110
k               3
t = 2**k                               1000
t -= 1                                  111
n ^= t          1                         1
k               1
t = 2**k                                 10
t -= 1                                    1
n ^= t          0                         0

```

On additional hurdle in the implementation is that we have to print **n** before the first step, *after* the last step, and in all steps in between. Python doesn't have do-while loops and a single *print* statement costs **8** bytes, so we do the following instead.

In the straightforward implementation of the update step, i.e.,

```
while n:print n;n^=2**n.bit_length()-1
print n

```

we replace the loop with an infinite one (`while 1`) and compute the `1` in the loop as `n/n`. This is equivalent while **n \> 0**.

Once **n = 0**, we stay in the loop, print the state once more, then try to update it. However, `0/0` triggers a *ZeroDivisionError*, breaking out of the loop and exiting with an error. Note that this causes stray output to STDERR, which is allowed by default.

# Answer
> 8 votes
# JavaScript, 82 bytes

*Saved a byte thanks to @Arnuald*

```
for(y of prompt(n=0))n=n<<8|y.charCodeAt()
for(;alert(n)|n;)for(i=1;i<=n;i*=2)n^=i
```

One of the very few times when a full program outperforms a function (and ES6 does not outperform ES5)...

---

The above supports up to 4-letter words. Add 4 bytes to support up to 6-letter words:

```
for(y of prompt(n=0))n=n*256+y.charCodeAt()
for(;alert(n)|n;n=i-n-1)for(i=1;i<=n;)i*=2
```

# Answer
> 7 votes
# Actually, 14 bytes

```
2@├¿W■├♂≈♂Y2@¿

```

Try it online!

Explanation:

```
2@├¿W■├♂≈♂Y2@¿
 @├             encode input in binary
2  ¿            convert from binary to decimal
    W           while the number is not 0:
     ■            print the number without popping
      ├           convert number to binary
       ♂≈         convert each character to an int
         ♂Y       boolean negate each int
           2@¿    convert from binary to decimal

```

# Answer
> 6 votes
# 05AB1E, 18 bytes

Uses CP-1252 encoding.

```
Çžz+b€¦J[CÐ,_#bS_J

```

Try it online!

**Explanation**

```
Ç                     # convert string to list of ascii codes
 žz+                  # add 256 to each
    b                 # convert to binary
     €¦               # remove the first digit of each list of digits
       J              # join
        [             # start loop
         C            # convert to decimal
          Ð           # triplicate
           ,          # print 1 copy
            _#        # if the 2nd copy is 0, break loop
              b       # convert 3rd copy to binary
               S      # split to list
                _     # negate each in list
                 J    # join

```

# Answer
> 4 votes
# PHP, ~~132~~ ~~126~~ ~~123~~ ~~120~~ ~~108~~ 107 bytes

```
foreach(unpack("C*",$argv[1])as$i)$n=$n*256+$i;for(print$n;$n;)echo _.$n=bindec(strtr(decbin($n),"01",10));

```
* printing 0 after loop instead of initial value before loop saves 6 bytes.
* `unpack` instead of `str_split` renders `ord()` obsolete -\> -3 bytes
* underscore `_` as separator saves 3.
* `bindec` instead of `ltrim` to remove leading zeroes: -12
* `echo` in loop body saves 1 byte over `print` in loop head.

# Answer
> 4 votes
# MATL, 13 bytes

```
8W:qZA`tB~XBt

```

Try it online!

### Explanation

```
8W:q            % Push array [0 1 ... 255]
    ZA          % Take input string and convert it from the base defined by the
                % alphabet [0 1 ... 255] to decimal
      `         % Do...while
       t        % Duplicate
        B       % Convert to binary
         ~      % Negate
          XB    % Convert to decimal
            t   % Duplicate. Used as loop condition: exit if zero

```

# Answer
> 4 votes
# Mathematica, 99 bytes

```
a=FromDigits;b=IntegerDigits;NestWhileList[a[1-#~b~2,2]&,a[Join@@b[ToCharacterCode@#,2,8],2],#>0&]&

```

Anonymous function. Takes a string as input, and returns a list of numbers as output.

# Answer
> 4 votes
# Haskell, ~~109~~ ~~123~~ ~~118~~ ~~102~~ 97 bytes

Thanks to @nimi for saving 5 bytes!

```
c 0=0
c n=1-mod n 2+2*c(div n 2)
(++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum

```

Usage: `(++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum $ "Infinity"`

Guaranteed to work on numbers up to 29 bits by the language, usually works up to 63-bit numbers on 64-bit systems. Use `map(fromIntegral.fromEnum)` instead (+14 bytes) to support arbitrarily large numbers.

Works for unicode range `[0..255]`. Recursively flips bits.

# Answer
> 4 votes
## Perl, 65 bytes

**53 bytes code + 12 for `-Mbigint -p`.**

Thanks to @Dada for saving me 13 bytes!

```
$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0

```

Fairly straightforward approach, only different to most of these is that the number is stored as binary and printed out in decimal. I'm sure it can be improved, perhaps with storing details in an array. `-Mbigint` is a bit inconvenient but necessary.

### Usage

```
echo -n 'Inf' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0'
4812390
3576217
618086
430489
93798
37273
28262
4505
3686
409
102
25
6
1
0

```

```
echo -n 'Infinity' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0'
5291279215216915577
3932092821637860230
679593196789527673
473328307817319302
103132444486104185
40982743589751686
31074850448176249
4953946570787718
4053252683953273
450346943417222
112603010004089
28134478351238
7049893737593
1746199284614
452823970937
96931842950
40507110521
28212366214
6147372153
2442562438
1852404857
295078790
241792121
26643334
6911097
1477510
619641
428934
95353
35718
29817
2950
1145
902
121
6
1
0

```

# Answer
> 4 votes
# Pyth, 12 bytes

```
.usi!MjN2 2C

```

A program that takes input of a quoted string and prints the result as a list of integers.

Verify all test cases

**How it works**

```
.usi!MjN2 2C  Program. Input: Q
           C  Convert Q to an integer by code-points using base-256 (implicit input)
.u            Apply the following function A(N) until a repeat occurs, storing the results
              in a list:
      jN2       Convert to binary as a list
    !M          Map negation over the above
   i      2     Convert from binary to integer
  s             Integer (Converts final False to 0)
              Implicitly print

```

# Answer
> 3 votes
# Python 2, ~~117~~ 115 bytes

Saving 2 bytes thanks to Cyoce.

Assumes input enclosed in quotes, e.g. `"Inf"`

```
s=input()
n=sum(ord(s[-i-1])<<i*8for i in range(len(s)))
while n:
 print n;k,m=n,1
 while k:k/=2;m*=2
 n^=m-1
print 0

```

`m` counts up to the highest digit, so `m-1` is a XOR mask to perform the desired operation. The longest part is converting the input into the initial bit sequence.

Example:

```
"Inf"
4812390
3576217
618086
430489
93798
37273
28262
4505
3686
409
102
25
6
1
0

"Infinity"
5291279215216915577
3932092821637860230
679593196789527673
473328307817319302
103132444486104185
40982743589751686
31074850448176249
4953946570787718
4053252683953273
450346943417222
112603010004089
28134478351238
7049893737593
1746199284614
452823970937
96931842950
40507110521
28212366214
6147372153
2442562438
1852404857
295078790
241792121
26643334
6911097
1477510
619641
428934
95353
35718
29817
2950
1145
902
121
6
1
0

```

# Answer
> 3 votes
# Python 3, ~~99~~ 95 bytes

```
x=int.from_bytes(bytes(input(),'utf-8'),'big')
while x:print(x);x^=2**x.bit_length()-1
print(0)

```

Main idea is to convert string to bytes to to number. Each iteration print the output and XOR with all 1s to progress towards zero.

# Answer
> 3 votes
# Ruby, ~~104~~ ~~101~~ ~~100~~ ~~81~~ ~~80~~ 65 bytes

*19 bytes saved thanks to @WayneConrad!
15 Bytes saved thanks to @philomory!
1 byte saved thanks to @LeeW!*

```
p n=$*[0].unpack('B*')[0].to_i(2)
p n^=2**n.bit_length-1while n>0

```

Takes input via command line arguments.

Inspired by @JimmyJohnson's Python answer

# Answer
> 3 votes
# Labyrinth, 104 103 bytes

```
'  )25 }_';:_';_2/;{
''', 6 2 1   1   { (
 ' | / _ _   _}*2_ $
 * _ :!\ }2_\     !:
 652       @'''''''

```

Try it Online!

## Explanation:

The instruction pointer starts at the top-left most non-wall character (walls include spaces and any letter except `v`).

### Orange:

This loop gets the input one character at a time as an ASCII code, adding it to the current value and multiplying the current value by 256.

* `'` No-op
* `,` Push the ascii code of the next input char to the top of the stack or -1 if EOF. At this point if input was received, the code will turn right (moving down) because the top of the stack is potive. Otherwise it will turn left because the top of the stack is negative.
* `|` Pop the top two items from the stack and push the result of a bitwise OR.
* `_` Push zero
* `256` Each digit seen pops `x` and pushes `x*10+digit`. So this combined with the push zero previous push 256 to the top of the stack.
* `*` Pop `y`, pop `x`, push `x*y`. At this point since the top of the stack is positive the code will turn right to continue around the loop.

### Blue:

* `)` Increment the top of the stack. When the end of input is reached, the code will turn left to get to this point with a -1 on the stack which will get incremented to zero.
* `256` Having the top of the stack 0 allows us to push this 256.
* `/` Pop `y`, pop `x` push `x/y` (integer division). Since we were multiplying the input by 256 each loop, we need to revert the last multiplication.
* `:` Duplicate the top of the stack so we have a copy of the current value for later.
* `!` Pop the top of the stack and print the integer value to STDOUT.
* `\` Print a new line.
* `_2` Push a two to the top of the stack.
* `}` Move the top of the stack to the top of the auxiliary stack.

### Red:

This loop flips the bits of the current value by XOR with a particular value calculated in the inner (green) loop. It then outputs the current value and exits the program if the current value is zero.

* `_` Push zero (control flow).
* `;` Discard the top of the stack (control flow).
* `:` Duplicate the current value. The copy will be used to calculate the XOR.
* `_` Push zero (control flow).
* (Green loop)
* `$` Pop `y`, pop `x`, Push `x XOR y`.
* `:!` Duplicate the current value and print the integer representation.
* If the current value is 0, we continue straight into the `@` and terminate.
* `\` Print a new line.
* `_2}` Push 2 and move to the aux stack.
* `_1` Push 1 (control flow).

### Green:

This loop calculates the value by which we need to XOR the current value. This is done by repeatedly doubling the top of the auxiliary stack while halving a copy of the current value on the stop of the main stack until it reaches 0.

* `_` Push zero (control flow).
* `;` Discard the current value which is only used to enforce control flow.
* `_2` Push 2 in order to halve the current value.
* `/` Divide
* `{` Move the top of the aux stack to the top of the main stack.
* `_2*` Double the top of the stack
* `}` Move the top of the main stack back to the aux stack.
* `_1` Push one for control flow.
* After exiting the loop:
* `;` Discard the left over zero from calculating the XOR.
* `{` Move the calculated XOR to the main stack.
* `(` Subtract one from XOR value.

# Answer
> 2 votes
## PowerShell v2+, 158 bytes

```
for($a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)});$a){[convert]::ToInt64($a,2);$a=$a.TrimStart('0')-split0-replace1,0-join1}

```

Yeah, so, converting bases in PowerShell is really sucky. And we get to do it twice here.

OK, so this is just a `for` loop on `$a` -- i.e., we loop so long as `$a` exists. We'll eventually reach an empty string (which is falsey), so that's how we'll terminate.

The setup of the loop, `$a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)})`, takes the input `$args[0]`, casts it as a `char`-array, and loops through each character. We use the .NET `[convert]::ToString(int,base)` to convert each to a binary string. However, that doesn't include leading zeros, so we need to re-cast that string as an `[int]` and call *its* `.ToString()` method with `8` zeros as the mask. Then those strings are encapsulated in parens and `-join`ed together, then saved into `$a`.

Inside the loop, we `[convert]::ToInt64(string,base)` to convert the binary number to a decimal number. That gets left on the pipeline and is subsequently flushed when the loop resets (and therefore implicitly printed). The next section performs the calculations -- we `.TrimStart()` to remove any leading zeros, `-split0` to split on zeros and get a `string`-array of `1`s, `-replace` those ones with zeros, and finally `-join` the array back together with `1`s. Then, the loop begins again.

```
PS C:\Tools\Scripts\golfing> .\count-down-from-infinity.ps1 'PPCG'
1347437383
800046264
273695559
263175352
5260103
3128504
1065799
1031352
17223
15544
839
184
71
56
7
0

```

# Answer
> 2 votes
# CJam, ~~17~~ ~~16~~ 18 bytes

```
q256b0{_p2b:!2bj}j

```

Try it online!

```
q256b   e# read printable ascii to integer
0       e# value for terminal case
{       e# recursive function
  _p    e#   print current number
  2b    e#   create binary representation with no leading zeros
  :!    e#   flip bits
  2b    e#   convert binary back to integer
  j     e#   recursive call
}j      e# end

```

***NOTE:*** *The old 16 byte version didn't behave correctly with empty strings:*

```
q256b{_p2b:!2b}h

```

Also, thanks to Dennis for suggesting `p` which saves 1 byte over `N\` putting newlines into the stack.

# Answer
> 2 votes
# J, 24 bytes

```
256-.&.#:^:*^:a:@#.a.&i.

```

Explanation will come later!

# Answer
> 1 votes
# Retina, 116 bytes

Byte count assumes ISO 8859-1 encoding. Line 5 contains non-printable bytes. It's `T`\x00-\xFF`.

```
-2`
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±

\d+
$*
+`(1+)\1
${1}0
01
1

{*(`1
01
+`10
011
^0+

)M`1
^0+

T`01`10

```

**Try it online**

Don't try this with input longer than two characters. (It times out using the online interpreter.) We gotta convert the binary to unary before decimal. :D

Unfortunately, there's a trailing zero and linefeed, but I decided to assume that was okay because the output is still correct.

**Explanation**

```
-2`         # Convert ASCII to decimal (ord)
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±

\d+         # Decimal to binary
$*
+`(1+)\1
${1}0
01
1

{*(`1       # Loop; Loop print and undo; Convert binary to unary
01
+`10
011
^0+

)M`1        # Unary to decimal; End print and undo
^0+         # Remove leading zeros

T`01`10     # Flip bits; (implicit loop end)

```

# Answer
> 1 votes
# C, ~~147~~ ~~135~~ ~~133~~ ~~125~~ ~~122~~ ~~121~~ ~~117~~ ~~115~~ 103 bytes

*Saved 5 bytes thanks to @Cyoce!*

*Saved 2 bytes thanks to @Cyoce and @cleblanc!*

*Saved 12 bytes thanks to @ceilingcat*

```
i,n;main(p,v)char**v;{while(*v[1])i=i*256+*v[1]++;for(;printf("%d\n",n=i),i;i^=p-1)for(p=2;n/=2;)p*=2;}

```

Ungolfed:

```
int i;
int main (c,v) {
    char**v;
    while (*v[1]) /* put first command line argument into i as binary */
        i = i*256 + *v[1]++;
    while (i != 0) {
        printf("%d\n",i);
        int p = 2,n = i;
        while (n /= 2) /* calculate smallest power of 2 > i */
            p *= 2;
        i ^= p - 1; /* flip bits */
    }
}

```

# Answer
> 1 votes
# Ruby - 70 bytes

```
λ cat inf.rb
n,=$*[0].unpack 'B*';loop{p n.to_i(2);n.tr!('10','01').sub!(/^0*/,'')}
λ ruby inf.rb Hello
310939249775
788572378000
310939249775
238816564112
36061342831
32658133904
1701604463
445879184
90991727
43226000
23882863
9671568
7105647
1282960
814191
234384
27759
5008
3183
912
111
16
15
0
inf.rb:1:in `block in <main>': undefined method `sub!' for nil:NilClass (NoMethodError)
        from inf.rb:1:in `loop'
        from inf.rb:1:in `<main>'

```

The program exits with an exception after completing, but my understanding is that that is fine as long as the error output goes to STDERR rather than STDOUT (which it does).

# Answer
> 0 votes
# C, ~~129~~ ~~120~~ ~~117~~ ~~110~~ ~~107~~ 105 Bytes

```
long long i,m,n;f(char*v){for(;*v;i<<=8,i+=*v++);for(;printf("%llu,",i),n=i;i^=m-1)for(m=2;n>>=1;m<<=1);}

```

Tested with

```
main (int c, char**v) {
    f(v[1]);
}

```

output

```
5291279215216915577,3932092821637860230,679593196789527673,473328307817319302,103132444486104185,40982743589751686,31074850448176249,4953946570787718,4053252683953273,450346943417222,112603010004089,28134478351238,7049893737593,1746199284614,452823970937,96931842950,40507110521,28212366214,6147372153,2442562438,1852404857,295078790,241792121,26643334,6911097,1477510,619641,428934,95353,35718,29817,2950,1145,902,121,6,1,0,

```

# Answer
> 0 votes
# C#, ~~360~~ 359 bytes

```
using w=System.Console;using q=System.Convert;s={System.Func<int,int,string>S=q.ToString;string t="",f="";for(int i=0;i<s.Length;i++)t+=i>0?S(s[i],2).PadLeft(8,'0'):S(s[i],2);w.WriteLine(q.ToInt64(t,2).ToString());while(t!="0"){f="";foreach(var n in t)f+=n=='0'?'1':'0';t=f.TrimStart(new char[]{'0'});t+=t==""?"0":"";w.WriteLine(q.ToInt64(t,2).ToString());}};

```

Full program:

```
using w = System.Console;
using q = System.Convert;

class a
{
    static void Main()
    {
        System.Action<string> b = s =>
        {
            System.Func<int,int,string> S = q.ToString;
            string t = "", f = ""; // Var does not work here
            for(int i = 0; i < s.Length; i++)
                t += i > 0 ? S(s[i], 2).PadLeft(8, '0') : S(s[i], 2);
            w.WriteLine(q.ToInt64(t, 2).ToString());
            while(t != "0")
            {
                f = "";
                foreach (var n in t) f += n== '0' ? '1' : '0';
                t = f.TrimStart(new char[] { '0' });
                t += t == "" ? "0" : "";
                w.WriteLine(q.ToInt64(t, 2).ToString());
            }
        };

        b("Inf");
        b("Infinity");
        w.Read(); // prevent close in VS
    }
}

```

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


title: How much candy can you eat?

text:
# Question
Title: How much candy can you eat?
*Credit to Geobits in TNB for the idea*

A post without sufficient detail recently posited an interesting game:

2 children sit in front of an array of candy. Each piece of candy is numbered 1 to `x`, with `x` being the total amount of candy present. There is exactly 1 occurrence of each number.

The goal of the game is for the children to eat candy and multiply the values of the candy they have eaten to arrive at a final score, with the higher score winning.

However the original post missed key information, such as how candy is selected, so the kids in our story decided that the older kid gets to go first, and can eat up to half the candy, however once he announces the end of his turn, he can't change his mind.

One of the kids in this game doesn't like candy, so he wants to eat as little as possible, and he once watched his dad write some code once, and figures he can use the skills gained from that to work out how much candy he needs to eat to ensure victory, whilst still eating as little as possible.

## The Challenge

Given the total number of candy `x`, your program or function should output the smallest amount of candy he has to eat to ensure victory, `n`, even if his opponent eats all the remaining candy.

Naturally bigger numbers make bigger numbers, so whatever amount you'll give him, he'll eat the `n` largest numbers.

## The Rules

* `x` will always be a *positive* integer in the range `0 < x! <= l` where `l` is the upper limit of your language's number handling capabilities
* It is guaranteed that the kid will always eat the `n` largest numbers, for example for `x = 5` and `n = 2`, he will eat `4` and `5`

## Test cases

```
x = 1
n = 1
(1 > 0)

x = 2
n = 1
(2 > 1)

x = 4
n = 2
(3 * 4 == 12 > 1 * 2 == 2)

x = 5
n = 2
(4 * 5 == 20 > 1 * 2 * 3 == 6)

x = 100
n = 42
(product([59..100]) > product([1..58]))

x = 500
n = 220
(product([281..500]) > product([1..280]))

```

## Scoring

Unfortunately, our brave contestant has nothing to write his code with, so he has to arrange the pieces of candy into the characters of the code, as a result, your code needs to be as small as possible, smallest code in bytes wins!

# Answer
> 9 votes
# Python 3, 76 bytes

```
F=lambda x:x<2or x*F(x-1)
f=lambda x,n=1:x<2or n*(F(x)>F(x-n)**2)or f(x,n+1)

```

Try it online!

Relies on the fact that for eating \\$n\\$ candies to still win and the total number of candies being \\$x\\$, \\$\frac{x!}{(x-n)!}\>(x-n)!\\$ must be true, which means \\$x!\>((x-n)!)^2\\$.

-1 from Skidsdev

~~-3~~ -6 from BMO

-3 from Sparr

+6 to fix `x = 1`

# Answer
> 5 votes
# JavaScript (ES6), 53 bytes

```
n=>(g=p=>x<n?g(p*++x):q<p&&1+g(p/n,q*=n--))(q=x=1)||n

```

Try it online!

### Working range

Interestingly, the differences between the kids' products are always big enough that the loss of precision inherent to IEEE 754 encoding is not an issue.

As a result, it works for \\$0 \le n \le 170\\$. Beyond that, both the mantissa and the exponent overflow (yielding *+Infinity*) and we'd need BigInts (+1 byte).

### How?

Let \\$p\\$ be the candy product of the other kid and let \\$q\\$ be our own candy product.

1. We start with \\$p=n!\\$ (all the candy for the other kid) and \\$q=1\\$ (nothing for us).
2. We repeat the following operations until \\$q\ge p\\$:

* divide \\$p\\$ by \\$n\\$
    * multiply \\$q\\$ by \\$n\\$
    * decrement \\$n\\$

The result is the number of required iterations. (At each iteration, we 'take the next highest candy from the other kid'.)

### Commented

This is implemented as a single recursive function which first compute \\$n!\\$ and then enters the loop described above.

```
n => (           // main function taking n
  g = p =>       // g = recursive function taking p
    x < n ?      //   if x is less than n:
      g(         //     this is the first part of the recursion:
        p * ++x  //     we're computing p = n! by multiplying p
      )          //     by x = 1 .. n
    :            //   else (second part):
      q < p &&   //     while q is less than p:
      1 + g(     //       add 1 to the final result
        p / n,   //       divide p by n
        q *= n-- //       multiply q by n; decrement n
      )          //
)(q = x = 1)     // initial call to g with p = q = x = 1
|| n             // edge cases: return n for n < 2

```

# Answer
> 4 votes
# Jelly, 9 bytes

```
ḊPÐƤ<!€TL

```

**Try it online!** Or see the test-suite.

### How?

```
ḊPÐƤ<!€TL - Link: integer, x                   e.g. 7
Ḋ         - dequeue (implicit range of x)           [   2,   3,   4,   5,   6,   7]
  ÐƤ      - for postfixes [all, allButFirst, ...]:
 P        -   product                               [5040,2520, 840, 210,  42,   7]
      €   - for each (in implicit range of x):
     !    -   factorial                             [   1,   2,   6,  24, 120, 720, 5040]
    <     - (left) less than (right)?               [   0,   0,   0,   0,   1,   1, 5040]
          -   -- note right always 1 longer than left giving trailing x! like the 5040 ^
       T  - truthy indices                          [                       5,   6, 7   ]
        L - length                                  3

```

# Answer
> 3 votes
# APL (Dyalog Unicode), 10 bytes

```
+/!≤2*⍨!∘⍳

```

Try it online!

Port of Dennis' answer. Thanks to, well, Dennis for it.

### How:

```
+/!≤2*⍨!∘⍳ ⍝ Tacit function, takes 1 argument (E.g. 5)
         ⍳ ⍝ Range 1 2 3 4 5
       !∘  ⍝ Factorials. Yields 1 2 6 24 120
    2*⍨    ⍝ Squared. Yields 1 4 36 576 14400
  !        ⍝ Factorial of the argument. Yields 120.
   ≤       ⍝ Less than or equal to. Yields 0 0 0 1 1
+/         ⍝ Sum the results, yielding 2.

```

Since this answer wasn't strictly made by me, I'll keep my original answer below.

---

# APL (Dyalog Unicode), ~~14 12~~ 11 bytes

```
(+/!>×\)⌽∘⍳

```

Try it online!

Prefix tacit function. Basically a Dyalog port of Jonathan's answer.

Thanks to ngn and H.PWiz for the help in chat. Thanks to ngn also for saving me a byte.

Thanks to Dennis for pointing out that my original code was wrong. Turns out it saved me 2 bytes.

Uses `⎕IO←0`.

### How:

```
+/(!>×\)∘⌽∘⍳ ⍝ Tacit function, taking 1 argument (E.g. 5).
           ⍳ ⍝ Range 0 1 2 3 4
         ⌽∘  ⍝ Then reverse, yielding 4 3 2 1 0
  (    )∘    ⍝ Compose with (or: "use as argument for")
   !         ⍝ Factorial (of each element in the vector), yielding 24 6 2 1 1
     ×\      ⍝ Multiply scan. Yields 4 12 24 24 0
    >        ⍝ Is greater than. Yields 1 0 0 0 1
+/           ⍝ Finally, sum the result, yielding 2.

```

# Answer
> 3 votes
# , ~~70~~ ~~41~~ 38 bytes

*-29 because Dennis knows **all** the internal functions*

*-3 switching to scan() input*

```
sum(prod(x<-scan():1)<=cumprod(1:x)^2)

```

Try it online!

Pretty simple R implementation of nedla2004's Python3 answer.

~~I feel like there's a cleaner implementation of the 1-handling, and I'd like to lose the curly-braces.~~

I'm mad I didn't go back to using a which approach, madder that I used a strict less-than, but even madder still that I didn't know there's a `cumprod()` function. Great optimisation by Dennis.

# Answer
> 2 votes
# Haskell, ~~52~~ 51 bytes

Using the straightforward approach: We check whether the product of the last \\$n\\$ numbers, which is \\$\frac{x!}{(x-n)!}\\$ is less than the product of the first \\$n\\$ numbers, namely \\$(x-n)!\\$ and takes the least \\$n\\$ for which this is true.

```
g b=product[1..b]
f x=[n|n<-[1..],g(x-n)^2<=g x]!!0

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~183~~ ~~176~~ 149 bytes

```
R=reversed
def M(I,r=1):
 for i in I:r*=i;yield r
def f(x):S=[*range(1,x+1)];return([n for n,a,b in zip([0]+S,R([*M(S)]),[0,*M(R(S))])if b>a]+[x])[0]

```

Try it online!

It's is a lot faster than some other solutions - 0(N) multiplications instead of O(N²) - but I can't manage to reduce code size.

-27 from Jo King

# Answer
> 2 votes
# Jelly, 7 bytes

```
R!²<!ċ0

```

Try it online!

### How it works

```
R!²<!ċ0  Main link. Argument: n

R        Range; yield [1, ..., n].
 !       Map factorial over the range.
  ²      Take the squares of the factorials.
    !    Compute the factorial of n.
   <     Compare the squares with the factorial of n.
     ċ0  Count the number of zeroes.

```

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

```
E!IN-!n›iNq

```

Try it online!

```
E!IN-!n›iNq

E                For loop with N from [1 ... input]
 !               Push factorial of input
  IN-            Push input - N (x - n)
     !           Factorial
      n          Square
       ›         Push input! > (input - N)^2 or x! > (x - n)^2
        i        If, run code after if top of stack is 1 (found minimum number of candies)
         N       Push N
          q      Quit, and as nothing has been printed, N is implicitly printed

```

Uses the same approach as my Python submission. Very new to 05AB1E so any tips on code or explaination greatly appreciated.

-4 bytes thanks to Kevin Cruijssen

# Answer
> 1 votes
# Clean, 57 bytes

```
import StdEnv
$x=while(\e=prod[1..x-e]^2>prod[1..x])inc 1

```

Try it online!

A straight-forward solution.

# Answer
> 0 votes
# Jelly, 14 bytes

```
ạ‘rP>ạ!¥
1ç1#«

```

Try it online!

Handles 1 correctly.

# Answer
> 0 votes
# Charcoal, 20 bytes

```
ＮθＩ⊕ΣＥθ‹Π⊕…ιθ∨Π…¹⊕ι¹

```

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

```
Ｎθ                      Input `n`
    Σ                   Sum of
      θ                 `n`
     Ｅ                  Mapped over implicit range
        Π               Product of
           ι            Current value
          …             Range to
            θ           `n`
         ⊕              Incremented
       ‹                Less than
              Π         Product of
                ¹       Literal 1
               …        Range to
                  ι     Current value
                 ⊕      Incremented
             ∨          Logical Or
                   ¹    Literal 1
   ⊕                    Incremented
  Ｉ                     Cast to string
                        Implicitly print

```

`Product` on an empty list in Charcoal returns `None` rather than `1`, so I have to logically `Or` it.

# Answer
> 0 votes
# C (gcc), 68 bytes

```
n;f(x){int i=2,j=x,b=1,g=x;while(i<j)b*i>g?g*=--j:(b*=i++);n=x-j+1;}

```

Try it online!

Edit: trading bytes against mults, no doing 2\*x mults instead of x+n

Edit: moving back to int instead of long through macro. Would fail at 34 with long.

Well I have this in C. Fails at 21.

There is a possible ambiguity as to whether the good kid wants to always win or never lose... what do you think?

# Answer
> 0 votes
# PHP, 107 bytes

```
<?php $x=fgets(STDIN);function f($i){return $i==0?:$i*f($i-1);}$n=1;while(f($x)<f($x-$n)**2){$n++;}echo $n;

```

Try it online!

Uses the same \\$x^2\>((x-1)!)^2\\$ method as others have used.

Uses the factorial function from the PHP submission for this challenge (thanks to @donutdan4114)

# Answer
> 0 votes
# Wolfram Language (Mathematica), 43 bytes

```
Min[n/.Solve[#!>(#-n)!^2, Integers]]/.n->1&

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
L!ns!@O

```

Port of *Dennis♦*' Jelly answer, so make sure to upvote him if you like this answer!

Try it online or verify all test cases.

**Explanation:**

```
L          # List in the range [1, (implicit) input]
 !         # Take the factorial of each
  n        # Then square each
   s!      # Take the factorial of the input
     @     # Check for each value in the list if they are larger than or equal to the
           # input-faculty (1 if truthy; 0 if falsey)
      O    # Sum, so determine the amount of truthy checks (and output implicitly)

```

# Answer
> 0 votes
# Japt `-x`, 7 bytes

Port of Dennis' Jelly solution.

Only works in practice up to `n=4` as we get into scientific notation above that.

```
õÊ®²¨U²

```

Try it

```
õ           :Range [1,input]
 Ê          :Factorial of each
  ®         :Map
   ²        :  Square
    ¨       :  Greater than or equal to
     U²     :  Input squared
            :Implicitly reduce by addition

```

# Answer
> 0 votes
# C# (.NET Core), 93 bytes

```
n=>{int d(int k)=>k<2?1:k*d(k-1);int a=1,b=d(n),c=n;for(;;){a*=n;b/=n--;if(a>=b)return c-n;}}

```

Try it online!

Based off of @Arnauld's javascript answer.

# Answer
> 0 votes
# Python 3, 75 bytes

```
f=lambda n:n<1or f(n-1)*n
n=lambda x:x-sum(f(n)**2<f(x)for n in range(1,x))

```

Try it online!

# 74 bytes version

```
f=lambda n:n<1or f(n-1)*n
n=lambda x:1+sum(f(n)>f(x)**.5for n in range(x))

```

but this version overflowed for 500...

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


# Question
Title: Given a fair coin as input, generate any particular unfair outcome
It is easy to generate a fair coin using a unfair coin, but the reverse is harder to accomplish.

Your program will receive one number *X* (between 0 and 1, inclusive) as input. The input must not simply be hard-coded as a number in the middle of the source code. It must then return a single digit: a `1` with a probability of *X* and a `0` otherwise.

Your program is only allowed to use one form of random number generator in the source code: `int(rand(2))` (or an equivalent), which returns either a zero or a one with equal probability. You can include or access this function as many times as you wish in your code. You also have to provide the function yourself as part of the code.

Your program is not allowed to use any other random number generating functions or external sources (such as time and date functions) that could function as a random number generating function. It also cannot access any external files or pass the job along to external programs.

This is code golf, the shortest answer wins.

# Answer
# Perl, 37 42 char

```
($d/=2)+=rand>.5for%!;print$d/2<pop|0

```

Takes arbitrary probability as a command line argument. Builds a uniform random number in `$d` and compares it to the input.

Earlier, 52 char solution

```
$p=<>;do{$p*=2;$p-=($-=$p)}while$--(.5<rand);print$-

```
> 4 votes

# Answer
## Python, 81 chars

```
import random
print(sum(random.randint(0,1)*2**-i for i in range(9))<input()*2)+0

```

Can be off by a bit, but never more than 1%.
> 3 votes

# Answer
# Mathematica 165

Not streamlined, but some may find the algorithm of interest:

```
d = RealDigits; r = RandomInteger;
f@n_ := If[(c = Cases[Transpose@{a = Join[ConstantArray[0, Abs[d[n, 2][[2]]]], d[n, 2][[1]]],
         RandomInteger[1, {Length@a}]}, {x_, x_}]) == {}, r, c[[1, 1]]]

```

**Usage**

```
f[.53]

```

> 1

**Check**

Let's see if `f[.53]` really produces the value `1` around 53% of the time. Each test calculates the % for samples of 10^4.

50 such tests are run and averaged.

```
Table[Count[Table[f[.53], {10^4}], 1]/10^4 // N, {50}]
Mean[%]

```

> {0.5292, 0.5256, 0.5307, 0.5266, 0.5245, 0.5212, 0.5316, 0.5345, 0.5297, 0.5334, 0.5306, 0.5288, 0.528, 0.5379, 0.5293, 0.5263, 0.539, 0.5322, 0.5195, 0.5208, 0.5382, 0.543, 0.5336, 0.5305, 0.5303, 0.5297, 0.5318, 0.5243, 0.5281, 0.5361, 0.5349, 0.5308, 0.5265, 0.5309, 0.5233, 0.5345, 0.5316, 0.5376, 0.5264, 0.5269, 0.5295, 0.523, 0.5294, 0.5326, 0.5316, 0.5334, 0.5165, 0.5296, 0.5266, 0.5293}
>
> 0.529798

**Histogram of results**

**Explanation** (spoiler alert!)

The base 2 representation of .53 is

> .10000111101011100001010001111010111000010100011110110

Proceeding from left to right, one digit at a time:

If RandomInteger\[\] returns 1, then answer = 1,

Else If second RandomInteger\[\] returns 0, then answer = 0,

Else If third RandomInteger\[\] returns 0, the answer = 0,

Else....

If, when all digits have been tested, there is still no answer, then answer = RandomInteger\[\].
> 3 votes

# Answer
# Haskell, 107 chars:

```
import System.Random
g p|p>1=print 1|p<0=print 0|1>0=randomIO>>=g.(p*2-).f
f x|x=1|1>0=0.0
main=readLn>>=g

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 42 bytes

```
RandomInteger[]/.⌈1-2#⌉:>#0@Mod[2#,1]&

```

Try it online!

This is a recursive approach. Ungolfed, the algorithm is:

* If the input probability `p` is less than 1/2, then when the coinflip comes up 0, return 0. Otherwise, recurse on `2p`; assuming correctness, the overall probability of getting 1 is half of `2p` or `p`.
* If the input probability `p` is greater than 1/2, then when the coinflip comes up 1, return 1. Otherwise, recurse on `2p-1`; assuming correctness, the overall probability of getting 0 is half of `1-(2p-1)` or `1-p`.

To make it shorter, we start with the random coinflip, which, in either branch, gets returned half the time. If the coinflip does not match the case when we're supposed to return it, replace it by the result of recursing on `2p` modulo 1. (That is, when `p` is less than 1/2, replace 1; when `p` is greater than 1/2, replace 0. This is equivalent to replacing `⌈1-2p⌉`.)
> 0 votes

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


# Question
Title: Approximate the proportion of integers with neighboring factors
If 1 is not counted as a factor, then

* 40 has two neighboring factors (4 and 5)
* 1092 has two neighboring factors (13 and 14)
* 350 does not have two neighboring factors (out of its factors 2, 5, 7, 10, 14, 25, 35, 50, 70, and 175, no two are consecutive)

The proportion of positive integers that have this property is the proportion divisible by any of 6 (2 × 3), 12 (3 × 4), 20 (4 × 5), 30, 56, …. If we only calculate the proportion divisible by the first *n* of these, we get an approximation that gets more accurate as *n* increases.

For example, for *n=1*, we find the proportion of integers divisible by 2 × 3 = 6, which is 1/6. For *n=2*, all integers divisible by 3 × 4 = 12 are also divisible by 6, so the approximation is still 1/6. For *n=3*, the proportion of integers divisible by 6 or 20 is 1/5, and so on.

Here are the first few values:

```
1  1/6                0.16666666666666666
3  1/5                0.20000000000000000
6  22/105             0.20952380952380953
9  491/2310           0.21255411255411255
12 2153/10010         0.21508491508491510
15 36887/170170       0.21676558735382265
21 65563/301070       0.21776663234463747
24 853883/3913910     0.21816623274423785
27 24796879/113503390 0.21846817967287144

```

For values of *n* between the provided values, the output should be the same as the output for the value above (e.g. *n=5* → 1/5).

Your program should take *n* and output either a fraction or decimal answer. You may take *n* at any offset (e.g. 0-indexing or 2-indexing into this sequence, instead of 1-indexing).

For decimal output, your program must be accurate to at least 5 digits for all the test cases given.

Scoring is , with the shortest code winning.

Inspired by What proportion of positive integers have two factors that differ by 1? by marty cohen -- specifically, by Dan's answer.

# Answer
# Jelly,  ~~14 13~~  10 bytes

-1 using Erik the Outgolfer's idea to take the mean of a list of zeros and ones.
-3 by using 3-indexing (as allowed in the question) - thanks to Dennis for pointing this out.

```
ḊPƝḍⱮ!Ẹ€Æm

```

A monadic Link accepting an integer, `n+2`, which yields a float.

**Try it online!** (very inefficient since it tests divisibility over the range \\$\[2, (n+2)!\]\\$)

(Started out as `+2µḊPƝḍⱮ!§T,$Ẉ`, taking `n` and yielding `[numerator, denominator]`, unreduced)

### How?

```
ḊPƝḍⱮ!Ẹ€Æm - Link: integer, x=n+2
Ḋ          - dequeue (implicit range of) x  - i.e. [2,3,4,...,n+2]
  Ɲ        - apply to neighbours:
 P         -   product                             [2×3,3×4,...,(n+1)×(n+2)]
     !     - factorial of x                        x!
    Ɱ      - map across (implicit range of) x! with:
   ḍ       -   divides?                            [[2×3ḍ1,3×4ḍ1,...,(n+1)×(n+2)ḍ1],[2×3ḍ2,3×4ḍ2,...,(n+1)×(n+2)ḍ2],...,[2×3ḍ(x!),3×4ḍ(x!),...,(n+1)×(n+2)ḍ(x!)]]
       €   - for each:
      Ẹ    -   any?  (1 if divisible by any of the neighbour products else 0)
        Æm - mean

```
> 6 votes

# Answer
# Jelly, 12 bytes

```
Ḋ×‘$ḍẸ¥ⱮP$Æm

```

Try it online!

-2 thanks to Jonathan Allan's suggestion to replace the LCM with the product (i.e. the LCM multiplied by an integer).

Dennis noticed I can 2-index as well.
> 3 votes

# Answer
# 05AB1E, 15 bytes

```
Ì©!Lε®LüP¦Öà}ÅA

```

Port of *@JonathanAllan*'s Jelly answer, so also extremely slow.

Try it online or verify the first three test cases.

**Explanation:**

```
Ì                 # Add 2 to the (implicit) input
                  #  i.e. 3 → 5
 ©                # Store this in the register (without popping)
  !               # Take the factorial of it
                  #  i.e. 5 → 120
   L              # Create a list in the range [1, (input+2)!]
                  #   i.e. 120 → [1,2,3,...,118,119,120]
    ε       }     #  Map over each value in this list
     ®            #  Push the input+2 from the register
      L           #  Create a list in the range [1, input+2]
                  #   i.e. 5 → [1,2,3,4,5]
       ü          #  Take each pair
                  #    i.e. [1,2,3,4,5] → [[1,2],[2,3],[3,4],[4,5]]
        P         #   And take the product of that pair
                  #    i.e. [[1,2],[2,3],[3,4],[4,5]] → [2,6,12,20]
         ¦        #  Then remove the first value from this product-pair list
                  #   i.e. [2,6,12,20] → [6,12,20]
          Ö       #  Check for each product-pair if it divides the current map-value
                  #  (1 if truthy; 0 if falsey)
                  #   i.e. [1,2,3,...,118,119,120] and [6,12,20]
                  #    → [[0,0,0],[0,0,0],[0,0,0],...,[0,0,0],[0,0,0],[1,1,1]]
           à      #  And check if it's truthy for any by taking the maximum
                  #   i.e. [[0,0,0],[0,0,0],[0,0,0],...,[0,0,0],[0,0,0],[1,1,1]]
                  #    → [0,0,0,...,0,0,1]
             ÅA   # After the map, take the mean (and output implicitly)
                  #  i.e. [0,0,0,...,0,0,1] → 0.2

```
> 3 votes

# Answer
# JavaScript (ES6),  ~~94 92~~  90 bytes

*Saved 2 bytes thanks to @Shaggy + 2 more bytes from there*

Returns a decimal approximation.

```
n=>(x=2,g=a=>n--?g([...a,x*++x]):[...Array(1e6)].map((_,k)=>n+=a.some(d=>k%d<1))&&n/1e6)``

```

Try it online!

---

# JavaScript (ES6), 131 bytes

A much longer solution that returns an exact result as a pair \\$\[numerator, denominator\]\\$.

```
f=(n,a=[],p=x=1)=>n?f(n-1,[...a,q=++x*-~x],p*q/(g=(a,b)=>a?g(b%a,a):b)(p,q)):[...Array(p)].map((_,k)=>n+=a.some(d=>-~k%d<1))&&[n,p]

```

Try it online!
> 2 votes

# Answer
# Charcoal, 26 bytes

```
ＦＮ⊞υ×⁺²ι⁺³ιＩ∕ＬΦΠυ¬⌊Ｅυ﹪ιλΠυ

```

Try it online! Link is to verbose version of code. Hopelessly inefficient (O(n!²)) so only works up to `n=4` on TIO. Explanation:

```
ＦＮ⊞υ×⁺²ι⁺³ι

```

Input `n` and calculate the first `n` products of neighbouring factors.

```
Ｉ∕ＬΦΠυ¬⌊Ｅυ﹪ιλΠυ

```

Take the product of all of those factors and use that to calculate the proportion of numbers having at least one of those factors.

30-byte less slow version is only O(n!) so can do up to `n=6` on TIO:

```
Ｆ⊕Ｎ⊞υ⁺²ιＩ∕ＬΦΠυΣＥυ∧μ¬﹪ι×λ§υ⊖μΠυ

```

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

~~46-byte faster version is only O(lcm(1..n+2)) so can do up to `n=10` on TIO:~~

~~```
ＦＮ⊞υ×⁺²ι⁺³ι≔⁰η≔⁰ζＷ∨¬η⌈Ｅυ﹪ηκ«≦⊕η≧⁺⌈Ｅυ¬﹪ηκζ»Ｉ∕ζη

```~~

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

45-byte faster version is only O(2ⁿ) so can do up to `n=13` on TIO:

```
⊞υ±¹ＦＥＮ×⁺²ι⁺³ιＦ⮌υ⊞υ±÷×ικ⌈Φ⊕ι∧λ¬∨﹪ιλ﹪κλＩΣ∕¹✂υ¹

```

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

54-byte fastest version uses more efficient LCM so can do up to `n=18` on TIO:

```
⊞υ±¹ＦＥＮ×⁺²ι⁺³ιＦＥυ⟦κι⟧«Ｗ⊟κ⊞⊞Ｏκλ﹪§κ±²λ⊞υ±÷Π…κ²⊟κ»ＩΣ∕¹✂υ¹

```

Try it online! Link is to verbose version of code.
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~69~~ ~~68~~ ~~61~~ 52 bytes

```
Count[Range[#!],b_/;Or@@(# #-#&@Range[3,#]∣b)]/#!&

```

Try it online!

3-indexed. At first I was going to use `LCM@@` but realized that `#!` would be shorter... but now it a lot of memory for `Range[#!]`...

Managed to golf down the condition by 2 bytes, which was nice.

---

Older numerical solution (56 bytes):

```
N@Count[Range[5^8],b_/;Or@@Array[(# #-#)∣b&,#,3]]/5^8&

```

Try it online!

2-indexed. More efficient when `#!>5^8` (`#>9`, assuming `#` is an integer).
> 1 votes

# Answer
# Python 2, 78 bytes

```
lambda n:sum(any(-~i%(j*-~j)<1for j in range(2,n+2))for i in range(10**7))/1e7

```

Try it online!

Returns the approximate decimal to +5 digits; uses the naive brute force approach xnor suggests in comments on the question.
> 1 votes

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


# Question
Title: reach catch when everything in the try block is caught already
This is limited to Java and C# by the syntax I guess.

In this programming puzzle, you are to produce `Exception`s that can be caught but are thrown again at the end of the catch block.

```
try
{
    while(true)
        try
        {
            // you are only allowed to modify code between this try { } brackets
        }
        catch(Exception ex2) {  }
}
catch(Exception ex1)
{
    // your goal is to reach this catch block by modifying the code ...
    // in the inner try block above
    // You win if you reach this part and execute on of the following code lines
    Console.WriteLine("You won!"); // for C#
    // Or
    System.out.println("You won!"); // for Java
}

```

You can freely put code before and after this snippet.

The shortest code to reach the outer `catch` block wins.

# Answer
> 24 votes
# C#, 46 (88 including boilerplate)

```
using System;class P{static void Main(){
        try
        {
            while(true)
                try
                {
                    System.Threading.Thread.CurrentThread.Abort();
                }
                catch(Exception ex2) {  }
        }
        catch(Exception ex1)
        {
            // your goal is to reach this catch block by modifying the code ...
            // in the inner try block above
            // You win if you reach this part and execute on of the following code lines
            Console.WriteLine("You won!"); // for C#
        }
}}

```

The `Abort()` method raises a ThreadAbortException, which is a special exception that is automatically rethrown at the end of each catch block (unless `Thread.ResetAbort()` is called).

# Answer
> 20 votes
**C#** 24 Characters

terminates the inner try block before intended, allowing me to cause an exception outside of the try block.

```
}finally{int a=1/0;}try{

```

# Answer
> 13 votes
## Java, 76 or 31

Counting only the insertions made to the code, ignoring new lines. 76 if you count *everything* I've added, 31 if you exclude the first line and the last line, i.e. only counting `int a=1/0;try{}catch(Error e){}`.

```
class P{public static void main(String[]A){
try
{
    while(true)
        try
        {
            int a=1/0;try{
        }
        catch(Exception ex2) {  }
}
catch(Exception ex1)
{
    // your goal is to reach this catch block by modifying the code ...
    // in the inner try block above
    // You win if you reach this part and execute on of the following code lines
    //Console.WriteLine("You won!"); // for C#
    // Or
    System.out.println("You won!"); // for Java
}
}catch(Error e){}
}}

```

# Answer
> 4 votes
> **Warning**: These programs are clone bombs (a sort of less-dangerous but still-dangerous form of a fork bomb); as such, **do not run them on a production system without sandboxing or resource limits**. Clone bombs create threads in a loop (as opposed to fork bombs, which create processes in a loop), thus you can stop them simply by killing the process in question (making them much less dangerous than fork bombs, which can be very hard to clear up); but they will likely tie up most of your CPU until you manage to do so (or until the program wins and exits naturally by itself). Asking your OS to place limits on the amount of memory and CPU time these programs are allowed to use should create a safe environment in which to test them.

# Java (OpenJDK 8), ~~65~~ 60 bytes (with a slight modification to the wrapper)

```
Thread x=Thread.currentThread();new Thread(x::stop).start();

```

Try it online!

Requires both instances of `catch (Exception …)` in the question to be changed to `catch (Throwable …)`. This should in theory be *more* secure, not less, but it enables this solution to be possible.

I saved 5 bytes over the first version of this answer via using a method reference rather than a lambda.

# Java 4, 104 bytes (untested, should work with the original wrapper)

```
final Thread x=Thread.currentThread();new Thread(){public void run(){x.stop(new Exception());}}.start();

```

Try it online! (link goes to a Java 8 implementation, thus won't work)

Using features that have been removed from modern versions of Java, it's possible to solve even the version of the puzzle which requires an `Exception`. Probably, at least. (Java 4 is very old by now and I can't remember which features it did and didn't contain. As can be seen, there were many fewer features in Java back then and it was therefore more verbose; we didn't have lambdas, so I had to create an inner class.)

## Explanations

Most of the solutions to this question are in C# (together with a Java solution that cheats via using unbalanced brackets as a form of code injection, and a Perl solution which also isn't in Java). So I thought it would be worth trying to show how this puzzle can be solved "properly" in Java too.

Both programs are effectively identical (thus the fact that the first program works gives me high confidence that the second program would work too, unless I've accidentally used a non-Java-4 feature; `Thread#stop` was deprecated in Java 5).

Java's `Thread#stop` method works, behind the scenes, via causing a throwable to be thrown into the thread in question. The throwable intended for the purpose is `ThreadDeath` (an `Error`, specifically because people often try to blanket-catch exceptions and Java's designers didn't want that happening), although it allows you to throw anything (or used to; at some point after the API was designed, Java's designers realised that this was an incredibly bad idea and removed the version of the method that takes arguments outright). Of course, even the version which throws `ThreadDeath` is a fairly risky operation about which you can make few guarantees (for example, it allows you to solve this puzzle, something which "shouldn't" be possible), so you're not supposed to use it, but as of Java 8, it still works.

This program works by spawning a new thread, and asking it to forcibly throw an exception back into the main thread. If we're lucky, it'll do that at a point in time when we're outside the inner `catch` block (we can't escape the outer `catch` block until the program ends, because there's a loop around it). Because we have the loop conveniently added already, it's byte-saving to simply use that loop to allow us to keep creating threads, in the hope that one of them will eventually hit the correct timing. This normally seems to happen within a couple of seconds.

(TIO note: the current version of TIO is quite inclined to kill this program early in its execution, presumably due to all the threads being created. It can work on TIO, but does not work reliably, so often a few attempts are required to get the "You won!" output.)

# Answer
> 1 votes
# C#

```
    try
    {
        int i = 0, j = 1, k;

        int flag = 0;
        lbl:
        if (flag == 1)
        {
            k = j / i;
        }

        while (true)
            try
            {
                k = j / i;

            }
            catch (Exception e)
            {
                flag = 1;
                goto lbl;
                //Console.WriteLine("loose");

            }
    }
    catch (Exception e)
    {
        Console.WriteLine("Won");

    }

```

# Answer
> 1 votes
# Perl 5, 37 or 36 bytes

```
eval {
    while (1) {
        eval {

```

```
use overload'""',sub{die};die bless[]

```

```
        };
        $@ eq "" or 0;
    }
};
$@ eq "" or print "You won!\n";

```

Try it online!

Turns out that this question translates into Perl well enough to make an interesting puzzle there, too. Perl's `try` equivalent is called (a little confusingly) `eval`, and specifies an exception by setting `@_` to an exception if it occurred, and the null string otherwise. As such, a `catch` block is implemented via comparing `@_` to the null string.

This solution works by creating an object (whose class is the program as a whole; you can use arbitrary Perl files like classes, sort of like the reverse of Java (where you can use arbitrary classes like files)). That's the `bless[]` part (`bless` normally only appears deep inside constructors, as the primitive that makes things into objects in the first place, but you can use it directly if you really want to; `[]` is the memory allocator for the object – a list constructor, in this case – and the class isn't given so it's assumed to be the currently executing one). Meanwhile, we give our "class" (i.e. the main file) a custom compare-to-string method via `use overload`, and make that method throw an exception (thus breaking out of the loop and solving the puzzle); we can actually put the `use overload` anywhere, and although it would traditionally go in with the other method definitions and nearish the top of the file, we can put it into the gap we've been given instead and it still works. (If we put it at the end of the file, we could omit the semicolon after it, leading to a 36-byte solution, but this is arguably cheating as it depends on the program having a trailing semicolon in the first place, which is not guaranteed.) It's actually shorter to overload the stringify operation and let Perl autogenerate a string compare from that, than it would be to overload string compare directly (because overloading some operators forces you to overload other operators too).

Now, all we have to do is throw our object using `die`. The `eval` terminates, then when we attempt to compare `$@` to the null string (to see if there was an exception), the comparison throws another exception and we escape the outside `eval`.

---
Tags: code-golf, c#, java, programming-puzzle
---


title: Doubled-letter steganography

text:
# Question
Title: Doubled-letter steganography
Steganography hides a given message inside a given carrier, producing a package that does not look suspicious. For this challenge, you will write a program that takes an ASCII message and an ASCII carrier as input, and return or print a package that is identical to the carrier except characters corresponding to the message are doubled, in the same order that they appear in the message.

Rules:

1. If the carrier already contains sequences of the same character more than once, and they are not used to encode a character of the message, the program will reduce them to a single character.
2. If the carrier does not contain the message characters in the right order, the program may return nothing, the carrier itself, or an error.
3. You may assume that the message and carrier are non-empty ASCII strings.
4. Capitalization matters: A is not equivalent to a.
5. When more than one package is valid, your program may output any or all of them.
6. Space is a character like any other character.

Test cases:

```
Message      Carrier              Package
"hi"         "has it arrived?"    "hhas iit arived?" OR "hhas it ariived?"
"sir"        "has it arrived?"    "hass iit arrived?"
"foo"        "has it arrived?"    "" OR "has it arrived?" OR an error.
"Car"        "Cats are cool."     "CCaats arre col."
"car"        "Cats are cool."     "" OR "Cats are cool." OR an error.
"Couch"      "Couch"              "CCoouucchh"
"oo"         "oooooooooo"         "oooo"
"o o"        "oooo oooa"          "oo  ooa"

```

This is code golf, so fewest bytes wins.

# Answer
> 5 votes
# Jelly, 28 bytes

```
ẹⱮŒp<ƝẠ$ƇṪ
nƝ+çṬ¥a⁸ḟ0Ḥç¦ð¹ç?

```

A full program taking `carrier` and `message` as command line arguments which prints the result
(For a non-packable `message` prints the unchanged `carrier`).

**Try it online!** Or see the test-suite.

### How?

```
ẹⱮŒp<ƝẠ$ƇṪ - Link 1, helper function to find the indices to double: carrier, message
           -                               e.g. "programming", "rom"
 Ɱ         - map across message with:
ẹ          -   indices of                       [[2,5], [3], [7,8]]
  Œp       - Cartesian product                  [[2,3,7],[2,3,8],[5,3,7],[5,3,8]]
        Ƈ  - filter keep if:
       $   -   last two links as a monad:
     Ɲ     -     for neighbours:
    <      -       less than?                    [1,1]   [1,1]   [0,1]   [0,1]
      Ạ    -     all truthy?                     1       1       0       0
           -                                    [[2,3,7],[2,3,8]]
         Ṫ - tail (if empty yields 0)                    [2,3,8]

nƝ+çṬ¥a⁸ḟ0Ḥç¦ð¹ç? - Main Link: carrier, message
                ? - if...
               ç  - ...condition: last Link (the helper function) as a dyad
             ð    - ...then: perform the dyadic chain to the left (described below)
              ¹   - ...else: do nothing (yields carrier)
                  - (the then clause:)
 Ɲ                - for neighbours in the carrier
n                 - not equal?
     ¥            - last two links as a dyad:
   ç              -   call last Link (the helper function) as a dyad
    Ṭ             -   untruth (e.g. [2,5] -> [0,1,0,0,1])
  +               - add (vectorises)
      a⁸          - logical AND with carrier
        ḟ0        - filter out zeros
            ¦     - sparse application...
           ç      - ...to indices: call last Link (the helper function) as a dyad
          Ḥ       - ...do: double (e.g. 'x' -> 'xx')

```

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

Takes input as `(message)(carrier)`.

```
s=>g=([c,...C],p)=>c?(c==s[0]?(s=s.slice(1),c)+c:p==c?'':c)+g(C,c):s&&X

```

Try it online!

---

# Alternate version, 66 bytes

If we can take the message as an array of characters:

```
s=>g=([c,...C],p)=>c?(c==s[0]?s.shift()+c:p==c?'':c)+g(C,c):s+s&&X

```

Try it online!

---

***Edit**: Thanks to @tsh for noticing that I forgot to remove some code when switching from non-recursive to recursive versions.*

# Answer
> 2 votes
## Haskell, ~~124~~ ~~121~~ ~~107~~ ~~101~~ ~~97~~ ~~95~~ 90 bytes

```
(#).(++"ü")
"ü"#[]=[]
p@(m:n)#e@(c:d)|m/=c=c:p#snd(span(==c)d)|m==n!!0=m:m:n#d|1<2=m:n#e

```

Raises the "Non-exhaustive patterns" exception if the carrier does not contain the message.

Try it online!

Edit: -5 bytes thanks to @Laikoni.

# Answer
> 1 votes
# Retina 0.8.2, 67 bytes

```
+`(.)(\1*)\1*(.*¶)(?(\1)(\1(\2)))(.*)$(?!¶)
$1$4$5¶$3$6
M!s`.*¶$
¶

```

Try it online! Takes the carrier on the first line and the message on the second line. Explanation:

```
+`(.)(\1*)\1*(.*¶)(?(\1)(\1(\2)))(.*)$(?!¶)
$1$4$5¶$3$6

```

Process runs of 1 or more identical characters of the carrier. If there is also a run of 1 or more of the same characters in the message, then append the shorter of the two runs to the output in duplicate, otherwise append a single character of the carrier to the output. Each run of output characters is terminated with a newline to distinguish it from the input. The `(?!¶)` at the end prevents the regex from thinking the carrier is the message once the message is exhausted, as normally `$` is allowed to match where `¶$` would match.

```
M!s`.*¶$

```

Delete everything if the message wasn't completely encoded.

Remove the newlines from the output.

# Answer
> 0 votes
# Clean, 118 bytes

```
import StdEnv,StdLib
$[][]=[]
$[u:v]b#(_,w)=span((==)u)v
|b%(0,0)==[u]=[u,u: $if(v%(0,0)<>b%(1,1))w v(tl b)]=[u: $w b]

```

Try it online!

Takes the carrier first, then the message.

Errors with `Run time error, rule '$;2' in module 'main' does not match` if message won't fit.

# Answer
> 0 votes
# Ruby, 73 bytes

```
f=->m,c,b=p{x,*c=c;x ?(x==m[0]?x+m.shift: x==b ?'':x)+f[m,c,x]:m[0]?x:''}

```

Try it online!

Recursive function, takes inputs as array of characters.

For once I was hoping to make use of Ruby's built-in `squeeze` method that contracts consecutive runs of the same character to a single instance. But unfortunately, nope - the last two test cases screwed everything so badly, that I had to resort to a completely different approach, and this turned out to be basically a port of Arnauld's answer.

# Answer
> 0 votes
# Powershell, 134 bytes

```
param($m,$c)$c-csplit"([$m])"|%{$i+=$o=$_-ceq$m[+$i]
if($o-or$_-cne"`0$h"[-1]){$h+=($_-replace'(.)(?=\1)')*($o+1)}}
$h*!($i-$m.Length)

```

The script returns the `empty string` if the carrier does not contain the message characters in the right order.

Less golfed test script:

```
$f = {

param($message,$carrier)
$carrier-csplit"([$message])"|%{                # split by chars of the message, chars itself included ([])
    $offset=$_-ceq$message[+$i]                 # 0 or 1 if current substring is a current message char (case-sensitive equality)
    $i+=$offset                                 # move to next message char if need it
    if($offset-or$_-cne"`0$h"[-1]){             # condition to remove redundant doubles after message char: arrrived -> arrived, ooo -> oo, etc
                                                # `0 to avoid exception error if $h is empty
        $h+=($_-replace'(.)(?=\1)')*($offset+1) # accumulate a double message char or a single substring without inner doubles: arried -> arived, anna -> ana, etc
    }
}
$h*!($i-$message.Length)                        # repeat 0 or 1 times to return '' if the carrier does not contain the message characters in the right order

}

@(
    ,('hi'         ,'has it arrived?'    ,'hhas iit arived?', 'hhas it ariived?')
    ,('hi?'        ,'has it arrived?'    ,'hhas iit arived??', 'hhas it ariived??')
    ,('sir'        ,'has it arrived?'    ,'hass iit arrived?')
    ,('foo'        ,'has it arrived?'    ,'')
    ,('Car'        ,'Cats are cool.'     ,'CCaats arre col.')
    ,('car'        ,'Cats are cool.'     ,'')
    ,('Couch'      ,'Couch'              ,'CCoouucchh')
    ,('oo'         ,'oooooooooo'         ,'oooo')
    ,('o o'        ,'oooo oooa'          ,'oo  ooa')
    ,('er'         ,'error'              ,'eerorr', 'eerror')
    ,('a+b'        ,'anna+bob'           ,'aana++bbob')
) | % {
    $message,$carrier,$expected = $_
    $result = &$f $message $carrier
    "$($result-in$expected): $result"
}

```

Output:

```
True: hhas iit arived?
True: hhas iit arived??
True: hass iit arrived?
True:
True: CCaats arre col.
True:
True: CCoouucchh
True: oooo
True: oo  ooa
True: eerror
True: aana++bbob

```

# Answer
> 0 votes
# C (gcc), 69+12 = 81 bytes

```
g(char*m,char*_){for(;*_;++_)*m-*_?_[-1]-*_&&p*_):p p*m++));*m&&0/0;}

```

Compile with (12 bytes)

```
-Dp=putchar(

```

Try it online!

```
g(char*m,char*_){
    for(;*_;++_)        //step through _
        *m-*_?          //check if character should be encoded
            _[-1]-*_&&  //no? skip duplicates
                p*_)    //    print non-duplicates
        :p p*m++));     //print encoded character twice
    *m&&0/0;            //if m is not fully encoded, exit via Floating point exception
}

```

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


# Question
Title: Shortest Uniquely Identifying Substrings
Given a list of strings, replace each string by one of its non-empty substrings which is not a substring of any of the other strings in the list and as short as possible.

### Example

Given the list `["hello","hallo","hola"]`, `"hello"` should be replaced by just `"e"` as this substring is not contained in `"hallo"` and `"hola"` and it is as short as possible. `"hallo"` could be replaced by either `"ha"` or `"al"` and `"hola"` by any of `"ho"`, `"ol"` or `"la"`.

### Rules

* You can assume that the strings will be non-empty and only contain alphabetical characters of the same case.
* You can assume that such a substring exists for each string in the list, i.e. no string in the list will be a substring of any of the other strings.
* Input and output can be in any reasonable format.
* This is , so try to use as few bytes as possible in the language of your choice.

### Test Cases

Only one possible output is given for most cases.

```
["ppcg"] -> ["p"] (or ["c"] or ["g"])
["hello","hallo","hola"] -> ["e","ha","ho"]
["abc","bca","bac"] -> ["ab","ca","ba"]
["abc","abd","dbc"] -> ["abc","bd","db"]
["lorem","ipsum","dolor","sit","amet"] -> ["re","p","d","si","a"]
["abc","acb","bac","bca","cab","cba"] -> ["abc","acb","bac","bca","cab","cba"]

```

---

Related: Shortest Identifying Substring \- similar idea, but more involved rules and cumbersome format.

# Answer
# Jelly,  ~~12~~  9 bytes

```
Ẇ€ŒpẇþÞ⁸Ḣ

```

**Try it online!** Or see the test-suite (takes ~35s)
> 5 votes

# Answer
# , ~~30 29~~ 25 bytes

```
1(|:(0{-.&,)"_1]\.)<\\.&>

```

Try it online!

```
                   <\\.&>        a 3-dimensional array of substrings
1 |:                             transpose each matrix to sort the substrings by length
1              ]\.               all choices where one word is missing
    (0{-.&,)"_1                  for every matrix, flatten, remove substrings
                                  that are present in the corresponding complement,
                                  pick first

```
> 4 votes

# Answer
# Prolog (SWI), ~~175~~ 163 bytes

```
S/L/R:-sub_string(S,_,L,_,R).
[H|T]+[I|R]:-string_length(H,L),between(1,L,X),H/X/I,T+R.
R+R.
L-R:-L+R,forall(member(E,L),findall(_,(member(F,R),\+ \+ E/_/F),[_])).

```

Try it online!

Most of the things here should be fairly obvious, but:

### Explanation

Signatures: (`+` = input, `?` = optional, `-` = output, `:` = expression)

* `sub_string(+String, ?Before, ?Length, ?After, ?SubString)`
* `string_length(+String, -Length)`
* `member(?Elem, ?List)`
* `between(+Low, +High, ?Value)`
* `findall(+Template, :Goal, -Bag)`
* `forall(:Cond, :Action)`

`\+ \+` is just `not not` (i.e. converts a match to boolean (in this case, prevents it from matching both `p`s in `ppcg` separately))
> 4 votes

# Answer
# APL (Dyalog), 25 bytes

Thanks ngn for saving one byte

```
⊃¨1↓≢~⍨/(,⍨(,∘↑⍳∘≢,/¨⊂)¨)

```

Try it online!
> 4 votes

# Answer
# Pyth, 12 bytes

```
mhf!ts}LTQ.:

```

Try it here!

### How it works

Basicaly filters the substrings of each that only occur in one of the strings in the list (that is, it is unique to that string) and gets the first one.

```
mhf!ts}LTQ.:     Full program, Q=eval(stdin_input())
m         .:     Map over Q and obtain all the substrings of each.
  f              And filter-keep those that satisfy (var: T)...
      }LTQ       ... For each string in Q, yield 1 if it contains T, else 0.
   !ts           ... Sum the list, decrement and negate.
 h               Head. Yields the first valid substring, which is always the shortest.

```
> 4 votes

# Answer
# Jelly, 10 bytes

```
Ẇ€ṙƬ1ḟ/Ḣ$€

```

Try it online!
> 3 votes

# Answer
# Python 2, 116 bytes

```
def f(a):g=lambda s,S:s not in`set(a)-{S}`[3:]and min(s,g(s[1:],S),g(s[:-1],S),key=len)or S;return[g(s,s)for s in a]

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 93 bytes

```
a=>a.map(s=>(L=s.length,g=n=>a.every(S=>S==s|!~S.search(u=s.substr(n%L,n/L+1)))?u:g(n+1))(0))

```

Try it online!

### How?

For each string **s** of length **L** in the input array **a\[ \]** and starting with **n = 0**, we use the recursive function **g()** to generate all substrings **u** of **s** with:

```
u = s.substr(n % L, n / L + 1)

```

For instance, with **s = "abc"** and **L = 3**:

```
 n | n%L | floor(n/L+1) | u
---+-----+--------------+-------
 0 |  0  |       1      | "a"
 1 |  1  |       1      | "b"
 2 |  2  |       1      | "c"
 3 |  0  |       2      | "ab"
 4 |  1  |       2      | "bc"
 5 |  2  |       2      | "c"
 6 |  0  |       3      | "abc"
 7 |  1  |       3      | "bc"
 8 |  2  |       3      | "c"

```

Some substrings are generated several times, but it doesn't matter. What's important is that all substrings of length **N** have been generated before any substring of length **N+1**.

We stop the process as soon as **u** cannot be found in any *other* string **S** in **a\[ \]**, which is guaranteed to happen when **u == s** in the worst case, as per challenge rule #2:

> *no string in the list will be a substring of any of the other strings*

Therefore, in the above example, steps **7** and **8** will actually never be processed.
> 3 votes

# Answer
# PowerShell, 107 bytes

```
($a=$args)|%{$(for($i=0;$i++-lt($g=($s=$_)|% Le*)){0..($g-$i)|%{$s|% s*g $_ $i}|?{!($a-match$_-ne$s)}})[0]}

```

Try it online!

## Explanation

For each string supplied (and assign the whole array to `$a`):

* Do a `for` loop over each substring length (1 based) of the string (assigning the string itself to `$s` and the length to `$g`)
* For each length (`$i`):
    + Make an index loop, from 0 to to length - `$i`, then for each index:
        - Get the substring of the current string (`$s`) at position `$_` (index) and of length `$i`
        - Pass that substring to `Where-Object` (`?`), and return it if:
            * The subset of array (`$a`) that does not contain the current string `$s`, does not have a match for the current substring `$_`

Back at the string level, we have all of the substrings of this string that were not found in the others, so take the first one `[0]` since we only need one of them, then continue with the next string.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 149 bytes

```
a=>a.Select(s=>{var t=s;for(int j=0,k,l=s.Length;j++<l;)for(k=-1;j+k++<l;)if(!a.Where(u=>s!=u&u.Contains(t=s.Substring(k,j))).Any())j=k=l;return t;})

```

Try it online!

Less golfed...

```
// a is an input array of strings
a=>
  // iterate over input array
  a.Select(s=>{
    // t is the result string
    var t=s;
    // j is the substring length
    for(int j=0,k,l=s.Length;j++<l;)
      // k is the start index
      for(k=-1;j+k++<l;)
        // LINQ query to check if substring is valid
        // the tested string is collected in t
        if(!a.Where(u=>s!=u&u.Contains(t=s.Substring(k,j))).Any())
          // break loops
          j=k=l;
    // return result
    return t;
  })

```
> 0 votes

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