title: Calculate n Kaprekar Numbers

text:
# Question
Title: Calculate n Kaprekar Numbers
A Kaprekar number is an n-digit number *k* that, when the first *n* or *n-1* digits of k^2 are added to the second *n* the digits of N^2, the result is N.

Examples:

```
9^2 = 81.  8+1 = 9.
45^2 = 2025.  20+25 = 45.
297^2 = 88,209. 88+209 = 297

```

The Kaprekar sequence begins at 1.

Write a program that calculates and outputs the first *n* Kaprekar numbers, with *n* being in the range, but not limited to the range, of 1 to 100. Each Kaprekar number must be separated with whitespace and nothing else.

More Kaprekar numbers can be found here to check your program against, but this resource MAY NOT be used in any way to help with the calculation - in other words, no hard-coding, reading from this source, or using it in any other exploitive way - all the numbers must be generated by your program.

Shortest code wins.

# Answer
> 4 votes
## Perl - 63 bytes

```
#!perl -l
map{1while$l=length++$_,$_**2=~/.{$l}$/,$`+$&^$_;print}($_)x<>

```

Counting the shebang as one byte. Input is taken from `stdin`.

This has an acceptable runtime for *n ≤ 50*, after that it gets a bit slow.

Sample usage:

```
$ echo 20 | perl kaprekar.pl
1
9
45
55
99
297
703
999
2223
2728
4950
5050
7272
7777
9999
17344
22222
77778
82656
95121

```

# Answer
> 4 votes
# C, 109 106

```
long long i=1;x=10,n;main(){scanf("%d",&n);for(;n;x*=x<=++i?10:1)(i-i*i/x-i*i%x)||printf("%lld ",i,n--);}

```
* with `n` up to 17 it would be ok to remove the `long long`,
* The exceeding printf parameter is abused:)
* Why it is not possible to use empty statement in the ternary operator? the two `1` are silly...
* Thank to Josh for aditional 3 characters...

# Answer
> 3 votes
# Mathematica ~~144~~ 154

```
k@m_:=((x=m^2)-(w=FromDigits[Take[IntegerDigits@x,y=-IntegerLength@m]]))*10^y+w==m;
g@n_:=(s={};i=0;While[Length@s<n,If[k@i,s=Append[s,i]];i++];s)

```

Test

```
g[14]

```

> 0
> 1
> 9
> 45
> 55
> 99
> 297
> 703
> 999
> 2223
> 2728
> 4950
> 5050
> 7272

# Answer
> 3 votes
## Javascript 96

```
for(i=0,n=prompt(s='');n;i++){t=''+i*i;if(t.substr(0,l=t.length/2)==i-t.substr(l))n--,s+=i+' '}s

```

Output :

```
0 1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643 390313 461539 466830 499500 500500 533170 538461 609687 643357 648648 670033 681318 791505 812890 818181 851851 857143 961038 994708 999999

```

# Answer
> 3 votes
# python - 98

I used some nice python slicing to shave a few characters off.

```
i=n=0
while n<20:
 i+=1;s=str(i**2);l=-len(str(i))
 if int("0"+s[:l])+int(s[l:])==i:print(i);n+=1

```

# Answer
> 3 votes
C# - 255 Characters.

```
int x=100;decimal k=0;while(x>0){k++;decimal d=k*k;string s=d.ToString("n").Replace(",","").Split('.')[0];int g=k.ToString().Length;int h=s.Length;if(k==d||(h!=g&&long.Parse(s.Substring(h-g))+long.Parse(s.Substring(0,h-g))==k)){Console.Write(k+" ");x--;}}

```

x is the number of Kaprekar numbers you wish the code to find. This has been tested in the range of 1 to 100 but should support a lot more than this. 100 numbers took two and a quarter hours to return although the first 50 only took about 1 second - things slowed down gradually after that.

Output:

```
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778
82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643
390313 461539 466830 499500 500500 533170 538461 609687 643357 648648 670033
681318 791505 812890 818181 851851 857143 961038 994708 999999 4444444 4927941
5072059 5555556 9372385 9999999 11111112 13641364 16590564 19273023 19773073
24752475 25252525 30884184 36363636 38883889 44363341 44525548 49995000 50005000
55474452 55636659 61116111 63636364 69115816 74747475 75247525 80226927 80726977
83409436 86358636 88888888 91838088 94520547 99999999 234567901 332999667
432432432 567567568 667000333 765432099 999999999 1111111111 1776299581 2020202020
3846956652 3888938889 4090859091 4132841328 4756047561

```

Laid out this code is as follows;

```
        int x = 100;
        decimal k = 0;
        while (x > 0)
        {
            k++;
            decimal d = k * k;
            string s = d.ToString("n").Replace(",", "").Split('.')[0];
            int g = k.ToString().Length;
            int h = s.Length;

            if (k == d || (h != g && long.Parse(s.Substring(h - g)) + long.Parse(s.Substring(0, h - g)) == k) )
            {
                Console.Write(k + " "); x--;
            }
        }

```

I'd love to know if this can be shortened further.

# Answer
> 3 votes
# C, ~~90~~ ~~76~~ 75 bytes

```
long long d,r=1;k(n){for(;++d/r?r*=10:--n;d-d*d/r-d*d%r||printf("%d ",d));}

```

# Answer
> 2 votes
### R, 99 characters

```
k=n=0;N=scan();while(n<N){k=k+1;j=k^2;i=10^ceiling(nchar(j)/2);if(k==j%/%i+j%%i){cat(k," ");n=n+1}}

```

With `i` being half the number of digits of `k^2` rounded up, the evaluation of wether k is a Kaprekar number is performed here by adding the quotient and the remainder of the integer division of `k^2` by `10^i` (the quotient being the left half of the digits rounded down and the remainder the right half rounded up).

# Answer
> 2 votes
# Python 2.7, 144 (including newlines)

```
def c(c):
 l="1";i=2;u=1
 while u<c:
  r=str(i**2);w=len(r)
  if w>1:
   if i==int(r[:w/2])+int(r[w/2:]):
    l+=" "+str(i);u+=1
  i+=1
 print l

```

Output for c = 10:

```
1 9 45 55 99 297 703 999 2223 2728

```

Output for u = 20:

```
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121

```

# Answer
> 2 votes
# bash+sed, 75 characters

Bash does integer-only arithmetic and represents numbers as decimal strings; these attributes are helpful for golfing this challenge. Also undeclared/unassigned variables are assumed to have a value of 0 when doing arithmetic.

```
for((;s=++i*i,l=${#s}/2,1;));{
((${s:0:l}+10#${s:l}-i))||echo $i
}|sed $1q

```

It irked me to put the `10#` in there, but something like this is necessary if the second half of the split starts with a `0`. When doing arithmetic, treats such numbers as octal, unless the base is explicitly stated.

```
$ ./kaprekar.sh 10
1
9
45
55
99
297
703
999
2223
2728
$

```

# Answer
> 1 votes
## Python 3.3 - 117 characters

```
n=int(input())
p=1
while n>0:
    v=str(p**2)
    l=len(v)
    if p==int(v[l//2:])+int('0'+v[:l//2]):
        print(p)
        n-=1
    p+=1

```

---

Each level of indentation, and each newline except the final one, all count for 1 character. I think that is fair for Python code. The script expects the user to input the number of Kaprekar numbers to compute.

# Answer
> 1 votes
# J - 64

Kinda ugly, but still. It checks all numbers up to one million then takes `n` of them, so it works only for n\<=50.

```
n{.}.I.(]=+/&;&:(10&#.&.>)&(<.@-:@#({.;}.)])&(10&#.inv@*:))i.1e6

```

`n` is where to put the input

---
Tags: code-golf
---


# Question
Title: Is case sensitivity important? Part II: reality check
In this question Tom learned that, in general, there are many motivations to choose to include case sensitivity in his programming language, because the possible combinations for a variable name are much more than what's possible with a case insensitive programming language for a name of the same length.

But, as a more meticulous person than him pointed out, even with case sensitivity, many combinations like `A_18__cDfG` are wasted anyway because no one will ever use them, so Tom decided to be an even more meticulous person and to redo the calculation of the difference of possibilities of variable names between a case sensitive programming language and a case insensitive programming language only counting the variable names that are likely to be used.

# The Challenge

Write a function (or a full program if your language doesn't support them) that takes an input `n` and returns (or outputs) the difference between the number of possible, **valid** combinations for a variable name of length `n` with case sensitivity and a variable name of the same length without case sensitivity.

# Valid names

You must only count names in which:

* The first character is either an alphabet letter or an underscore, but never a digit;
* If there are digits, they must appear at the end of the name, so that `x1` and `arraysize12` are valid but `iam6feettall` isn't;
* If underscores are present, they must appear at the beginning of the name, like in `__private` and `_VERSION` but unlike in `__init__` or `some_variable`;
* For case sensitive names, variables like `HeLlObOyS` aren't counted. A name must be either all uppercase (`HELLOBOYS`) or all lowercase (`helloboys`);
* There must be at least one alphabetic character. This means `_________a9999999999` is valid but `__` or `_4` arent't.

# Rules

* Regexs are, of course, allowed;
* Blame Tom's meticulousness.

# Testcases

```
Input (lenght of the varable name) -> Output (differences in valid combinations)
0 -> 0 (no combinations for both cases: 0 - 0 = 0)
1 -> 26
2 -> 962
3 -> 27898
4 -> 754234
5 -> 19898970
6 -> 520262106

```

# Scoring

It's again code golf. Shortes program in bytes wins.

# Reference, non-competing Lua implementation

Since the test cases may be wrong, I've been asked to include it, so here it is:

```
local case = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"

local function isvalid(s)  --checks if a string s is valid AND only suitable for case sensitive
    if s:upper() == s then --if the string is all uppercase, it's also valid for case unsensitive
        return false
    end
    return (s:match"^_*[%w]+[%d]*$" --checks if it matchs the underscore-character-digit sequence
            and s:lower() == s)     --checks if it's all lowercase
            and true                --trasforms to boolean value
end

local function each(s, n) --recursive function called for character at position 2..n
    if n == 0 then
        if isvalid(s) then
            return 1
        end
        return 0
    else
        local total = 0
        for i = 1, #case do
            total = total + each(s..case:sub(i, i), n - 1)
        end
        return total
    end
end

local function diff(n) --the actual function
    local total = 0
    if n > 0 then
        for s = 1, #case - 10 do --loops for character at position 1, which can't be a digit
            total = total + each(case:sub(s, s), n - 1)
        end
    end
    print(string.format("%.0f", total)) --prints the result in non-scientific notation
end

```

# Answer
> 9 votes
# Haskell, 41 bytes

```
d n=sum[26^a*10^k|a<-[1..n],k<-[0..n-a]]

```

Runtime: O(k\*n²), where k depends on the size of the resulting numbers.

## Results

```
ghci> forM_ [0..100] $ \n -> printf "%3d: %d\n" n (d n)
  0: 0
  1: 26
  2: 962
  3: 27898
  4: 754234
  5: 19898970
  6: 520262106
  7: 13555703642
  8: 352737183578
  9: 9174055661914
 10: 238554336098650
 11: 6202701627453786
 12: 161273131202687322
 13: 4193130300158759258
 14: 109021676693016629594
 15: 2834566482907321258330
 16: 73698757444479241605466
 17: 1916167982445349170631002
 18: 49820370432467967325294938
 19: 1295329660133056039346557274
 20: 33678571452348345911899378010
 21: 875642860649945882598272717146
 22: 22766714405787481836443979534682
 23: 591934574839363416636432356790618
 24: 15390298948712337721436130165444954
 25: 400147772695409669646228273190457690
 26: 10403842090369540299690823991840788826
 27: 270499894352496936680850312676749398362
 28: 7032997253193809242590997018484373246298
 29: 182857928583327929196254811369482593292634
 30: 4754306143169415047991513984495436314497370
 31: 123611959722433680136668252485770233065820506
 32: 3213910952783564572442263453518914948600222042
 33: 83561684772375567772387738680380677552494661978
 34: 2172603804081793650970970094578786505253750100314
 35: 56487698906126923814134111347937338025486391497050
 36: 1468680171559302908056375783935259677551535067812186
 37: 38185684460541904498354659271205640505228800652005722
 38: 992827795974089805846110029940235542024837705841037658
 39: 25813522695326337840887749667335012981534669240755867994
 40: 671151590078484812751970380239599226408790289148541456730
 41: 17449941342040605420440118775118468775517436406750966763866
 42: 453698474893055743820331977041969077052342235464414024749402
 43: 11796160347219449368217520291980084892249787010963653532373338
 44: 306700169027705683862544416480371096087383351173943880730595674
 45: 7974204394720347783315043717378537387160856019411429787884376410
 46: 207329314262729042395080025540730860955071145393586063373882675546
 47: 5390562170830955102560969552947891273720738669122126536609838453082
 48: 140154616441604832669474097265534062005628094286064178840744688669018
 49: 3644020027481725649435215417792774501035219340326557538748250794283354
 50: 94744520714524866885604489751501025915804591737379384896343409540256090
 51: 2463357538577646539028605622427915562699808274060752896193817536935547226
 52: 64047296003018810014772635072014693519083904014468464189928144849213116762
 53: 1665229696078489060384377400761270920385070393265068957827020654968429924698
 54: 43295972098040715569996701308681932818900719113780681792391425918068066931034
 55: 1125695274549058604819943122914619142180307585847186615491065962758658629095770
 56: 29268077138275523725318810084668986585576886120915740891656603920614013245378906
 57: 760970005595163616858291951090282540113887928032698152071960590824853233268740442
 58: 19785220145474254038315619617236234931849975017739040842759864250335072953876140378
 59: 514415723782330604996206398937030997116988239350103950800645359397600785689668538714
 60: 13374808818340595729901369261251694813930583111991591609705668233226509316820270895450
 61: 347745029276855488977435629681432954051084049800670270741236262952778131126215932170586
 62: 9041370761198242713413326660606145694217074183706315928161031725661120298170503125324122
 63: 235075639791154310548746496064648676938532817665253103021075713756078016641321970147316058
 64: 6111966634570012074267408926569754489290742148185469567436857446546917321563260112719106394
 65: 158911132498820313930952632379702505610448184741711097642247182499108739249533651819585655130
 66: 4131689444969328162204768444761154034760541692173377427587315633865716109376763836198115922266
 67: 107423925569202532217323979592678893792662972885396702006159095369397507732684748630039902867802
 68: 2793022064799265837650423469698540127498126183909203141049025368493224089938692353269926363451738
 69: 72618573684780911778911010215050932203840169670528170556163548469712715227294890073906974338634074
 70: 1888082915804303706251686265620213126188733300322621323349141149101419484798556030810470221693374810
 71: 49090155810911896362543842906414430169795954697277043295966558765525795493651345689961114652916633946
 72: 1276344051083709305426139915569664073303583711018092014584019416792559571723823876827877869864721371482
 73: 33184945328176441941079637804840154794782065375359281268073393725495437753708309686413713505371644547418
 74: 862808578532587490468070582926132913553222588648230201858797125751770270485304940735645440028551647121754
 75: 22433023041847274752169835156082344641272676193742874137217614158434915921506817348015670329631231714054490
 76: 583258599088029143556415714058169849561978469926203616456546857008196702848066139937296317459300913454305626
 77: 15164723576288757732466808565512704977500329106970182916759107171102003162938608527258593142830712638700835162
 78: 394282812983507701044137022703333218303897445670113644724625675337540971125292710597612310602487417495110603098
 79: 10251353137571200227147562590286692564790222476311843651729156447664954138146499364426808964553561743761764569434
 80: 266535181576851205905836627347454295573434673272996823833846956528177696480697872363985921967281494226694767694170
 81: 6929914720998131353551752311033814573798190393986806308568909758621508997387033570352522860038207738782952848937306
 82: 180177782745951415192345560086879207807641839132545852911680542613048122820951761718054483249882290097245662961258842
 83: 4684622351394736795000984562258859691887576706335081064592582996828140082233634693558305453385828431417276125881618778
 84: 121800181136263156670025598618730354877965883253600996568296046806420531026963390921404830676920428105738068161810977114
 85: 3166804709542842073420665564086989255716001853482514799664586105855822695589937052845414486488820019638078661095974293850
 86: 82336922448113893908937304666261720937504937079434273680168127641140278974227252262869665537598209399478934077384220528986
 87: 2140759983650961241632369921322804747264017252954180004573260207558536142218797447723500192866442333275341174900878622642522
 88: 55659759574924992282441617954392923457753337465697569007793654285410828586577622529699893903416389554047759436311733077594458
 89: 1447153748948049799343482066814216010190475662997025683091523900309570432139907074661086130377715017294130634232993948906344794
 90: 37625997472649294782930533737169616267841256126811556649268510296937720124526472830077128278709479338536285378946731560453853530
 91: 978275934288881664356193877166410022992761548185989361769870156609269612126577182470894224135335351690832308741503909460689080666
 92: 25435174291510923273261040806326660598100689141724612294905512960729898804179895633132138716407608032850528916167990534866804986202
 93: 661314531579284005104787060964493175553506806573728808556432225867866257797566175350324495515486697743002640709256642795425818530138
 94: 17194177821061384132724463585076822564420065859805837911356126761453411591625609447997325772291543030206957547329561601569960170672474
 95: 447048623347595987450836053211997386675210601243840674584148184686677590271154734536819358968469007674269785119457490529707853326373210
 96: 11623264207037495673721737383511932053558364521228746428076741690742506235938911986846192222069083088419903301994783642661293075374592346
 97: 302204869382974887516765171971310233392546366440836296018884172848194051023300600546889886662685049187806374740753263598082508848628289882
 98: 7857326603957347075435894471254066068206494416350632585379877382941934215494704503108025942118700167771854632148473742439034118953224425818
 99: 204290491702891023961333256252605717773371743714005336108765700845379178491751205969697563383975093250957109324749206192303775981672723960154
100: 5311552784275166622994664662567748662107694225453027627716797110868747529674420244101025536872241313413773731332368249888787064412379711852890
(0.72 secs, 632,190,360 bytes)

```

## Ungolfed

```
difference :: Integer -> Integer
difference n = sum [ 26 ^ alpha * 10 ^ digits
                   | alphas <- [1 .. n]
                   , digits <- [0 .. n - alphas]
                   ]

```

## Explanation

All valid names have the structure, namely `[underscore]alpha[alpha][digit]`. We have at least one alphabet letter, arbitrary many underscores, and arbitrary many digits (as long as the resulting string has the correct length). The position of those is fixed by Tom's rules.

The number of valid case-insenstive combinations can be calculated as follows (`a` is the number of alphabet letters, `u` the number of underscores):

```
$$
c(n) = \sum_{a=1}^n \sum_{u=0}{n-a} 26^a \cdot 10^{n - a - u}
$$

```

The number of valid case-sensitive combinations can be calculated similarly, we just add `\sum_{\{L,U\}}`:

```
$$
C(n) = \sum_{\{L,U\} \sum_{a=1}^n \sum_{u=0}{n-a} 26^a \cdot 10^{n - a - u} \\
     = 2 \sum_{a=1}^n \sum_{u=0}{n-a} 26^a \cdot 10^{n - a - u}
$$

```

The difference `C(n) - c(n)` is… `c(n)`:

So all we have to do is to find out is the count of case-insensitive variants.

# Answer
> 4 votes
## JavaScript (ES7), 55 bytes

```
n=>[...Array(n)].reduce(r=>r+26**++i*(10**n---1)/9,i=0)

```

I get the same results as @Zeta does. I started along similar lines although I simplified `sum(10**[0..n-i])` to `(10**(n+1-i)-1)/9`.

# Answer
> 3 votes
# Pyth, ~~25~~ ~~18~~ 16 bytes

```
sm*^26ds^LTh-QdS

```

Try it online. Test suite.

I also get the same results as @Zeta.

# Answer
> 3 votes
## 05AB1E, ~~18~~ 14 bytes

```
Lv1¹y->×26ym*O

```

**Explanation**

```
Lv               # for each n in range(1,input)
  1¹y->×         # push 1 repeated (input-n+1) nr of times
        26ym     # 26^n
            *    # multiply the ones by the power of 26
             O   # sum and implicitly print

```

Try it online

# Answer
> 2 votes
## Racket, ~~91~~ 82 Bytes

Old solution (based off @Zeta's solution):

```
(λ(n)(for*/sum([i(in-range 1(+ 1 n))][j(in-range(+ 1(- n i)))])(*(expt 26 i)(expt 10 j))))

```

New solution (thanks to Neil's solution):

```
(λ(n)(for/sum([i(in-range 1(+ 1 n))])(*(expt 26 i)(/(-(expt 10(-(+ n 1)i))1)9))))

```

# Answer
> 1 votes
# Emacs lisp, 106 bytes

```
(defmath f(n)(let((r 0))(for((k 1(1+ n)))(setq r(+ r(*(^ 26 k)(/(1-(^ 10(- n k -1)))9)))))(calc-eval r)))

```

Creates a function called `calcFunc-f`. Pretty much the first (Emacs) lisp I've written, uses Neil's optimization.

---
Tags: code-golf, math, combinatorics, regular-expression
---


title: Pi Bowling to 10 in 10

text:
# Question
Title: Pi Bowling to 10 in 10
**Your Goal**: Estimate pi to at least 10 decimal places. The format is your choice - it can output as a number, as a string, as an output to STDOUT, etc.

Seems easy, right? But wait, it's not as simple as it seems...

**The Rules**: You get exactly 10 function calls (this includes operators). These functions cannot be ones that naturally induce or define pi, such as the arc-trig functions or a function converting degrees to radians (this also includes any function that operates as a "solver", such as one that can find roots of `sin(x)`). If your language has complex number capabilities, this capability cannot be used. All functions must be part of your languages built-in functions or within a standard library (loading the library does not count as an operation, but it must be a standard library, not just a popular one).

All function calls must be crucial to your code - this means that you cannot use division by one, or factorial of two. You also cannot use any literal (except for three digits in the form of one, two, or three integers)\*, reading of files of any sort, or a code's ability to convert itself into values (such as a function to get the name of a variable as a string).

\*Note: an exception is made for format strings for languages that require them for output. However, only formats, not actual contents, can be found in the format strings, so you can have `printf("%f%f",x,y)`, but not `printf("%f.%f",x,y)`.

Loops may be used, but will eat up your function calls - the 10 function calls are calls, not total functions used. Assignment does not count as an operation, but operations such as array slicing (including obtaining a single value from an array) count, in which case a\[1\] would count as two bytes (for `[]`).

If you think you've found a loophole for the rules, then it's also against the rules. This is *not* a challenge for finding the best bending of the rules, or the best way of abusing a minor oversight in the challenge question... if your instinct is to call it a "loophole", then post it as a comment to help close it.

**Scoring**: This is code bowling, so you're after the highest score. But it's not the total number of bytes in your code that is being counted.

Instead, it's the sum of bytes in the functions being used. That is, if you use `4*cos(2/3)` (which happens to be approximately 3.14355), then you have three functions - `*`, `cos`, and `/`, with the total being 5 bytes. If you were to use, for instance (using Julia), `sum(map(n->1/n,1:4))`, then the operations are `sum`, `map`, `/`, and `:`, for 8 bytes... but as 1/n is being called four times, it uses 7 function calls (`sum`, `map`, four instances of `/`, and `:`). User-made functions do not count towards either the function call allowance or the byte count (note: functions used *in* those user-made functions *do* count).

**Additional emphasis**: The point, here, is to find the best way to abuse your language's longest built-in/standard function names in the context of calculating pi. More digits of pi aren't necessary, but I will personally be more likely to upvote an answer that gets more digits than necessary.

Remember, since you're after long function names, you should probably avoid unary and binary operators, as most of these have full function equivalents (in Julia, for instance, `*` can be replaced by `prod`).

**Quick Summary**: You have 10 built-in function calls (includes operators/subroutines/etc). You must estimate pi to 10 decimal places. You can use a *total* of 3 characters for integer literals (so you can have 1 and 36, or 1 and 2 and 3, or 328, but you can't have 22 and 49). Score is count of built-in function name bytes (if the user defines the name, it doesn't count). No functions that calculate or use pi directly. No complex numbers. This is not a challenge to find loopholes.

# Answer
> 4 votes
# R, ~~34~~ 42 Points

I think I have complied with all the rules and scored it correctly.

**Edit** Turns out not complying with the rules in the first place was a bit of a bonus.

Use this formula to calculate pi `(63/25)x((17+sqrt(5)*15)/(7+sqrt(5)*15))`

```
# set up the required numbers
a<-5
b<-2
# Calculate 5^.5 * 15                    3 Operations 11 Bytes
c<-prod(sqrt(a),sum(a,a,a))
# Calculate (17 + c) / (7 + C)           3 Operations 7 Bytes
d<-sum(a,a,a,b,c)/sum(a,b,c)
# Calculate (63/25)*d                    3 Operations 19 Bytes
pi<-prod(as.double(paste0(b,'.',a,b)),d)
# Output pi showing all digits           1 Operations 5 Bytes
strwrap(pi)

```

Test run

```
> a<-5
> b<-2
> c<-prod(sqrt(a),sum(a,a,a))  # 3 Operations 11 Bytes
> d<-sum(a,a,a,b,c)/sum(a,b,c) # 3 Operations 7 Bytes
> pi<-prod(as.double(paste0(b,'.',a,b)),d) # 3 Operations 19 Bytes
> strwrap(pi)                    # 1 Operations 5 Bytes
[1] "3.14159265380569"

```

# Answer
> 2 votes
## C#

Exactly 10 function calls and 3 numeric literals.

```
using System;
using System.Linq;

namespace ConsoleApplication2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            /*3:*/
            int a = 3; //0 calls: 0
            /*14->15:*/
            int b = 14; //0 calls: 0 + 0 = 0
            /*14:*/
            int c = (b)++; //1 call: 0 + 1 = 1
            /*926:*/
            int d = 926; //0 calls: 1 + 0 = 1
            /*53:*/
            int e = (a*c) + (a*a); //3 calls: 1+3 = 4
            //3*14 + 3*3 = 42+9 = 51
            e++; //1 call: 4 + 1 = 5
            e++; //1 call: 5 + 1 = 6
            /*5:*/
            char f = e.ToString().ToCharArray().First(); //3 call: 6 + 3 = 9

            Console.WriteLine("{0}.{1}{2}{3}{4}{5}", a, c, b, d, e, f); //1 call: 9 + 1 = 10
        }
    }
}

```

Outputs: 3.1415926535

# Answer
> 1 votes
# C, 23 bytes

I think this is correct now...

```
#include <stdio.h>
#include <math.h>

main()
{
    double pi= (double)22 / 7; /* 1 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */

    printf("%.10f", pi); /* 6 bytes = 6 */
    return 0;
}

```

# Answer
> 0 votes
# Racket, 72 bytes

Gotta love those verbose built-in names!

```
((lambda() ; lambda is a Racket-defined function too, 6 bytes
  (define-values (a b) (integer-sqrt/remainder 491)) ; 13 (define-values) + 22 (integer-sqrt/remainder) = 35 (on this line alone).  a and b are 22 and 7 respectively
  (define-values (q) (/ a b)) ; 13 (define-values) + 1 (/) = 14
  (define-values (c) (+ (sin q) q)) ; 13 + 1 + 3  = 17
  (+ (sin c) c) ; 1 + 3 = 4
  )) ; total: 6 + 35 + 14 + 17 + 4 = 72

```

With the amount of precision that `in-exact` numbers in Racket have, this is actually equal to pi such that `(- pi (lambda...)` outputs `0.0`.

Also, I know this is a realllllllllllly old challenge. But all of the current challenge answers do horribly in comparison to this bowl, so I had to do it.

---
Tags: pi, function, code-bowling
---


title: Generalization of abbreviations

text:
# Question
Title: Generalization of abbreviations
Given an input of a list of words and their abbreviations, output the pattern by which the abbreviations can be formed.

Let us take the example input of

```
potato ptao
puzzle pzze

```

as an example (that is, the abbreviation for `potato` is `ptao`, and the abbreviation for `puzzle` is `pzze`).

Consider all possible ways to obtain `ptao` from `potato`. One possible way is to take the first, third, fourth, and sixth letters, which we will refer to as `1346`. But since `t` and `o` appear multiple times in the word, there are multiple other possible ways to generate `ptao` from `potato`: `1546`, `1342`, and `1542`.

Similarly, note that `pzze` can be generated from `puzzle` with any of `1336`, `1346`, `1436`, `1446`. The only pattern that these two abbreviations have in common is `1346`; therefore, that must be the output for this input. If multiple possible patterns are possible, you may output any, some, or all of them (at least one).

You may assume that:

* Input words and abbreviations contain only lowercase letter.
* There is at least one word/abbreviation pair in the input.
* It is possible for every abbreviation to be formed from its corresponding word.
* There will always be at least one pattern that forms every abbreviation.
* The maximum length of each word is 9 characters.

Input may be taken as any of the following:

* 2-dimensional array/list/array of tuples/etc. `[[word, abbr], [word, abbr],
...]`
* flat 1-dimensional array/list `[word, abbr, word, abbr, ...]`
* single string, delimited by any single character that is not a lowercase letter `"word abbr word abbr"`
* hash/associative array/etc. `{word => abbr, word => abbr, ...}`

In any of these input options, you are also permitted to swap the order of word/abbr (please fully describe the input format in your post).

Output may be given as a single number, a string delimited by non-digits, or an array/list/tuple/etc. of numbers.

Since this is , the shortest code in bytes will win.

Test cases (remember that you only need to output ≥1 results if multiple patterns work):

```
In                                Out
--------------------------------------------------------
potato ptao puzzle pzze         | 1346
aabbcc abc fddeef def           | 246
prgrmming prgmg puzzles pzzlz   | 14353
aaaaa a bbbb b ccc c dd d e e   | 1
aaaaa a bbbb b ccc c            | 1, 2, 3
abcxyz zbcyax                   | 623514
abcxyz acbbacbcbacbbac          | 132213232132213
potato ptao                     | 1346, 1546, 1342, 1542
a aaaaa                         | 11111

```

# Answer
> 3 votes
# MATL, 29 bytes

```
!"@Y:!=2#fX:wX:h]N$v1XQtv4#X>

```

Input is a 2D array in the following format:

```
{'potato' 'ptao'; 'puzzle' 'pzze'}

```

**Try it online!** (*the linked code includes some modifications owing to changes in the language since this answer was posted*)

```
!       % take input. Transpose
"       % for each column
  @Y:   %   push column. Unpack the two strings and push them onto the stack
  !     %   transpose second string
  =     %   matrix with all pairwise matchings of characters in word and abbreviation
  2#f   %   find row and col indices of those matchings
  X:    %   transform into column vector
  wX:   %   swap, transform into column vector
  h     %   concat into a two-col matrix
]       % end for
N$v     % concatenate all matrices containing the indices
1       % push 1
XQ      % build matrix adding 1 for each (row,col) index
tv      % concat vertically with itself, so that it has at least two rows.
        % This forces the following function to work on each col.
4#X>    % arg max of each col: position that produces a match in all pairs.
        % If there are several maximizers in each col this gives the first

```

The code required some involved (and lengthy!) tricks to

* Prevent the orientation of vectors produced by `find` (`f`) from changing depending on input shape. These are statements `X:wX:`: force both outputs to be column vectors.
* Counteract the "work along first non-singleton dimension" default behaviour of the `min` (`X>`) function. These are statements `tv`: concat a copy of itself to assure at least two rows);

# Answer
> 3 votes
# Pyth, 19 bytes

```
mhh@Fd.TmmxkmbhdedQ

```

Try it here!

Takes a list in the following format:

```
[["word","abbr"],["word","abbr"],...]

```

Alternative 17 bytes solution which outputs the result as list of zero-based indices which are wrapped in an 1-element list:

```
m@Fd.TmmxkmbhdedQ

```

## Explanation

Example: `[["potato", "ptao"],["puzzle", "pzze"]]`

First we map every char in the abbrevation to a list of the indices of all occurences in the word which yields

`[[[0], [2, 4], [3], [1, 5]], [[0], [2, 3], [2, 3], [5]]]`

Then we transpose this list which gives us

`[[[0], [0]], [[2, 4], [2, 3]], [[3], [2, 3]], [[1, 5], [5]]]`

So the indices of each char of each abbrevation are together in one list.

Then we just have to find one common index in all of those lists which yields:

`[[0], [2], [3], [5]]`

This is the output of my alternative 17 byte solution above. This then gets transformed into `[1,3,4,6]`.

### Code breakdown

```
mhh@Fd.TmmxkmbhdedQ   # Q = input

m                 Q   # map input with d
        m       ed    # map each abbrevation with k
            mbhd      # map word to char list
         mxk          # map each abbrevation char to a list of indices
      .T              # Transpose
    Fd                # Fold every element
   @                  # and filter on presence
 hh                   # Take first element of the result und and increment it

```

# Answer
> 2 votes
# Perl, ~~46~~ ~~45~~ 42 bytes

Includes +1 for `-p`

Give input as sequential words on STDIN, e.g.

```
perl -p abbrev.pl
prgrmming
prgmg
puzzles
pzzlz

```

Terminate STDIN with `^D` or `^Z` or whatever is needed on your system

`abbrev.pl`:

```
s#.#${${--$_.$.%2}.=$&}||=-$_#eg;$_ x=eof

```

## Explanation

Consider this input (conceptual layout, not the real way to input for this program):

```
potatoes     ptao
puzzle       pzze

```

The program build strings representing the vertical columns of the full strings indexed on a column id

```
id1    pp     -> 1
id2    ou     -> 2
id3    tz     -> 3
id4    az     -> 4
...

```

etc. It also does the same for the abbreviations, but using a different id

```
ID1    pp     -> 1
ID2    tz     -> 3
ID3    az     -> 4
ID4    oe     -> 6

```

The words are implicitely processed one by one by using the `-p` option. The columns strings are constructed using repeated concatenations while each word is walked using `s#.# ...code.. #eg`, so each column needs a repeatable id. I use minus the column number followed by the line number modulo 2. The column number can be constructed using `--$_` which starts out as the current word which due to the use of only `a-z` is guaranteed to evaluate as 0 in a numeric context. So I get `-1, -2, -3, ...`. I'd really would have liked to use `1, 2, 3, ...`, but using `$_++` would trigger perl magic string increment instead of a normal numeric counter. I **do** want to use `$_` and not some other variable because any other variable I would have to initialize to zero in every loop which takes too many bytes.

The line number modulo 2 is to make sure the ids for the full word and the ids for the abbreviation don't clash. Notice that I cannot use the full word and the abbreviation on one string to have a column number going over the combined string because the full words don't all have the same length, so the abbeviated word columns wouldn't line up. I also can't put the abbreviated word first (they all have the same length) because I need the count of the first column of the full words to be 1.

I abuse the perl global name space through a non strict reference to construct the column strings as:

```
${--$_.$.%2}.=$&

```

Next I map each column string to the first column number that string ever appears in (the mapping already indicated above) by again abusing the perl global namespace (but notice that the names cannot clash so the globals don't interfere with each other):

```
${${--$_.$.%2}.=$&} ||= -$_

```

I have to negate `$_` because like I explained above I count the columns as `-1, -2, -3, ...`. The `||=` make sure only the first appearance of a given column gets a new column number, otherwise the previous column number is preserved **and** returned as value. This will happen in particular for every abbreviated word since the specification guarantees that there is a column in the full words that will have appeared beforehand. So in the very last abbreviated word each letter will be replaced by the column number in the full word that corresponds with the column for all abbreviated words. So the result of the very last substitution is the final result that is wanted. So print if and only if we are at the end of the input:

```
$_ x=eof

```

The column index assignment will also create entries for incomplete columns because the column is not completely constructed yet or some words are shorter and don't reach the full column length. This is not a problem since the columns needed in every abbreviated word are guaranteed to have a corrsponding column from the full words which has the maximum possible length (the number of currently seen pairs) so these extra entries never cause false matches.

# Answer
> 1 votes
## Haskell, 74 bytes

```
import Data.List
foldl1 intersect.map(\(w,a)->mapM(`elemIndices`(' ':w))a)

```

Input format is a list of pairs of strings, e.g.:

```
*Main > foldl1 intersect.map(\(w,a)->mapM(`elemIndices`(' ':w))a)  $ [("potato","ptao"),("puzzle","pzze")]
[[1,3,4,6]]

```

How it works: `mapM` (same as `sequence . map`) first turns every pair `(w,a)` into a list of lists of indices of the letters in the abbreviation (`' ':` fixes Haskell's native 0-based index to 1-based), e.g. `("potato", "ptao") -> [[1],[3,5],[4],[2,6]]` and then into a list of all combinations thereof where the element at position `i` is drawn from the `i`th sublist, e.g. `[[1,3,4,2],[1,3,4,6],[1,5,4,2],[1,5,4,6]]`. `foldl1 intersect` finds the intersection of all such lists of lists.

# Answer
> 0 votes
## ES6, 92 bytes

```
(w,a)=>[...a[0]].map((_,i)=>[...w[0]].reduce((r,_,j)=>w.some((s,k)=>s[j]!=a[k][i])?r:++j,0))

```

Accepts input as an array of words and an array of abbreviations. Returns an array of 1-based indices (which costs me 2 bytes dammit). In the case of multiple solutions, the highest indices are returned.

# Answer
> 0 votes
## Python 3, 210 bytes

Not an impressive answer seing the topscores here, but this is truly some of the craziest list comprehension I've ever done with Python. The approach is quite straigthforward.

```
 def r(p):
    z=[[[1+t[0]for t in i[0]if l==t[1]]for l in i[1]]for i in[[list(enumerate(w[0])),w[1]]for w in p]]
    return[list(set.intersection(set(e),*[set(i[z[0].index(e)])for i in z[1:]]))[0]for e in z[0]]

```

The function expects input always as a string 2-D array like: `[[word, abbr],...]` and returns a list of integers.

Ps: A detailed explanation coming soon

Ps2: Further golfing suggestions are welcomed!

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


title: Rotate a diamond tiling

text:
# Question
Title: Rotate a diamond tiling
Any regular hexagon can be tiled with diamonds, for instance like so (stolen from this question):

```
   ______
  /_/_/\_\
 /_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
 \_\/_/\_\/
  \_\_\/_/

```

We'll consider the above a tiling of size 1 (since the diamonds' sides are made of one / or \ each). The same tiling of size 2 would look like:

```
      ____________
     /   /   /\   \
    /___/___/  \___\
   /   /\   \  /\   \
  /___/  \___\/  \___\
 /\   \  /   /\  /   /\
/  \___\/___/  \/___/  \
\  /   /\   \  /   /\  /
 \/___/  \___\/___/  \/
  \   \  /   /\   \  /
   \___\/___/  \___\/
    \   \   \  /   /
     \___\___\/___/

```

Your task is to rotate diamond tilings by a multiple of 60 degrees. The diamond tiling in the input can be in any size (and the size is not explicitly specified in the input). But it would always be a valid tiling, and all sides of the hexagon would have the same length.

These are the above examples rotated by 60 degrees clockwise:

```
   ______
  /_/\_\_\
 /\_\/_/\_\
/\/_/\_\/_/\
\/\_\/_/_/\/
 \/_/\_\_\/
  \_\/_/_/

      ____________
     /   /\   \   \
    /___/  \___\___\
   /\   \  /   /\   \
  /  \___\/___/  \___\
 /\  /   /\   \  /   /\
/  \/___/  \___\/___/  \
\  /\   \  /   /   /\  /
 \/  \___\/___/___/  \/
  \  /   /\   \   \  /
   \/___/  \___\___\/
    \   \  /   /   /
     \___\/___/___/

```

The input is a non-negative integer and a diamond tiling. Your program (or function) should rotate it by the integer * 60 degrees. You decide whether to rotate clockwise or counterclockwise, as long as it is consistent. Both the input and output shouldn't have extra leading or trailing spaces.

This is code-golf. Shortest code wins.

Related questions:

# Answer
## JavaScript (ES6), ~~452~~ ~~356~~ 315 bytes

Where `\n` represents the literal newline character. Edit: Saved 96 bytes by realising that my algorithm doesn't need to know the number and size of diamonds separately, plus a few minor golfs that I missed the first time around. Saved 41 bytes by rearranging the code so that the destination was always the same pair of characters, plus a minor golf that I missed when converting to my previous algorithm.

```
r=
(s,n)=>(z=s.search`_`,l=(f,n=z*2+1)=>[...Array(n)].map(f),a=s.split`\n`,l(_=>(o=a.map(s=>[...s].fill` `),l((_,r)=>l((_,c)=>(d=z+c*2-r,a[s=z+r-c]&&(a[s][r+c]=='/'?o[r][d]=o[r][d+1]='_':0,a[s][r+c-1]=='\\'?o[r][d]='/':0),a[--s]&&(a[s][r+c]==`_`||a[s][r+c-1]==`_`?o[r][d+1]=`\\`:0)))),a=o.map(a=>a.join``)),n),a.join`\n`)
;
```

```
<pre id=i1>
   ______
  /_/_/\_\
 /_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
 \_\/_/\_\/
  \_\_\/_/
</pre>
<input type=button value="Rotate!" onclick="i1.textContent = r(i1.textContent, 1)">
<pre id=i2>
      ____________
     /   /   /\   \
    /___/___/  \___\
   /   /\   \  /\   \
  /___/  \___\/  \___\
 /\   \  /   /\  /   /\
/  \___\/___/  \/___/  \
\  /   /\   \  /   /\  /
 \/___/  \___\/___/  \/
  \   \  /   /\   \  /
   \___\/___/  \___\/
    \   \   \  /   /
     \___\___\/___/
</pre>
<input type=button value="Rotate!" onclick="i2.textContent = r(i2.textContent, 1)">
```

Explanation: Considers each pair of output characters, which could be `__`, `/_`, `_\`, `/` or `\`, checking for the appropriate characters in the input which map to those output characters. Ungolfed:

```
function rotate(str, num) {
  // Measure the size using the indent of the _ in the first row.
  var size = str.indexOf('_');
  var arr = str.split('\n');
  while (num--) {
    // We build a character array to represent the output by turning the
    // input into a nested array and replacing everything with spaces.
    // Note that the output will have any trailing spaces from the input.
    var res = arr.map(s => Array.from(s).fill(' '));
    // Loop over a diamond that encloses the hexagon.
    for (var destrow = 0; destrow <= size * 2; destrow++) {
      for (var col = 0; col <= size * 2; col++) {
        var destcol = size + col * 2 - destrow;
        var srcrow = size + destrow - col;
        var srccol = destrow + col;
        // Map / to __, \ to / and __ to \.
        // We write __ first in case it gets overwritten by / or \.
        if (arr[srcrow]) {
          if (arr[srcrow][srccol] == '/') {
            res[destrow][destcol] = res[destrow][destcol + 1] = '_';
          }
          if (arr[srcrow][srccol - 1] == '\\') {
            res[destrow][destcol] = '/';
          }
        }
        // Need to check both positions in case one was overwritten.
        if (arr[srcrow - 1] &&
            (arr[srcrow - 1][srccol] == '_' || arr[srcrow - 1][srccol - 1] == '_')) {
          res[destrow][destcol + 1] = '\\';
        }
      }
    }
    arr = res.map(a => a.join(''));
  }
  return arr.join('\n');
}

```
> 3 votes

# Answer
# Pyth, 81 bytes

```
ju.es.e.reh|@s.e.e[yYykZ)bGCa+LV,t-y+k*3Y*5J-+kY/lG2Jc2j406610 4K"_/\\_\\"dKbGQ.z

```

Try it online

Rotates counterclockwise.

Each 60° rotation is performed using the following algorithm. Suppose the input is a hexagon of order *k*, so it has 2⋅*k* \+ 1 rows and 4⋅*k* columns. To find the rotated character at row *i* column *j*, let

* *u* = *i* \+ *j**k*
* *v* = *j* − 3⋅*i* \+ 5⋅*k*

Then the output character is

* `\`, if the input has `/` at row (*u* \+ 1)/2 column (*v* \+ 1)/2; else
* `/`, if the input has `_` at row *u*/2 column *v*/2 or row *u*/2 column (*v* \+ 2)/2; else
* `_`, if the input has `\` at row (*u* \+ 2)/2 column *v*/2 or row (*u* \+ 1)/2 column (*v* − 1)/2; else
* space.

(We do not count characters at half-integer indices.)
> 3 votes

---
Tags: code-golf, ascii-art, hexagonal-grid, tiling
---


# Question
Title: Coercing a string to an integer in GolfScript
**GolfScript** automatically coerces values, according to the following ‘priority’ sequence:

> integer → array → string → block

(listed from lowest to highest.)

This means that `"1"7+` leaves the string `"17"` on the stack (and not `8`), because strings have a higher priority than integers.

\[*To those GolfScript veterans – apologies for insulting your respective intelligences.*\]

How would it be possible to do this the other way? That is, to **coerce a string into an integer**?

# Answer
> 10 votes
There's an operator `~` in golfscript, which does the following: `bitwise not, dump, eval`.

Therefore, `"1"` will give the string `"1"` while `"1"~` will evaluate that string (into the integer `1`).

Then, all you need to do is `"1"~7+`.

Try it online!

---
Tags: tips, golfscript
---


title: Save the pilot!

text:
# Question
Title: Save the pilot!
## Question

We are captured by robot army on their space station. Our space ship pilot is in the prison which is in level 1. There is only one way how to escape and it's rescuing your space ship pilot. It mean's moving from level N to level 1. However because it's very risky you need to get to the prison in the least number of steps as possible.

## Conditions

* There are 4 ways how to move:

1. Move from level N to level N - 1 `e.g. from 12 to 11`
    2. Move from level N to level N + 1 `e.g. from 12 to 13`
    3. Use teleport from level 2k to level k `e.g. from 12 to 6`
    4. Use teleport from level 3k to level k `e.g. from 12 to 4`
* Teleports are only one-way (you can get from 12 to 4 but it's imposible to get from 4 to 12)
* Every action takes one step

## Input

Input should be read from STDIN, or the closest alternative in your programming language. Input consists of an integer `n` where `1 <= n <= 10^8`.

## Output

The output should be the minimum number of steps it takes to go from `n` to level 1.

## Examples

```
Level         Minimum number of steps
1             0
8             3
10            3
267           7
100,000,000   25

```

---

Try to code program that will help us to save our space ship pilot from the prison in the shortest time and return home!

The shortest code will win!

# Answer
# Pyth, 32 bytes

```
L?<b3tbhSsmm+h%_Wkbdy/+kbd2tS3yQ

```

Try it online: Demonstration or Test Suite

### Explanation:

I transformed the problem a little bit. I define 4 new operations, that replace the 4 operations of the question.

* `level / 2` (counts as `(level % 2) + 1` steps, because you might need to do move a level down first in order to teleport)
* `(level + 1) / 2` (counts as `(level % 2) + 1` steps)
* `level / 3` (counts as `(level % 3) + 1` steps)
* `(level + 1) / 3` (counts as `(-level % 3) + 1` steps)

By design these operations can be applied to each number, if the number is `0 mod 2`, `1 mod 2`, `0 mod 3`, `1 mod 3` or `2 mod 3`.

You can easily think about, why this works. The main idea is, that there is at least one optimal solution, that doesn't have two (move down) or two (move up) motions in a row. Proof: If you have a solution, that has two such motions in a row, than you can replace them and make the solution smaller or equal in length. For instance you could replace (move up, move up, teleport from 2k to k) by (teleport from 2k to k, move up) and similar in all other cases.

```
L?<b3tbhSsmm+h%_Wkbdy/+kbd2tS3yQ
L                                 define a function y(b), which returns:
 ?<b3                               if b < 3:
     tb                               return b-1
                                    else:
          m                tS3        map each d in [2, 3] to:
           m              2             map each k in [0, 1] to:
              %_Wkbd                      (b mod d) if k == 0 else (-b mod d)
             h                            +1, this gives the additional steps
            +       y/+kbd                + f((b+k)/d) (recursive call)
         s                            combine the two lists
       hS                             and return the minimum element
                               yQ call y with input number

```

The function `y` uses implicitly memoization and therefore the runtime doesn't explode.
> 8 votes

# Answer
### Python, 176 bytes

```
n=int(1e8);s,f,L=0,input(),[1,0]+[n]*(n-1)
def h(q):
 if 0<=q<=n and L[q]>s:L[q]=s+1
while n in L:
 for i,v in enumerate(L):
  if v==s:map(h,(i-1,i+1,i*2,i*3))
 s+=1
print L[f]

```

Brute force all the way; a list of all numbers `1 to 100,000,000` on a 64bit computer is ~800Mb of memory.

The list index represents the numbers, values represent the distance from 1 in allowed rescue steps.

* Set list\[1\]=0 meaning "reachable in 0 steps".
* for every number in the list which is reachable in 0 steps (i.e. `1`)
    + set number+1, number-1, number\*2, number\*3 reachable in 1 step
* for every number in the list which is reachable in 1 step (i.e `0,2,2,3`)
    + set number+1, number-1, number\*2, number\*3 reachable in 2 steps
* ... etc. until every list index is reached.

Runtime is a bit over 10 minutes. \*ahem\*.

### Code comments

```
n=int(1e8)           # max input limit.
s=0                  # tracks moves from 1 to a given number.
f=input()            # user input.

L=[1,0]+[n]*(n-1)    # A list where 0 can get to room 1 in 1 step,
                     # 1 can get to itself in 0 steps,
                     # all other rooms can get to room 1 in
                     # max-input-limit steps as a huge upper bound.

def helper(q):
    if 0<=q<=n:      # Don't exceed the list boundaries.
      if L[q]>s:     # If we've already got to this room in fewer steps
                     # don't update it with a longer path.
          L[q]=s+1   # Can get between rooms 1 and q in steps+1 actions.

while n in L:        # until there are no values still at the
                     # original huge upper bound

 for i,v in enumerate(L):
  if v==s:                            # only pick out list items
                                      # rechable in current s steps,
      map(helper,(i-1,i+1,i*2,i*3))   # and set the next ones reachable
                                      # in s+1 steps.

 s+=1                                 # Go through the list again to find
                                      # rooms reachable in s+1 steps

print L[f]                            # show answer to the user.

```

### Other

* If you run it in PythonWin, you can access the list L in the interpreter afterwards.
* Every room has a path to the captain in 30 moves or less.
* Only one room is 30 moves away - room 72,559,411 - and there are 244 rooms which are 29 moves away.
* It may have terrible runtime characteristics for the maximum case, but one of the question comments is "*@Geobits all programs that should find shortest ways for 20000 test cases in 5 minutes*" and it tests 1-20,001 in \<6 seconds.
> 4 votes

# Answer
# Python 2 ... 1050

poorly written, ungolfed, unoptimal.

Reads the start level on stdin, prints the minimum number of steps on stdout.

```
def neighbors(l):
    yield l+1
    yield l-1
    if not l%3:yield l/3
    if not l%2:yield l/2

def findpath(start, goal):
    closedset = set([])
    openset = set([start])
    came_from = {}
    g_score = {}
    g_score[start] = 0
    f_score = {}
    f_score[start] = 1
    while len(openset) > 0:
        current = min(f_score, key=f_score.get)
        if current == goal:
            return came_from
        else:
            openset.discard(current)
        del f_score[current]
        closedset.add(current)
        for neighbor in neighbors(current):
            if neighbor in closedset:
                continue
            tentative_g_score = g_score[current] + 1
            if (neighbor not in openset) or (tentative_g_score < g_score[neighbor]):
                came_from[neighbor] = current
                g_score[neighbor] = tentative_g_score
                f_score[neighbor] = tentative_g_score + 1
                openset.add(neighbor)
def min_path(n):
    path = findpath(n,1)
    i,current = 0,1
    while current <> n:
        i+=1
        current = path[current]
    return i
print min_path(input())

```
> 2 votes

# Answer
# 32-bit x86 machine code, 59 bytes

In hex:

```
31c9487435405031d231dbb103f7f14a7c070f94c301d008d353e8e3ffffff5b00c3585331d2b102f7f152e8d2ffffff5a00d05a38d076019240c3

```

The machine language *per se* has no concept of standard input. Since the challenge is pure computational, I opted to write a function taking input parameter in `EAX` and returning result in `AL`.

The math behind the code is nicely explained by @Jakube: the search is conducted only among the paths having teleports interspersed with no more than one one-level moves. The performance is about 12000 test cases per second in the lower end of input range and 50 cases per second in the upper end. The memory consumption is 12 bytes of stack space per recursion level.

```
0:  31 c9               xor ecx, ecx
_proc:
2:  48                  dec eax
3:  74 35               je _ret       ;if (EAX==1) return 0;
5:  40                  inc eax       ;Restore EAX
6:  50                  push eax
7:  31 d2               xor edx, edx  ;Prepare EDX for 'div'
9:  31 db               xor ebx, ebx
b:  b1 03               mov cl, 3
d:  f7 f1               div ecx       ;EAX=int(EAX/3); EDX=EAX%3
f:  4a                  dec edx       ;EDX is [-1..1]
10: 7c 07               jl _div3      ;EDX<0 (i.e. EAX%3==0)
12: 0f 94 c3            sete bl       ;BL=EDX==0?1:0
15: 01 d0               add eax, edx  ;If EAX%3==2, we'd go +1 level before teleport
17: 08 d3               or bl, dl     ;BL=EAX%3!=0
_div3:
19: 53                  push ebx      ;Save register before...
1a: e8 e3 ff ff ff      call _proc    ;...recursive call
1f: 5b                  pop ebx
20: 00 c3               add bl, al    ;BL is now # of steps if taken 3n->n route (adjusted) less one
22: 58                  pop eax       ;Restore original input parameter's value
23: 53                  push ebx
24: 31 d2               xor edx, edx
26: b1 02               mov cl, 2
28: f7 f1               div ecx       ;EAX=EAX>>1; EDX=EAX%2
2a: 52                  push edx      ;Save register before...
2b: e8 d2 ff ff ff      call _proc    ;...another recursive call
30: 5a                  pop edx
31: 00 d0               add al, dl    ;AL is now # of steps if using 2n->n route (adjusted) less one
33: 5a                  pop edx
34: 38 d0               cmp al, dl    ;Compare two routes
36: 76 01               jbe _nsw
38: 92                  xchg eax, edx ;EAX=min(EAX,EDX)
_nsw:
39: 40                  inc eax       ;Add one for the teleport itself
_ret:
3a: c3                  ret

```
> 2 votes

---
Tags: code-golf
---


title: I programming puzzles, il code golf

text:
# Question
Title: I programming puzzles, il code golf
# Background

The Italian definite article (corresponding to English *the*) has seven different forms: *l'*, *il*, *lo*, *gli*, *i*, *la*, *le*. Which one to use depends on three variables:

* Gender: masculine / feminine.
* Number: singular / plural.
* Initial letter of the subsequent word: vowel / consonant type A / consonant type B.
    + Vowel is any of these: *aeiou*.
    + Consonant type B is any of these cases: *s-* followed by another consonant, *z-*, *gn-*, *pn-*, *ps-*, *x-*, *i-* followed by vowel (this *i* acts as a semivowel).
    + Consonant type A is a consonant that is not type B.

The table shows the article form to be used in each of the twelve combinations of the three above variables. Note that the *l'* form is attached to the following word with a single quote and without a space.

# The challenge

Input **a word** and one or two strings, numbers or Booleans indicating **gender** and **number**. (The initial letters will have to be obtained from the input word).

The input word will be a sequence of lowercase ASCII letters. Accented vowels will be replaced by their non-accented versions (for example, *realtà* will be input as *realta*).

The gender and number inputs can be separate numbers, Booleans or strings, or a combined number of string (for example, 1 for masculine singular, 2 for feminine singular, etc).

Any reasonable format and separator can be used, as long as it is specified in the answer.

Output the **word preceded by the appropriate form of the article**, with space or single quote as needed. The output should also be lowercase. Trailing or leading blank space is allowed.

Code golf, shortest wins.

# Test cases

In the following I use the input letters `m`, `f` to specify gender, and `s`, `p` for number (this is just one possible input format).

```
Input               Output              Comment

macchina f s        la macchina         Initial letter is cons. A
zio m s             lo zio              Initial letter is cons. B
libri m p           i libri             Initial letter is cons. A
ieri m s            lo ieri             Initial letter is cons. B
aquile f p          le aquile           Initial letter is vowel
spagnoli m p        gli spagnoli        Initial letter is cons. B
golf m s            il golf             Initial letter is cons. A
ombra f s           l'ombra             Initial letter is vowel
impossibili m p     gli impossibili     Initial letter is vowel

```

# Answer
# Retina, ~~138~~ ~~133~~ ~~129~~ 113 bytes

```
^.(s[^aeiou]|z|gn|pn|ps|x|i[aeiou])
B$&
^.[aeiou]
V$&
^\d.
A$&
V[02]
l'
A0
il
B0
lo
A1
i
.1
gli
.2
la
.3
le

```

Test suite. (prepended `%(G`\n` to run all test-cases at once)

Input format: `macchina f s` becomes `2macchina` instead.

```
0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

```

Conversion table thanks to Kevin Lau.
> 7 votes

# Answer
# Python 3.5, ~~238~~ ~~235~~ ~~192~~ ~~181~~ 178 bytes:

(*-13 bytes thanks to tips from Leaky Nun!*)

```
import re;R=re.match;lambda a,b:(R('s[^aeiou]|(z|gn|pn|ps|x|i)[aeiou]',a)and['lo ','gli ','la '][b]or R('[aeiou]',a)and["l'",'gli '][b%2]or['il ','i ','la '][b]if b<3else'le ')+a

```

An anonymous lambda function that takes arguments in the form of `(<String>, <Integer Gender-Plurality mapping>)`, where the mapping is as follows:

```
0 -> Masculine Singular
1 -> Masculine Plural
2 -> Feminine Singular
3 -> Feminine Plural

```

To call it, simply give the function any valid name, and then call it like a normal function wrapped inside a print statement. Therefore, if the question were to be named `U`, simply call it like `print(U(<String>, <Integer Gender-Plurality mapping>))`.

Try It Online! (Ideone)
> 4 votes

# Answer
# Java, ~~227~~ ~~208~~ 195 bytes

*-13 bytes thanks to Leaky Nun*

```
String f(String a,int o){boolean v=a.matches("^([aeou]|i[^aeiou]).*"),b=a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");return(o>1?o>2?"le ":v?"l'":"la ":o>0?v||b?"gli ":"i ":v?"l'":b?"lo ":"il ")+a;}

```

Takes your string and an int based on the following mapping:

```
0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

```

Returns a string with the result.

Ungolfed with test cases and with no ternary operators (for real now):

```
class Test {

    public static String f(String a, int o) {
        boolean v = a.matches("^([aeou]|i[^aeiou]).*");
        boolean b = a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");
        String r;
        if(o > 1)
            if(o > 2)
                r = "le ";
            else
                if(v)
                    r = "l'";
                else
                    r = "la ";
        else
            if(o > 0)
                if(v || b)
                    r = "gli ";
                else
                    r = "i ";
            else
                if(v)
                    r = "l'";
                else if(b)
                    r = "lo ";
                else
                    r = "il ";
        return r + a;
    }

    public static void main(String[] args) {
        System.out.println(f("macchina", 2));
        System.out.println(f("zio", 0));
        System.out.println(f("libri", 1));
        System.out.println(f("ieri", 0));
        System.out.println(f("aquile", 3));
        System.out.println(f("spagnoli", 1));
        System.out.println(f("golf", 0));
        System.out.println(f("ombra", 2));
        System.out.println(f("impossibili", 1));
    }
}

```

Uses a little bit of regex magic and acts depending on the two booleans specified. To my surprise, no imports are needed, which helps out with the code size!
> 4 votes

# Answer
# Ruby, ~~147~~ 146 bytes

Try it online?

It might be possible to use a better method to determine which article to use, but I'm not aware of any.

As per the spec, the identifier is a number, as follows:

```
0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

```

---

```
->w,i{(%w"lo gli la le l' gli l' le il i la le"[(0..2).find{|r|[/^(i[aeiou]|s[^aeiou]|z|x|[gp]n|ps)/,/^[aeiou]/,//][r]=~w}*4+i]+' '+w).sub"' ",?'}

```
> 3 votes

# Answer
## Batch, ~~446~~ ~~390~~ ~~385~~ 380 bytes

```
@echo off
set w=%2
call:l %1 l' gli_ l' le_ il_ i_ la_ le_ lo_ gli_ le_ le_
exit/b
:l
for /l %%a in (0,1,%1)do shift
set o=%5
for %%a in (gn pn ps)do if %%a==%w:~,2% set o=%9
for %%a in (s z x)do if %%a==%w:~,1% set o=%9
for %%a in (a e i o u)do if %%a==%w:~,1% set o=%1
for %%a in (a e i o u)do if i%%a==%w:~,2% (set o=%9)else if s%%a==%w:~,2% set o=%1
echo %o:_= %%w%

```

New version uses the same `0-3` encoding for the gender and number as several other answers. Works by creating a 1-dimensional array `%2` .. `%13` of forms, then shifting out the first `1+%1` elements so that the forms of interest become `%1`, `%5` and `%9` (which is fortunate as Batch won't go above `%9` without shifting). It then laboriously checks the lists of prefixes to find out which form needs to be used. `_` is used as a placeholder to represent a space until the word is output.
> 2 votes

# Answer
# Python 3, 235 bytes

I was interested to see how short I could get this in Python without regexes. It turns out that this is not the best option...

```
lambda s,c,v='aeiou':[["l'",'il','lo'],['gli','i','gli'],["l'",'la','la'],['le']*3][c][[[1,2][s[0]=='s'and s[1]not in v or s[0]in'zx'or s[:2]in['gn','pn','ps']or s[0]=='i'and s[1]in v],0][s[0]in v and not(s[0]=='i'and s[1]in v)]]+' '+s

```

An anonymous function that takes input via argument of the word `s` and the gender-number code `c` as an integer, using the following mapping:

```
0 - Masculine Singular
1 - Masculine Plural
2 - Feminine Singular
3 - Feminine Plural

```

and returns the word with the correct article.

**How it works**

A list containing the possibilities for each `c` as separate lists is created. The list is then indexed into using the value of `c`, yielding a 3-element list with the relevant options. A list index is now chosen by indexing into another nested list with the results of Boolean expressions. If the first character of `s` is a vowel and is not `i` followed by a vowel, the option for `vowel` is yielded via the returning of the index `0`. Else, a Boolean expression returning `True` for `cons. B` and `False` for `cons. A` is evaluated, yielding the indices `2` and `1` respectively. Finally, the index is used to yield the article, which is concatenated with a space and the original string before being returned.

Try it on Ideone
> 1 votes

# Answer
# JavaScript 210 bytes

```
(s,p)=>{var c=i=>!("aeiou".indexOf(s[i])+1),r=["z","gn","pn","ps","x"].some(t=>!s.indexOf(t))||(c(1)?s[0]=="s":s[0]=="i")?2:c(0)?1:0;return (p&1?(p&2?"le ":r&1?"i ":"gli "):!r?"l'":p&2?"la ":r&1?"il ":"lo ")+s}

```

An anonymous function taking two parameters s and p where

```
s  is the input string
p  is plurality (bit 0, set=plural) and gender (bit 1, set=f) combined as
    0 = masculine singular
    1 = masculine plural
    2 = feminine singular
    3 = feminine plural

```

After assigning the function to a variable and some unpacking), it can be tested as

```
var f=(s,p)=>{
    var c = i=>!("aeiou".indexOf(s[i])+1),
        r = ["z","gn","pn","ps","x"].some(t=>!s.indexOf(t))
             || ( c(1)? s[0]=="s":s[0]=="i" )
             ?   2 : c(0) ? 1 : 0;

     return (p&1?(p&2?"le ":r&1?"i ":"gli "):!r?"l'":p&2?"la ":r&1?"il ":"lo ")+s;
}

console.log("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
 f("macchina",2),
 f("zio",0),
 f("libri",1),
 f("ieri", 0),
 f("aquile",3),
 f("spagnoli",1),
 f("golf",0),
 f("ombra",2),
 f("impossibili",1))

```

where

* `c` is a function to test `s` for a consonant at position `i`.
* `r` evaluates to 0 for starting with a vowel, 1 for starting with a type A consonant and 2 for starting with a type B consonant (tested in reverse order).
* Bit bashing in the return statement puts it together.
> 1 votes

---
Tags: code-golf, string, natural-language
---


title: Display a cribbage score in ASCII

text:
# Question
Title: Display a cribbage score in ASCII
Cribbage is an interesting game, because you need a specific board to score your game. A cribbage board looks like this:

Notice how the first column is on the left as it goes up, then on the right as it goes down, then back on the left as it goes up again.

And here is what a poorly ~~drawn~~ rendered ASCII art of a cribbage board looks like:

```
                     * * *
   -----------      -------
  /     *     \     |*|*|*|
 /*     *     *\    |*|*|*|
/   *   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 * * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------

```

Here is your challenge:

Step 1: Draw this ASCII art of a cribbage board. Trailing whitespace is OK, provided that there is no visible difference.

Step 2: Given three integers as input, display each peg in the correct hole. The pegs can be 0-indexed or 1-indexed. The inputs will be in `[0-121]` inclusive. You can take these inputs in any reasonable manner, for example, 3 separate inputs, an array, command line arguments, etc. Here's an example for the input `(0, 37, 100)` (1-indexed):

```
                     * * *
   -----------      -------
  /     *     \     |*|*|*|
 /*     *     *\    |*|*|*|
/   2   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|3|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 1 * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------

```

Step 3: Output the whole thing.

# Test IO:

Since each of these is pretty vertically tall, I will only include 2, but you can see more at this github gist.

```
#Input: (56, 56, 56)
#Output:
                     * * *
   -----------      -------
  /     *     \     |*|*|*|
 /*     *     *\    |*|*|*|
/   *   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |3|2|1|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 * * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------

#Input: (120, 89, 23)
#Output:
                     * * *
   -----------      -------
  /     *     \     |1|*|*|
 /*     *     *\    |*|*|*|
/   *   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|3|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|2|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 * * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------

```

Standard loopholes apply, and the shortest answer in bytes wins!

# Answer
# Python 3, 496 bytes

```
z=r"""SSSWT
WOSY
  /UR\UZ
 /RR*\W Z
/WQQQ\WZ
MWZ
NWZVVVVVVV
YWYWY
 TW NPW MPW \WQQQ/PU\RR*/ PS\UR/PS O"""
for y in'M|UQR|,N|TUT|,OY----,P\nS,Q*W,R*U,SWW,T* * *,UW  ,V\nYWYWYXXXXX,W   ,X\nZ   Z   Z,Y-------,Z|*|*|*|'.split(','):z=z.replace(y[0],y[1:])
L=list(range(50,-1,-1))
del L[1::6]
def f(*s):
 b=list(z)
 for p in(0,1,2):b[(L[:-5]+[3+p,2+p,3+p]+L[-6::-1]+[51+p,52+p,51+p]+L)[s[p]]*28+([2*p+1]*37+[2+2*p,8,14-2*p]+[15-2*p]*37+[16-2*p,18,20+2*p]+[21+2*p]*42)[s[p]]]=str(p+1)
 print(*b,sep='')

```

Running (or importing) the code creates a function that is called with the three players scores: `f(5, 38, 53)`.

**Somewhat ungolfed version**

```
z=r"""SSSWT
WOSY
  /UR\UZ
 /RR*\W Z
/WQQQ\WZ
MWZ
NWZVVVVVVV
YWYWY
 TW NPW MPW \WQQQ/PU\RR*/ PS\UR/PS O"""

subs='M|UQR|,N|TUT|,OY----,P\nS,Q*W,R*U,SWW,T* * *,UW  ,V\nYWYWYXXXXX,W   ,X\nZ   Z   Z,Y-------,Z|*|*|*|'

for y in subs.split(','):
   z=z.replace(y[0],y[1:])

L=list(range(50,-1,-1))
del L[1::6]

def f(*s):
 b=list(z)
 for p in(0,1,2):
  R = L[:-5] + [3+p,2+p,3+p] + L[-6::-1] + [51+p,52+p,51+p] + L
  C = [2*p+1]*37 + [2+2*p,8,14-2*p] + [15-2*p]*37 + [16-2*p,18,20+2*p] + [21+2*p]*42
  b[R[s[p]]*28+C[s[p]]] = str(p)

 print(*b,sep='')

```

`z` is a coded/compressed version of the empty cribbage board.

`subs` contains a comma separated list of substitutions to decode/uncompress `z`. In each substitution, the first letter is the substring to replace and the remainder of the string is the replacement. The `for y in subs.split(','):` loop does the substitutions. For example, `Z|*|*|*|` causes all 'Z's to be replaced by `|*|*|*|`. The compression method was used for its simplicity and effectiveness (its better than the stdlib). But it could probably be improved or replaced with something better.

Because, Python strings are immutable, `b` is a list of the characters in the game board.

`R` is a list mapping a player and score to a row in the ascii game board. It uses 'L', which is a list or row numbers from which row numbers corresponding to '-------'-rows have been deleted.

Similarly, `C` maps a player and score to a column in the ascii game board.

Using `R` and `C`, the proper peg hole in the game board can be set to the player's number.

Lastly, `print(*b,sep='')` prints each character in `b` without inserting a space between adjacent characters. (Saves a few bytes over using ''.join)
> 4 votes

# Answer
# Matricks, ~~1441~~ 980 bytes

Hooray for esolangs!

Edit: compressed checking each number into a loop to save a ton of bytes. Also made the bottom part "copy" the top (I need a reverse function). I also replaced most ascii characters with their raw values to save a few more. Also, I fixed a bug in the interpreter where number input wasn't working right.

```
a45;u[m"|;:5:1;];a[a45;u[m42:5:1;];];a{};a{};z:1;a[m32:6:1;a{a{};};];a{a{};};u{};u{};u{};z5:;v[mic%2:42:32;:1:17;s::"|;;s:16:"|;;s:7:32;s:9:32;v[m32:4:7;s1:2:42;s2:4:42;s3:6:42;a[mi(re3)&(c=1):42:32;:4:3;];a[m32:4:7;s3::42;s2:2:42;s1:4:42;];];s3::"|;;s3:16:"|;;s2::47;s1:1:47;s:2:47;s2:16:92;s1:15:92;s:14:92;v[mi(cT3)&(cE13)&(r=1):45:32;:2:17;];a[m32:7:3;];a[a45;u[m"|;:5:1;];a[a45;u[m42:5:1;];];a{};a{};z:1;v[mic%2:42:32;:1:7;];];];u{z43:10;q1:;u{q5:;};u{q4:;z2:;};u{q3:;z4:;};u{q2:;z6:;};u{q1:;z8:;};u{z10:;};q6:;s2::92;s3:1:92;s4:2:92;s2:16:47;s3:15:47;s4:14:47;b[mi(c%2)&(ce6):42:32;:1:10;];};s:1:48;s:2:-1;j1;
s:1:g:1;+1;s:2:g:2;+1;s::n;;ig:;E36:s(40-g:;)*1.2+2:1+g:2;*2:g:1;;:ig:;T80:s(120-g:;)*1.2+2:21+g:2;*2:g:1;;:i(g:;E76)&(g:;T40):s(g:;-31)*1.2-4:15-g:2;*2:g:1;;:ig:;=37:s3+g:2;:2+g:2;*2:g:1;;:ig:;=38:s2+g:2;:8:g:1;;:ig:;=39:s3+g:2;:14-g:2;*2:g:1;;:ig:;=77:s51+g:2;:16-g:2;*2:g:1;;:ig:;=78:s52+g:2;:18:g:1;;:s51+g:2;:20+g:2;*2:g:1;;;;;;;;;;ig:2;e2:j1;:s::;s:1:;;s:2:;

```

Takes input on command line: `python matricks.py <filename> [[]] <num1>,<num2>,<num3> --asciiprint`

Matricks is a language of my own creation. Documentation is on the Github page. The most recent update was a bugfix, no new features added or anything.

Breakdown of this solution:

1. First block created
2. Block copied to fill entire board
3. Top curve
4. Bottom curve
5. Checking the placement of each number
> 5 votes

# Answer
# Python 2, 615 bytes

```
def f(a):
 D="-";S=" ";A=S*55+D+S;B="|/4 /41/4 - 2  -4-3   -|/4 /43/4 - 2  -4-1   -".replace("4","    ");C=B.replace("/","\\");s=t=u="";d={"1":0,"2":0,"3":0}
 for i in range(23):j=15>i>7;k=i-i/8;x=k%7*5;y=(6-k%7)*5;M=A+S*52+("123","321")[i<8]+D+S+A;N=chr((x,y)[j]/10+49);Q=("|"+N)[i%2]*5+D;s+=(S+S*5*(i<7)+C[x+39:x+34:-1]*j+B[y+39:y+34:-1]*(i>15)+("| "[i<7]+N)[i%2]+D+Q*(7+(i>15))+("|"+N)[i%2]+B[x:x+5]*(i<7)+C[y:y+5]*j+S*(i<16),(M[::-1],M)[i<8])[i%8==7]
 for x in s:
    if "4">x>"0":d[x]+=1;x=("*"+x)[d[x]==a[x]+1]
    t+=x
 for i in range(1512):j=i/27;k=i%27;u+=t[k*57+(56-j,j)[16>k>10and 51>j>5]]+"\n"*(k>25)
 print u

```

The function is called by passing in a dictionary that contains the scores. For example:

```
f({"1":40, "2":70, "3":76})

```

The byte count reflects indenting the "for x" loop with tabs instead of spaces.

**Explanation**

The first loop builds the board horizontally into a 57x27 string, with track numbers instead of "holes".

```
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-||/
      1-11111-11111-11111-11111-11111-11111-11111-1  /
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-|  1/
      2-22222-22222-22222-22222-22222-22222-22222-2    -
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 2  -
      3-33333-33333-33333-33333-33333-33333-33333-3    -
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-|3   -
                                                       -
                                                    321-
                                                       -
    \||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|3   -
   \  3-33333-33333-33333-33333-33333-33333-33333-3    -
  \3  |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 2  -
 -    2-22222-22222-22222-22222-22222-22222-22222-2    -
 -  2 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|  1\
 -    1-11111-11111-11111-11111-11111-11111-11111-1  \
 -   1|-|||||-|||||-|||||-|||||-|||||-|||||-|||||-||\
 -
 -321
 -
 -   1|-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|
 -    1-11111-11111-11111-11111-11111-11111-11111-11111-1
 -  2 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|
 -    2-22222-22222-22222-22222-22222-22222-22222-22222-2
  /3  |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|
   /  3-33333-33333-33333-33333-33333-33333-33333-33333-3
    /||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|

```

The second loop copies the string, replacing the numbers with asterisks except at the scoring peg locations. The peg locations in the straight lines in the middle of the track come out backward.

The third loop changes the orientation to vertical, correcting the pegs in the middle track and adding newline characters.

Try it here
> 4 votes

# Answer
## Batch, ~~1302~~ ~~1099~~ ~~1096~~ 1079 bytes

```
@set s= set
@%s%o=echo
@%o%off
%s%x=41
%s%y=35
%s%z=121
%s%m=-------
%s%w=
%s%p=if %1==
%s%q=if %2==
%s%r=if %3==
%s%l=call:l
%l%
%o%%w%%w%%w%%w% %g% %h% %i%
%o%   %m%---- %w%%m%
%l%
%p%38%s%j=1
%o%  /%w%%j%%w%\  %n%
%l%
%q%38%s%j=2
%o% /%f%%w%%j%%w%%a%\ %n%
%l%
%q%37%s%j=2
%q%39%s%k=2
%o%/   %j%   %c%   %k%   \%n%
%l%
%o%^|%w%%c%   %d%%w%^|%n%
%l%
%o%^|%a% %b% %c%%w%%d% %e% %f%^|%n%
%l%
for /l %%a in (1,1,7)do call:b
%o%%m%   %m%   %m%
%o% %a% %b% %c%    ^|%d% %e% %f%%w%%g% %h% %i%^|
%l%
%o%%w%%w%^|%w%%f%   %g%%w%^|
%l%
%q%77%s%j=2
%q%79%s%k=2
%o%%w%%w%\   %j%   %g%   %k%   /
%l%
%q%78%s%j=2
%o%%w%%w% \%i%%w%%j%%w%%d%/
%r%78%s%j=3
%o%%w%%w%  \%w%%j%%w%/
%o%%w%%w%   %m%----
exit/b
:b
%o%%m%   %m%   %m%
for /l %%a in (1,1,4)do call:o
:o
%o%^|%a%^|%b%^|%c%^|   ^|%d%^|%e%^|%f%^|%n%
:l
for %%a in (a b c d e f g h i j k) do%s%%%a=*
%p%%x%%s%a=1
%q%%x%%s%b=2
%r%%x%%s%c=3
%r%%y%%s%d=3
%q%%y%%s%e=2
%p%%y%%s%f=1
%p%%z%%s%g=1
%q%%z%%s%h=2
%r%%z%%s%i=3
%s%n=   ^^^|%g%^^^|%h%^^^|%i%^^^|
set/ax-=1,y+=1,z-=1

```

Ungolfed:

```
@echo off
@rem values that pegs at the very top of each column would be
set x=41
set y=35
set z=121
rem deal with the four custom pegs on the top curve
call :loop
echo                      %g% %h% %i%
echo    -----------      -------
call :loop
if %1==38 (set j=1) else set j=*
echo   /     %j%     \     ^|%g%^|%h%^|%i%^|
call :loop
if %2==38 (set j=2) else set j=*
echo  /%f%     %j%     %a%\    ^|%g%^|%h%^|%i%^|
call :loop
if %2==37 (set j=2) else set j=*
if %2==39 (set k=2) else set k=*
echo /   %j%   %c%   %k%   \   ^|%g%^|%h%^|%i%^|
call :loop
echo ^|     %c%   %d%     ^|   ^|%g%^|%h%^|%i%^|
call :loop
echo ^|%a% %b% %c%     %d% %e% %f%^|   ^|%g%^|%h%^|%i%^|
call :loop
rem deal with the 7 sets of 5 standard rows
call :block
call :block
call :block
call :block
call :block
call :block
call :block
rem deal with the four custom pegs on the bottom curve
echo -------   -------   -------
echo  %a% %b% %c%    ^|%d% %e% %f%     %g% %h% %i%^|
call :loop
echo           ^|     %f%   %g%     ^|
call :loop
if %2==77 (set j=2) else set j=*
if %2==79 (set k=2) else set k=*
echo           \   %j%   %g%   %k%   /
call :loop
if %2==78 (set j=2) else set j=*
echo            \%i%     %j%     %d%/
if %3==78 (set j=3) else set j=*
echo             \     %j%     /
echo              -----------
exit/b
:block
echo -------   -------   -------
call :output
call :output
call :output
call :output
:output
rem prints each of the 35 main rows
echo ^|%a%^|%b%^|%c%^|   ^|%d%^|%e%^|%f%^|   ^|%g%^|%h%^|%i%^|
:loop
rem check for pegs in the current row, also works for some of the curve
if %1==%x% (set a=1) else set a=*
if %2==%x% (set b=2) else set b=*
if %3==%x% (set c=3) else set c=*
if %3==%y% (set d=3) else set d=*
if %2==%y% (set e=2) else set e=*
if %1==%y% (set f=1) else set f=*
if %1==%z% (set g=1) else set g=*
if %2==%z% (set h=2) else set h=*
if %3==%z% (set i=3) else set i=*
rem decrement the first and third columns, increment the second column
set/a x-=1
set/a y+=1
set/a z-=1

```
> 4 votes

# Answer
# Java, ~~1059~~ 1035 bytes

```
class C{static int[]i=new int[3];String d="-------",l=d+"----";<T>void p(String s,T...o){System.out.format(s+"\n",o);}C(){p("%26s\n%14s%13s\n  /%6s     \\%15s\n /%s%6s%6s\\%14s\n/%4s%4s%4s   \\%13s\n|%6s%4s     |%13s\n|%s%10s|%13s",o(121,0),l,d,s(38,0),t(120,0),s(37,0),s(38,1),s(39,0),t(119,0),s(37,1),s(38,2),s(39,1),t(118,0),s(37,2),s(39,2),t(117,0),o(36,0),o(40,2),t(116,0));for(int j=0;j<7;)g(j++*5);d();p(" %s    |%s%10s|\n%11s%6s%4s     |\n%11s%4s%4s%4s   /\n%12s%s%6s%6s/\n%13s%6s     /\n%24s",o(0,0),o(76,2),o(80,0),"|",s(77,0),s(79,0),"\\",s(77,1),s(78,0),s(79, 1),"\\",s(77,2),s(78,1),s(79,2),"\\",s(78,2),l);}String s(int r,int c){return r==i[c]?c+"":"*";}String t(int r,int d){return l.format("|%s|%s|%s|   ",s(r,d),s(r,1),s(r,2-d));}void r(int r){p(t(35-r,0)+t(41+r,2)+t(115-r,0));}void d(){p(d+"%10s%10s",d,d);}void g(int r){d();for(int j=0;j<5;)r(r+j++);}String o(int r,int d){return l.format("%s %s %s",s(r,d),s(r,1),s(r,2-d));}public static void main(String[]a){for(int j=0;j<3;)i[j]=Integer.decode(a[j++]);new C();}}

```

Ungolfed:

```
class Crib {

    static int[] input = new int[3];
    String divider = "-------", longDivider = divider + "----";

    <T> void p(String s, T...o) {
        System.out.format(s+"\n",o);
    }

    Crib() {

        p("%26s", troika(121,0));
        p("%14s%13s", longDivider, divider);
        p("  /%6s     \\%15s", star(38,0), trio(120,0));
        p(" /%s%6s%6s\\%14s", star(37,0), star(38,1), star(39,0), trio(119,0));
        p("/%4s%4s%4s   \\%13s", star(37,1), star(38,2), star(39,1), trio(118,0));
        p("|%6s%4s     |%13s", star(37,2), star(39,2), trio(117,0));
        p("|%s%10s|%13s", troika(36,0), troika(40,2), trio(116,0));
        for(int i = 0; i < 7;)
            group(i++*5);
        printDivider();
        p(" %s    |%s%10s|", troika(0,0), troika(76,2), troika(80,0));
        p("%11s%6s%4s     |", "|", star(77,0), star(79,0));
        p("%11s%4s%4s%4s   /", "\\", star(77,1), star(78,0), star(79, 1));
        p("%12s%s%6s%6s/", "\\", star(77,2), star(78,1), star(79,2));
        p("%13s%6s     /", "\\", star(78,2));
        p("%24s", longDivider);
    }

    String star(int row, int cell) {
        return row == input[cell] ? cell+"" : "*";
    }

    String trio(int row, int diff) {
        return longDivider.format("|%s|%s|%s|   ", star(row, diff), star(row, 1), star(row, 2-diff));
    }

    void printRow(int row) {
        p(trio(35-row, 0) + trio(41+row, 2) + trio(115-row, 0));
    }

    void printDivider() {
        p(divider + "%10s%10s", divider, divider);
    }

    void group(int row) {
        printDivider();
        for(int i = 0; i < 5;)
            printRow(row+i++);
    }

    String troika(int row, int diff) {
        return longDivider.format("%s %s %s", star(row, diff), star(row, 1), star(row, 2-diff));
    }

    public static void main(String[] args) {
        for(int i = 0; i < 3;)
            input[i] = Integer.decode(args[i++]);
        new Crib();
    }
}

```

Abuses formats (printfs) like mad, which is probably why it's not as small as it could be.
> 2 votes

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


title: Recognize mod-folds

text:
# Question
Title: Recognize mod-folds
# Task

Define a *mod-fold* as a function of the form **f(x) = x % a1 % a2 % … % ak**, where the **ai** are positive integers and **k ≥ 0**. (Here, **%** is the left-associative modulo operator.)

Given a list of **n** integers **y0, …, yn−1**, determine if there exists a mod-fold **f** so that each **yi = f(i)**.

You may choose and fix **any two outputs** *Y* and *N* for your function/program. If there exists such an **f**, you must always return/print exactly *Y*; if not, you must always return/print exactly *N*. (These could be `true`/`false`, or `1`/`0`, or `false`/`true`, etc.) Mention these in your answer.

The shortest submission in bytes wins.

# Example

Define **f(x) = x % 7 % 3**. Its values start:

```
|   x  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ...
| f(x) | 0 | 1 | 2 | 0 | 1 | 2 | 0 | 0 | 1 | 2 | ...

```

Thus, given `0 1 2 0 1 2 0 0 1 2` as input to our solution, we would print *Y*, as this **f** generates that sequence. However, given `0 1 0 1 2` as input, we would print *N*, as no **f** generates that sequence.

# Test cases

The formulas given when the output is *Y* are just for reference; you must at no point print them.

```
0 1 2 3 4 5              Y    (x)
1                        N
0 0 0                    Y    (x%1)
0 1 2 0 1 2 0 0 1 2      Y    (x%7%3)
0 0 1                    N
0 1 2 3 4 5 6 0 0 1 2    Y    (x%8%7)
0 1 2 0 1 2 0 1 2 3      N
0 2 1 0 2 1 0 2 1        N
0 1 0 0 0 1 0 0 0 0 1    Y    (x%9%4%3%2)

```

# Answer
> 7 votes
# Pyth, 14 bytes

```
}Qm%M+RdUQy_Sl

```

Returns `True/False`. Try it online: Demonstration or Test Suite

### Explanation:

```
}Qm%M+RdUQy_SlQ   implicit Q (=input) at the end
             lQ   length of input list
            S     create the list [1, 2, ..., len]
           _      reverse => [len, ..., 2, 1]
          y       generate all subsets (these are all possible mod-folds)
  m               map each subset d to:
        UQ           take the range [0, 1, ..., len-1]
     +Rd             transform each number into a list by prepending it to d
                     e.g. if mod-fold = [7,3], than it creates:
                        [[0,7,3], [1,7,3], [2,7,3], [3,7,3], ...]
   %M                fold each list by the modulo operator
                  this gives all possible truthy sequences of length len
}Q                so checking if Q appears in the list returns True or False

```

# Pyth, 11 bytes

```
q%M.e+k_tx0

```

Based on @ferrsum's idea. I actually thought about using the zero-indices for the subset generation, but didn't realize, that all zero-indices has to be the solution already.

# Answer
> 4 votes
# Python 3, ~~239~~ 218 bytes

```
from itertools import*
lambda z:z in[[eval(''.join([str(l)]+['%'+str(i[::-1][k])for k in range(len(i))]))for l in range(len(z))]for i in(i for j in(combinations(range(1,len(z)+1),i+1)for i in range(len(z)))for i in j)]

```

An anonymous function that takes input of a list `z` and returns `True` or `False` for `Y` and `N`.

This uses a method similar to @Jakube 's answer, and although it is essentially a brute force, runs very quickly.

```
from itertools import*               Import everything from the Python module for
                                     iterable generation
lambda z                             Anonymous function with input list z
combinations(range(1,len(z)+1),i+1)  Yield all sorted i+1 length subsets of the range
                                     [1,len(z)]...
...for i in range(len(z))            ...for all possible subset lengths
(i for j in(...)for i in j)          Flatten, yielding an iterator containing all possible
                                     mod-fold values as separate lists
...for i in...                       For all possible mod-fold values...
...for k in range(len(i))            ...for all mod-fold values indices k...
...for l in range(len(z))            ...for all function domain values in [0,len(z)-1]...
[str(l)]+['%'+str(i[::-1][k])...]    ...create a list containing each character of the
                                     expression representing the function defined by the
                                     mod-fold values (reversed such that the divisors
                                     decrease in magnitude) applied to the domain value...
 eval(''.join(...))                  ...concatenate to string and evaluate...
 [...]                               ...and pack all the values for that particular
                                     function as a list
 [...]                               Pack all lists representing all functions into a list
 ...:z in...                         If z is in this list, it must be a valid mod-fold, so
                                     return True. Else, return False

```

Try it on Ideone

# Answer
> 4 votes
# Python 2, 69 bytes

```
f=lambda a,i=0:i/len(a)or a[i]in[a[i-1]+1,i,0][i<=max(a)::2]*f(a,i+1)

```

Uses `True`/`False`.

The answer to what characterizes a mod-foldable series turns out to be less interesting than it seems at first. It is a series of the form 0, 1, ..., M - 1, 0, 1, ... x1, 0, 1, ..., x2, ... such that for all i, 0 \<= xi \< M. Such a sequence can be produced by the mod chain of all the (0-based) indices of the zeroes in the array, excluding the first.

# Answer
> 3 votes
# Jelly, ~~19~~ ~~15~~ 14 bytes

```
LṗLUZ’1¦%/sLe@

```

Returns **1** for truthy, **0** for falsy. Try it online!

The algorithm is **O(nn)**, where **n** is the length of the list, making it too slow and memory-intensive for most of the test cases.

A modified version – which replaces the second `L` with a `5` – can be used to verify all test cases. Note that this modified version won't work for arbitrarily long lists.

### How it works

```
LṗLUZ’1¦%/sLe@  Main link. Argument: A (array of integers)

L L             Yield the length l of A.
 ṗ              Take the l-th Cartesian power of [1, ..., l], i.e., construct
                all arrays of length l that consist of elements of [1, ..., l].
   U            Upend/reverse each array. This way, the first l arrays start
                with [1, ..., l], as do the next l arrays, etc.
    Z           Zip/transpose the array of arrays.
     ’1¦        Decrement the first array to map [1, ..., l] to [0, ..., l - 1].
        %/      Reduce the array's columns by modulus/residue.
          sL    Split the result into chunks of length l.
            e@  Verify if A belongs to the resulting array.

```

# Answer
> 3 votes
## JavaScript (ES6), ~~98~~ bytes

```
a=>a.every((n,i)=>n?n<(l+=p==i)&&n==p++:p=1,l=p=1)

```

Saved 48 bytes by switching to @Feersum's discovery. Any given value `n` in the array is either zero, in which case the next prediction `p` is 1, or it equals the next prediction, in which case `p` is incremented. We also measure the length `l` of the initial sequence by comparing `p` to `i`, as `n` must always be less than `l` at all times.

# Answer
> 2 votes
# Python 2, ~~103~~ 99 bytes

```
f=lambda l,r:r==x or l and f(l-1,[t%l for t in r])|f(l-1,r)
x=input();l=len(x);print+f(l,range(l))

```

Prints **1** for truthy and **0** for falsy. Test it on Ideone.

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