title: Euro coins and notes

text:
# Question
Title: Euro coins and notes
As the majority of nations using the Euro have the `,` as the decimal separator, you must use it also.

The task is to output all the values of the Euro coins and notes in ascending order. You must also put the trailing `,00` on the integer values.

`0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00`

I accept both output to stdout or a function returning an array/list. If output is to stdout, the acceptable separators between values are: space, tab, or newline.

There will be no accepted answer, unless I see some one I find very creative.

, so I want to know shortest answer by language.

# Update:

Leading `0` zeros are not acceptable. Sorry, I should make it clear before.

# Update 2:

It is also acceptable a function returning a string.

# Answer
# Pure Bash, 48

```
s={1,2,5}
eval echo 0,0$s 0,${s}0 ${s}{,0,00},00

```

Try it online.
> 27 votes

# Answer
# Japt, ~~23~~ 22 bytes

*-1 byte thanks to @Shaggy*

```
5Æ#}ì ®eX-2 x2 d".,"
c

```

Returns an array of strings.

Try it online! with the `-R` flag to output array items on separate lines.
> 7 votes

# Answer
# Python 2, 72 bytes

```
print[('%.2f'%(10**(x/3-2)*(5>>~x%3))).replace(*'.,')for x in range(15)]

```

Try it online!

The expression `5>>~x%3` maps the non-negative integers to `1`, `2`, `5`, `1`, `2`, `5`

It works because `5`, `2`, `1` are the successive right-bitshifts of `5` (`0b101``0b10``0b1`); we cycle through them backwards.
> 7 votes

# Answer
# SOGLOnline offline, ~~27~~ ~~26~~ ~~25~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes

```
252¹5∙īυ;{⁴Ζ.,ŗP*F⁾?½

```

Try it Here!

The online link doesn't show trailing zeroes, but the offline version does as Javas BigDecimals are nice.

Explanation:

```
252¹5∙īυ;{⁴Ζ.,ŗP*F⁾?½
252¹                 push the array [2, 5, 2]
    5∙               multiply vertically by 5
      īυ;            push 0.01 below that - the main number
         {           iterate over that array - [2,5,2,2,5,2,2,5,2,2,5,2,2,5,2]
          ⁴            duplicate the main number
           Ζ.,ŗ        replace "." with ","
               P       output in a new line
                *      multiply the main number with the current item of the array
                 F⁾?   if the current array item-2 isn't 0, then
                    ½    divide by 2

```

TO run in the offline interpreter, download SOGLOnlines repository, go to compiler/interpreter, open any of the `.pde` files with Processing, then do file -\> export for your OS (otherwise you can't give arguments to a Processing program :/), and then execute the compiled program with an argument to the path of the file with the code. Then, stdout will contain this.

`2L¼2¹5∙īυ;{⁴Ζ.,ŗP*` for 18 bytes almost works but the zero amount grows, resulting in `0,01 0,02 0,050 0,100 0,200 0,5000 1,0000 2,0000 5,00000 10,00000 20,00000 50,000000 100,000000 200,000000 500,0000000` (newlines replaced with spaces)
> 6 votes

# Answer
# Java 8, ~~109~~ ~~108~~ ~~81~~ 80 bytes

Thanks to @OlivierGrégoire for the Locale idea

```
x->{for(double i=.001;i<11;)System.out.printf("%.2f %.2f %.2f ",i*=10,i*2,5*i);}

```

Try it online!
> 6 votes

# Answer
# Charcoal, 36 bytes

```
ＥＥ×125⁵⁺⁺×0⁻²÷κ³ι×0÷κ³⁺⁺✂ι⁰±²¦¹,✂ι±²

```

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

```
   125                                  String `125`
  ×   ⁵                                 Repeated 5 times
 Ｅ                                      Map over each character
              ÷κ³   ÷κ³                 Integer divide loop index by 3
            ⁻²                          Subtract from 2
          ×0      ×0                    Repeat the string `0` x times
        ⁺⁺       ι                      Concatenate with the character
Ｅ                                       Map over each resulting string
                         ✂ι⁰±²¦¹        Slice off the last two digits
                                ✂ι±²    Extract the last two digits
                       ⁺⁺       ,       Concatenate with a comma
                                        Implicitly print one per line

```
> 6 votes

# Answer
# APL (Dyalog), ~~30~~ 28 bytes

Complete program. Outputs to space-separated to STDOUT.

```
'\.'⎕R','⊢2⍕×\.01,14⍴2 2.5 2

```

Try it online!

`2 2.5 2` the list;
`[2,2.5,2]`

`14⍴` cyclically **r**eshape to length 14;
`[2,2.5,2,2,2.5,2,2,2.5,2,2,2.5,2,2,2.5]`

`.01` prepend 0.01;
`[0.01,2,2.5,2,2,2.5,2,2,2.5,2,2,2.5,2,2,2.5]`

`×\` cumulative multiplication;
`[0.01,0.02,0.05,0.1,0.2,0.5,1,2,5,10,20,50,100,200,500]`

`2⍕` format with two decimals;
`" 0.01 0.02 0.05 0.10 0.20 0.50 1.00 2.00 5.00 10.00 20.00 50.00 100.00 200.00 500.00"`

yield that (to separate `','` from `2`)

`'\.'⎕R','` PCRE **R**eplace periods with commas;
`" 0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00"`
> 5 votes

# Answer
# Bash, 38 bytes

```
printf %.2f\\n {1,2,5}e{-2..2}|sort -h

```

Requires an appropriate locale, which is allowed by default and costs no bytes.

Try it online!
> 5 votes

# Answer
# R ~~70~~, 50 bytes

inspired by @Giuseppe:

```
format(c(1,2,5)*10^rep(-2:2,e=3),ns=2,de=",",sc=F)

```

Try it here!

Ungolfed

```
format(c(1,2,5)*10^rep(-2:2, each = 3),
   nsmall = 2,
   decimal.mark = ",",
   scientific = FALSE)

```
> 4 votes

# Answer
# Python 2, ~~80~~ ~~77~~ ~~75~~ 73 bytes

*-2 bytes thanks to @Mr.Xcoder*
*-1 byte thanks to @EriktheOutgolfer*
*-2 bytes thanks to @totallyhuman*
*-2 bytes thanks to @Lynn*

```
print[('%.2f'%(v*m)).replace(*'.,')for m in.01,.1,1,10,100for v in 1,2,5]

```

Try it online!
> 3 votes

# Answer
# Pyth, 37 bytes

```
smmX%"%.2f"*dk\.\,[1 2 5)[.01.1 1T^T2

```

Try it online!

# Pyth, 37 bytes

Will shorten in a few minutes.

```
V[.01.1 1T^T2)V[1 2 5)X%"%.2f"*NH\.\,

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 83 bytes

Returns an array.

```
_=>[...'125'.repeat(k=5)].map(c=>(c*(c-1?k:k*=10)/5e3).toFixed(2).split`.`.join`,`)

```

### Demo

```
let f =

_=>[...'125'.repeat(k=5)].map(c=>(c*(c-1?k:k*=10)/5e3).toFixed(2).split`.`.join`,`)

console.log(f())
```

---

# Recursive version (ES7), 84 bytes

Returns a string with a trailing space.

```
f=(i=0)=>i<15?('125'[i%3]/100*10**(i/3|0)).toFixed(2).split`.`.join`,`+' '+f(i+1):''

```

### Demo

```
f=(i=0)=>i<15?('125'[i%3]/100*10**(i/3|0)).toFixed(2).split`.`.join`,`+' '+f(i+1):''

console.log(f())
```
> 3 votes

# Answer
# Retina, 42 bytes

```

5$*0
0
$'1$`¶$'2$`¶$'5$`¶
..¶
,$&
m`^00?

```

Try it online! Explanation: There are fifteen values, with 1, 2 and 5 in each of five places. The first stage inserts five 0s. The second stage repeats them into a square, then changes the trailing diagonal into 1s, then duplicates those lines three times with 2 and 5. The third stage inserts the commas and the last stage removes unnecessary leading zeros.
> 2 votes

# Answer
# Charcoal, 37 bytes

```
”{➙∧N\`�4✳×″↶tι⦄|Ｑ~(↥↗⁻“Ｑ§U‴w⎇δUη◨÷¤Ｇ”

```

Try it online! Link is to verbose version.

Yay, compression!
> 1 votes

# Answer
# Bash, 88 bytes

```
s=125
for i in {0..14};{ printf %1.2f\  `bc<<<"scale=2;${s:i%3:1}*10^$[i/3-2]"`|tr . ,;}

```

Try it online!
> 1 votes

# Answer
## C++, ~~138~~ 120 bytes

-18 bytes thanks to MSalters

```
#include<iostream>
void p(){for(auto&a:{"0,0%d ","0,%d0 ","%d,00 ","%d0,00 ","%d00,00 "})for(int b:{1,2,5})printf(a,b);}

```

**Hardcoded version, by Lynn, 116 bytes**

```
#include<ios>
void p(){puts("0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00");}

```
> 1 votes

# Answer
# JavaScript (ES6), 81 bytes

Returns an array.

```
_=>[...Array(13),b=.005,i=0].map(p=>(b*=++i%3?2:2.5).toFixed(2).replace(".",","))

```

### Demo

```
let f =

_=>[...Array(13),b=.005,i=0].map(p=>(b*=++i%3?2:2.5).toFixed(2).replace(".",","))

console.log(f())
```

---
> 1 votes

# Answer
# , ~~70~~ 61 bytes

```
options(scipen=9,OutDec=",")
print(c(1,2,5)*10^rep(-2:2,e=3))

```

Try it online!

*-9 bytes thanks to Rui Barradas*

Outgolfed by AndriusZ
> 1 votes

# Answer
# Common Lisp, 95 bytes

```
(dotimes(i 5)(dolist(j'(1 2 5))(princ(substitute #\, #\.(format()"~$ "(*(expt 10(- i 2))j))))))

```

Try it online!
> 1 votes

# Answer
# Husk, 28 bytes

```
ṁm↔ṪöJ',CtN`J§¤eR'0≥≤2ḣ5"125

```

Try it online!

Just string manipulation, since Husk is terrible at formatting floating point numbers.

## Explanation

```
ṁm↔ṪöJ',CtN`J§¤eR'0≥≤2ḣ5"125
                        "125  The string "125".
                      ḣ5      The range [1,2,3,4,5].
   Ṫö                         Compute their outer product wrt this function:
                               Arguments are number n (say 3) and character c (say '5').
             §     ≥≤2         Compute max(0,n-2+1) and max(0,2-n+1),
                R'0            repeat '0' those numbers of times,
              ¤e               and put them into a list: ["00",""]
           `J                  Join with c: "005"
        CtN                    Split to lengths 2 and at most 3: ["00","5"]
     J',                       Join with ',': "00,5"
                              This gives a 2D array of the outputs reversed.
ṁ                             Map and concatenate
 m↔                           map reversal.
                              Implicitly print separated by newlines.

```
> 1 votes

# Answer
# C (gcc), 82 bytes

```
p(n){printf("%d,%02d ",n/100,n%100);}f(n){for(n=1;n<5e4;n*=10)p(n),p(n*2),p(n*5);}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 25 bytes

```
125S5иεN3÷°*т/'.',:N2›i0«

```

Returns a list of strings.

Try it online.

**Explanation:**

```
125                          # Push 125
   S                         # Split to a list of digits: [1,2,5]
    5и                       # Repeat it 5 times: [1,2,5,1,2,5,1,2,5,1,2,5,1,2,5]
      ε                      # Map each to:
       N3÷                   #  Integer-divide the map-index by 3
          °                  #  Take it to the power 10
           *                 #  Multiply the current map number with it
            т/               #  Divide it by 100
              '.',:          #  Replace all "." with ","
                   N2›i      #  And if the map-index is larger than 2:
                       0«    #   Append a "0"

```

`125S5и` could be `•}•15∍` (push compressed `125`; enlarge it to size 15: `125125125125125`) and `'.',:` could be `„.,`:` (push string ".,", pop and push the characters as separated items to the stack) for the same byte-count: Try it online.
Also, `N3÷°*т/` can be shortened to `N3÷Í°*` (where `Í` subtracts 2), but unfortunately we need the `/` so all the numbers becomes decimals, whereas with `N3÷Í°*` most numbers will remain integers.
> 1 votes

# Answer
# T-SQL, 104 bytes

```
SELECT FORMAT(p*n,'0\,00')
FROM(VALUES(1),(2),(5))a(n),(VALUES(1),(10),(100),(1E3),(1E4))b(p)
ORDER BY p,n

```

Line breaks are for readability only.

Annoyingly longer than the trivial `PRINT` version (90 bytes):

```
PRINT'0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00'

```
> 1 votes

# Answer
# Bubblegum, 41 bytes

```
00000000: 1dc5 8105 0040 1402 d055 1ae0 50d1 feab  .....@...U..P...
00000010: dd2f 788f 8fc2 e192 433c 5c42 e891 7049  ./x.....C<\B..pI
00000020: 11ab 67a6 b8bc 90f5 01                   ..g......

```

Try it online!
> 0 votes

# Answer
# Retina, 58 bytes

```

¶0¶00¶000¶0000¶
.*¶
1$&2$&5$&
^
¶
+`¶(.?.?¶)
¶0$1
..¶
,$&

```

Try it online!
> 0 votes

# Answer
# Kotlin, ~~100~~ 99 bytes

## Submission

```
fun g(){var i=1
while(i<1e5){listOf(1,2,5).map{print("%d,%02d ".format(i*it/100,i*it%100))}
i*=10}}

```

## Runner

```
fun g(){var i=1
while(i<1e5){listOf(1,2,5).map{print("%d,%02d ".format(i*it/100,i*it%100))}
i*=10}}

fun main(vararg string: String) {
    g()
}

```

## TryItOnline

Link

## Edits

-1 | println -\> print
> 0 votes

# Answer
# Ruby, ~~66~~ 62 bytes

```
-2.upto 2{|m|[1,2,5].map{|v|$><<('%.2f '.%v*10**m).tr(?.,?,)}}

```

4 bytes shorter thanks to Lynn!

Try it online!
> 0 votes

# Answer
# Perl 6, ~~50~~ 45 bytes

```
{TR/./,/}o{((10 X**^5-2)X*1,2,5).fmt('%.2f')}

```

Try it online!

Function returning a string.
> 0 votes

# Answer
# VBA, ~~94~~ ~~93~~ 92 Bytes

Anonymous VBE immediate window function that takes no input and outputs the euro units to the VBE immediate window.

Restricted to 32-Bit VBA as exponentiation of the form `a^b` throws an error in 64-Bit VBA. To run in 64-Bit, change `10^j` to `10 ^j`.

```
For j=-2To 2:For Each i In Array(1,2,5):?Replace(Format(i*10^j,"0.00"),".",",")" ";:Next i,j

```

-1 Byte for replacing `Next:Next` with `Next i,j`
> 0 votes

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

```
Console.Write("0,01{0}2{0}5 0,10 0,20 0,50 1{1}2{1}5{1}1{2}2{2}5{2}10{2}20{2}50{2}"," 0,0",",00 ","0,00 ");

```

Run it
> 0 votes

# Answer
# JavaScript - 96 bytes

```
x=>{for(o="",b=-2;b<3;b++)for(n of[1,2,5])o+=(n*10**b).toFixed(2).replace(".",",")+" ";return o}

```

And here's a slightly longer (98 characters) functional approach:

```
x=>[].concat.apply([],[.01,.1,1,10,100].map(n=>[n,n*2,n*5])).map(n=>n.toFixed(2).replace(".",","))

```
> 0 votes

# Answer
# , 36 bytes

```
echo'.,'charsub 0j2":,1 2 5*/~10^i:2

```

Try it online!
> 0 votes

# Answer
# Tcl, 80 bytes

```
lmap d {-2 -1 0 1 2} {lmap c {1 2 5} {puts [regsub \\. [format %.2f $c\e$d] ,]}}

```

Try it online!

~~Tcl, 90 bytes
```
lmap d {.01 .1 1 10 100} {lmap c {1 2 5} {puts [regsub \\. [format %.2f [expr $c*$d]] ,]}}

```
Try it online!
~~

~~Still very long, golfing it more later!~~
> 0 votes

# Answer
# MathGolf, ~~25~~ 24 bytes

```
5125ß*m{ï3/ú*_♀/\♀%αû,0u

```

Try it online!

## Explanation

```
5                          Push 5
 125ß                      Push [1,2,5]
     *                     Multiply
      m{                   Map each element to...
        ï                  Push map index
         3/                Divide by 3
           ú               Push 10**TOS
            *              Multiply
             _             Duplicate element
              ♀/           Divide by 100
                \♀%        Swap top two elements and calculate TOS % 100
                   α       Wrap last two elements in array
                    û,0    Push ",0"
                       u   Join array with separator

```
> 0 votes

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


title: Upward and onward to greater glory!

text:
# Question
Title: Upward and onward to greater glory!
May this challenge serve as (another) tribute to Stan Lee, who passed away aged 95.

Stan Lee has left us an invaluable legacy and a peculiar catch word: *Excelsior*. So here's a small challenge based on what he said it was its meaning:

> Finally, what does “Excelsior” mean? “Upward and onward to greater glory!” That’s what I wish you whenever I finish tweeting! Excelsior!

### Challenge

Given a series of non-negative integers, output a line with `Excelsior!` every time an integer is greater than the previous one.

### Rules

* Input will be an array of non-negative integers.
* Output will consist of lines with the word `Excelsior` (case does matter) followed by as many `!` as the length of the current run of increasingly greater numbers. You can also return an array of strings.
* Input and output formats are flexible according to the site rules, so feel free to adapt them to your language formats. You can also add spaces at the end of the lines, or even extra new lines after or before the text if you need.

### Examples

```
Input             Output
-----------------------------------
[3,2,1,0,5]       Excelsior!      // Excelsior because 5 > 0

[1,2,3,4,5]       Excelsior!      // Excelsior because 2 > 1
                  Excelsior!!     // Excelsior because 3 > 2 (run length: 2)
                  Excelsior!!!    // Excelsior because 4 > 3 (run length: 3)
                  Excelsior!!!!   // Excelsior because 5 > 4 (run length: 4)

[]                <Nothing>

[42]              <Nothing>

[1,2,1,3,4,1,5]   Excelsior!      // Excelsior because 2 > 1
                  Excelsior!      // Excelsior because 3 > 1
                  Excelsior!!     // Excelsior because 4 > 3 (run length: 2)
                  Excelsior!      // Excelsior because 5 > 1

[3,3,3,3,4,3]     Excelsior!      // Excelsior because 4 > 3

```

This is , so may the shortest code for each language win!

# Answer
# JavaScript (ES6), ~~58~~ 54 bytes

```
a=>a.map(c=>a<(a=c)?`Excelsior${s+='!'}
`:s='').join``

```

Try it online!

### Commented

```
a =>                           // a[] = input array, also used to store the previous value
  a.map(c =>                   // for each value c in a[]:
    a <                        //   compare the previous value
    (a = c)                    //   with the current one; update a to c
                               //   this test is always falsy on the 1st iteration
    ?                          //   if a is less than c:
      `Excelsior${s += '!'}\n` //     add a '!' to s and yield 'Excelsior' + s + linefeed
    :                          //   else:
      s = ''                   //     reset s to an empty string and yield an empty string
  ).join``                     // end of map(); join everything

```

### Why re-using a\[ \] to store the previous value is safe

There are three possible cases:

* If \\$a\[\text{ }\]\\$ is empty, the callback function of `.map()` is not invoked at all and we just get an empty array, yielding an empty string.
* If \\$a\[\text{ }\]\\$ contains exactly one element \\$x\\$, it is coerced to that element during the first (and unique) test `a < (a = c)`. So, we're testing \\$x \< x\\$, which is falsy. We get an array containing an empty string, yielding again an empty string.
* If \\$a\[\text{ }\]\\$ contains several elements, it is coerced to `NaN` during the first test `a < (a = c)`. Therefore, the result is falsy and what's executed is the initialization of \\$s\\$ to an empty string -- which is what we want. The first meaningful comparison occurs at the 2nd iteration.
> 9 votes

# Answer
# Python 2, ~~84~~ ~~83~~ ~~81~~ ~~70~~ 68 bytes

```
a=n=''
for b in input():
 n+='!';n*=a<b;a=b
 if n:print'Excelsior'+n

```

Try it online!

-2 bytes, thanks to ASCII-only
> 5 votes

# Answer
# 05AB1E, ~~26~~ ~~24~~ 23 bytes

```
ü‹γvyOE.•1Š¥èò²•™N'!×«,

```

-2 bytes thanks to *@Kroppeb*.

Try it online or verify all test cases.

**Explanation:**

```
ü                        # Loop over the (implicit) input as pairs
 ‹                       #  And check for each pair [a,b] if a<b is truthy
                         #   i.e. [1,2,1,3,4,1,5,7,20,25,3,17]
                         #   → [1,0,1,1,0,1,1,1,1,0,1]
  γ                      # Split it into chunks of equal elements
                         #  i.e. [1,0,1,1,0,1,1,1,1,0,1]
                         #   → [[1],[0],[1,1],[0],[1,1,1,1],[0],[1]]
   vy                    # Foreach `y` over them
     O                   #  Take the sum of that inner list
                         #   i.e. [1,1,1,1] → 4
                         #   i.e. [0] → 0
      E                  #  Inner loop `N` in the range [1, length]:
       .•1Š¥èò²•         #   Push string "excelsior"
                ™        #   Titlecase it: "Excelsior"
                 N'!×«  '#   Append `N` amount of "!"
                         #    i.e. N=3 → "Excelsior!!!"
                      ,  #   Output with a trailing newline

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•1Š¥èò²•` is `"excelsior"`.
> 5 votes

# Answer
# Perl 6, ~~60 58~~ 57 bytes

*-1 byte thanks to nwellnhof*

```
{"Excelsior"X~("!"Xx grep +*,[\[&(-+^*×*)]] .skip Z>$_)}

```

Try it online!

Anonymous code block that returns a list of Excelsiors!
> 5 votes

# Answer
# Java-8 118 113 Bytes

```
n->{String e="";for(int i=0;i<n.length-1;)System.out.print(""==(n[i+1]>n[i++]?e+="!":(e=""))?e:"Excelsior"+e+"\n");}

```

*Easy to read :*

```
private static void lee(int num[]) {
    String exclamation = "";
    for (int i = 0; i < num.length - 1;) {
        exclamation = num[i + 1] > num[i++] ? exclamation += "!" : "";
        System.out.print("".equals(exclamation) ? "" : "Excelsior" + exclamation + "\n");
    }
}

```
> 4 votes

# Answer
# Japt `-R`, ~~25~~ 22 bytes

```
ò¨ ËÅ£`ExlÐâ`ú'!Y+A
c

```

Try it

3 bytes saved thanks to Kamil

```
ò¨                      :Partition at items that are greater than or equal to the previous item
   Ë                    :Map
    Å                   :  Slice off the first element
     £                  :  Map each element at 0-based index Y
      `ExlÐâ`           :    Compressed string "Excelsior"
             ú'!        :    Right pad with exclamation marks
                Y+A     :     To length Y+10
c                       :Flatten
                        :Implicitly join with newlines & output

```
> 4 votes

# Answer
# 05AB1E, ~~20~~ 19 bytes

```
ü‹0¡€ƶ˜ε'!×”¸Îsiorÿ

```

Try it online!

**Explanation**

```
ü‹                    # pair-wise comparison, less-than
  0¡                  # split at zeroes
    €ƶ                # lift each, multiplying by its 1-based index
      ˜               # flatten
       ε              # apply to each
        '!×           # repeat "!" that many times
                  ÿ   # and interpolate it at the end of
           ”¸Îsior    # the compressed word "Excel" followed by the string "sior"

```
> 4 votes

# Answer
# C (gcc/clang), ~~106~~ ~~99~~ 97 bytes

```
f(a,n)int*a;{int r=0,s[n];for(memset(s,33,n);n-->1;)r*=*a<*++a&&printf("Excelsior%.*s\n",++r,s);}

```

Thanks to gastropner for golfing 2 bytes.

Try it online here.

Ungolfed:

```
f(a, n) // function taking a pointer to the first integer and the length of the array
  int *a; { // a is of type pointer to int, n is of type int

    int r = 0, // length of the current run
        i = 0, // loop variable
        s[n];  // buffer for exclamation marks; we will never need more than n-1 of those (we are declaring an array of int, but really we will treat it as an array of char)

    for(memset(s, 33, n); // fill the buffer with n exclamation marks (ASCII code 33)
        n -- > 1; ) // loop over the array

        r *= *a < *(++ a) // if the current element is less than the next:
             && printf("Excelsior%.*s\n", // print (on their own line) "Excelsior", followed by ...
                       ++ r, // ... r (incremented) of the ...
                       s) // ... n exclamation marks in the buffer s
             ; // else r is reset to 0

}

```
> 4 votes

# Answer
# , 86 bytes

Half of this answer is @Giuseppe's. RIP Stan Lee.

```
function(a)for(i in diff(a))"if"(i>0,cat("Excelsior",rep("!",F<-F+1),"
",sep=""),F<-0)

```

Try it online!
> 4 votes

# Answer
# Common Lisp, 111 bytes

```
(setq i 0)(loop for(a b)on(read)do(incf i(if(and b(> b a))1(- i)))(format(> i 0)"Excelsior~v@{~a~:*~}~%"i #\!))

```

Try it online!
> 3 votes

# Answer
# , 111 bytes

```
function(a,r=rle(sign(diff(a))),v=r$l[r$v>0])write(paste0(rep("Excelsior",sum(v)),strrep("!",sequence(v))),1,1)

```

Try it online!

A far better R tribute can be found here -- I was too fixated on `sequence` and `rle`.
> 3 votes

# Answer
# Java 8, 106 bytes

```
n->{String s="",z=s;for(int i=0;i<n.length-1;)z+=n[i++]<n[i]?"Excelsior"+(s+="!")+"\n":(s="")+s;return z;}

```

Try it online!

(those reassignments of `s`...yikes)
> 3 votes

# Answer
# Stax, 17 bytes

```
Θx7├╖&σ '@7g┼┘Ñ«═

```

Run and debug it
> 3 votes

# Answer
# Jelly, 16 bytes

```
<Ɲṣ0ÄẎ”!ẋ“Ø6ḥ»;Ɱ

```

A monadic Link yielding a list of lists of characters.

**Try it online!** (footer joins with newlines)

### How?

```
<Ɲṣ0ÄẎ”!ẋ“Ø6ḥ»;Ɱ - Link: list of integers     e.g. [1,1,4,2,1,1,3,4]
 Ɲ               - for each pair of integers:      [1,1] [1,4] [4,2] [2,1] [1,1] [1,3] [3,4]
<                -   less than?                    [  0,    1,    0,    0,    0,    1,    1]
  ṣ0             - split at zeros                  [[],    [1],     [],   [],      [1,    1]]
    Ä            - cumulative sums                 [[],    [1],     [],   [],      [1,    2]]
     Ẏ           - tighten                         [1,1,2]
      ”!         - literal '!' character           '!'
        ẋ        - repeat (vectorises)             [['!'],['!'],['!','!']]
         “Ø6ḥ»   - dictionary lookup               ['E','x','c','e','l','s','i','o','r']
               Ɱ - map with:
              ;  -   concatenate                   [['E','x','c','e','l','s','i','o','r','!'],['E','x','c','e','l','s','i','o','r','!'],['E','x','c','e','l','s','i','o','r','!','!']]

```
> 3 votes

# Answer
# Perl 5 `-n`, 41 bytes

```
$_>$l&&$l?say$c.='!':($c=Excelsior);$l=$_

```

Try it online!

Takes its input on separate lines.
> 3 votes

# Answer
# Japt, 22 bytes

```
ò¨ ®£`ExlÐâ`+'!pYÃÅÃc

```

Try it online!

Explanation, with simplified example:

```
ò¨                       :Split whenever the sequence does not increase
                           e.g. [2,1,1,3] -> [[2],[1],[1,3]]
   ®               Ã     :For each sub-array:
    £            Ã       :  For each item in that sub-array:
     `ExlÐâ`             :    Compressed "Excelsior"
            +            :    Concat with
             '!pY        :    a number of "!" equal to the index
                               e.g. [1,3] -> ["Excelsior","Excelsior!"]
                  Å      :  Remove the first item of each sub-array
                            e.g. [[Excelsior],[Excelsior],[Excelsior,Excelsior!]]->[[],[],[Excelsior!]]
                    c    :Flatten
                           e.g. [[],[],[Excelsior!]] -> [Excelsior!]

```
> 3 votes

# Answer
# PowerShell, ~~87~~ 85 bytes

```
param($n)for(;++$i-lt$n.count){if($n[$i]-gt$n[$i-1]){"Excelsior"+"!"*++$c}else{$c=0}}

```

Try it online!

There's probably a restructuring hiding in there, most likely in the if-else, but overall pretty alright. Uses the ol' "Un-instantiated variable defaults to 0" trick for both making the index and the `!`.
> 3 votes

# Answer
# Powershell, 69 bytes

```
$args|%{if($o-ne$e-and$_-gt$o){'Excelsior'+'!'*++$c}else{$c=0}$o=$_}

```

Less golfed test script:

```
$f = {

$args|%{
    if($old-ne$empty-and$_-gt$old){
        'Excelsior'+'!'*++$c
    }else{
        $c=0
    }
    $old=$_
}

}

@(
    ,( (3,2,1,0,5),  'Excelsior!')      # Excelsior because 5 > 0

    ,( (1,2,3,4,5),  'Excelsior!',      # Excelsior because 2 > 1
                    'Excelsior!!',     # Excelsior because 3 > 2 (run length: 2)
                    'Excelsior!!!',    # Excelsior because 4 > 3 (run length: 3)
                    'Excelsior!!!!')   # Excelsior because 5 > 4 (run length: 4)

    ,( $null,         '')                # <Nothing>

    ,( (42),          '')                # <Nothing>

    ,( (1,2,1,3,4,1,5), 'Excelsior!',      # Excelsior because 2 > 1
                        'Excelsior!',      # Excelsior because 3 > 1
                        'Excelsior!!',     # Excelsior because 4 > 3 (run length: 2)
                        'Excelsior!')      # Excelsior because 5 > 1

    ,( (3,3,3,3,4,3),   'Excelsior!')      # Excelsior because 4 > 3
) | % {
    $a,$expected = $_
    $result = &$f @a
    "$result"-eq"$expected"
    $result
}

```

Output:

```
True
Excelsior!
True
Excelsior!
Excelsior!!
Excelsior!!!
Excelsior!!!!
True
True
True
Excelsior!
Excelsior!
Excelsior!!
Excelsior!
True
Excelsior!

```
> 3 votes

# Answer
# Lua, 88 87 83 82 96 95 113 bytes

*Thanks @Kevin Cruijssen for update adhering to spirit of original question.*

```
s=io.read()n=9 e="Excelsior!"f=e
for c in s.gmatch(s,"%S+")do if n<c+0then print(e)e=e..'!'else e=f end n=c+0 end

```

Try it online!
> 2 votes

# Answer
# Retina, 55 bytes

```
\d+
*
L$rv`(_*,(?<!(?(1)\1|\2,)))+(_+)\b
Excelsior$#1*!

```

Try it online! Link includes test cases. Explanation:

```
\d+
*

```

Convert to unary.

```
rv`(_*,(?<!(?(1)\1|\2,)))+(_+)\b

```

Process overlapping matches from right to left (although the matches are then listed from left to right). This means that we can match every number in a run, and the match extends to the start of the run. Each match is further constrained that each additional matched number must be less than the previously matched additional number, or the first number if no additional numbers have been matched yet.

```
L$...
Excelsior$#1*!

```

For each match, output `Excelsior` with the number of additional numbers in the run as desired.
> 2 votes

# Answer
# Pyth, 32 bytes

```
j+L"Excelsior"*L\!fT.u*hN<0Y.+Q0

```

Try it online here, or verify all the test cases at once here.

```
j+L"Excelsior"*L\!fT.u*hN<0Y.+Q0   Implicit: Q=eval(input())
                            .+Q    Get forward difference between consecutive elements of Q
                    .u         0   Reduce the above, returning all steps, with current value N starting at 0, next element as Y, using:
                       hN            N+1
                      *              Multiplied by
                         <0Y         1 if 0<Y, 0 otherwise
                  fT               Filter to remove 0s
              *L\!                 Repeat "!" each element number of times
 +L"Excelsior"                     Prepend "Excelsior" to each
j                                  Join on newlines, implicit print

```
> 2 votes

# Answer
# Jelly, 18 bytes

```
<Ɲ‘×¥\ḟ0”!ẋ“Ø6ḥ»;Ɱ

```

Try it online!

Output prettified over TIO.
> 2 votes

# Answer
# C++ 14 (g++), ~~123~~ 118 bytes

```
[](auto a){for(int n=0,i=0;++i<a.size();)a[i]>a[i-1]?puts(&("Excelsior"+std::string(++n,33))[0]):n=0;}

```

Fortunately `std::string` has a constructor that repeats a `char`. Try it online here.

Thanks to gastropner for saving 5 bytes.

Ungolfed:

```
[] (auto a) { // void lambda taking a std::array of integer

    for(int n = 0, // length of the current run
        i = 0; // loop variable
        ++ i < a.size(); ) // start with the second element and loop to the last
        a[i] > a[i - 1] // if the current element is greater than the previous ...
        ? puts( // ... print a new line:
               &("Excelsior" + // "Excelsior, followed by ...
                std::string(++ n, 33)) // ... the appropriate number of exclamation marks (33 is ASCII code for '!'); increment the run length
               [0]) // puts() takes a C string
        : n = 0; // else reset run length

}

```
> 2 votes

# Answer
# C# (.NET Core), 115 107 105 bytes

```
a=>{var b="";for(int i=0;++i<a.Length;)if(a[i]>a[i-1])Console.WriteLine("Excelsior"+(b+="!"));else b="";}

```

Try it online!

*-8 bytes: changed* `b` *to a string holding "!"s from an int counter*
*-2 bytes: set* `b+="!"` *as an inline function (thanks to Zac Faragher)*

Uses an Action delegate to pull in the input and not require a return.

Ungolfed:

```
a => {
    var b = "";                         // initialize the '!' string (b)
    for(int i = 0; ++i < a.Length;)     // from index 1 until the end of a
        if(a[i] > a[i - 1])                 // if the current index is greater than the previous index
            Console.WriteLine("Excelsior" +     // on a new line, print "Excelsior"
                                    (b += "!"));    // add a "!" to b, and print the string
        else                                // if the current index is not greater than the previous index
            b = "";                             // reset b
}

```
> 2 votes

# Answer
# PHP, ~~117~~ 109 bytes

```
<?php do{$i=next($argv);if($p!==null&&$p<$i){$e.='!';echo "
Excelsior$e";}else$e='';$p=$i;}while($i!==false);

```

Try it online!
> 2 votes

# Answer
# J, 50 bytes

```
'Excelsior',"1'!'#"0~[:;@(([:<+/\);._1)0,2</\ ::0]

```

Try it online!

## ungolfed

```
'Excelsior' ,"1 '!' #"0~ [: ;@(([: < +/\);._1) 0 , 2 </\ ::0 ]

```
> 2 votes

# Answer
**Java, 113 bytes**

```
String i="";for(int a=0;a<s.length-1;a++){if(s[a+1]>s[a]){i+="!";System.out.println("Excelsior"+i);}else{i="";}}

```
> 1 votes

# Answer
**VBA, 114 bytes**

```
For i=0 To UBound(a)-LBound(a)-1 If a(i+1)>a(i)Then s=s&"!" Debug.Print("Excelsior"&s&"") Else s="" End If Next i

```
> 1 votes

# Answer
# Japt, 25 bytes

```
ä< ®?`ExlÐâ`+'!p°T:T=0
f

```

Try it online!
> 1 votes

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


title: Prisoner's Dilemma v.3 - Petri Dilemma

text:
# Question
Title: Prisoner's Dilemma v.3 - Petri Dilemma
A mad scientist has just created a new species of bacterium! He has decided to name it *Noblus Gentlemanus*, after observing its behaviour. However, his bacteria have ran out of food, and have declared war, as they are able to harvest other bacterium's corpses for enough food to create copies of themselves. There are a number of different subspecies of this bacterium, who have different strategies in playing Prisoner's Dilemma, their favourite game. There are five bacteria from each different subspecies. In Prisoner's Dilemma, each of the two players simultaneously chooses either defect or cooperate. If one player chooses cooperate and the other chooses default, the defaulter gets 2 points, and the cooperator loses 3 points. If both player choose cooperate, both players get one 1 point. If both players choose default, both players lose 1 point.

Being Noble Gentlemen, the bacteria have decided to fight this war by playing 200 round long games of Iterated Prisoner's Dilemma. The loser of each duel will commit suicide, allowing the victor to clone itself. In the event of a tie, both bacteria will remain alive, but neither will be able to clone itself. In addition, all bacteria from a match carry over 10% of their points to the next match. A clone carries over the points of the bacterium it was cloned by. Also, there is a one in ten chance each turn that one bacterium will mutate into another subspecies, with 0 bonus points (if I receive complaints about the randomness of this, I can remove it). After the bacteria have played a number of these duels equal to the number of subspecies of bacteria times ten, the mad scientist accidentally drops the petri dish the bacteria reside in, and all of the bacteria acquire new sources of food, ending their duels. This is different from an ordinary iterated prisoner's dilemma contest, as it involves 1v1 duels with carryover points, rather than simply attempting to get the most points overall. This makes a big difference in how effective a given strategy is.

Each bacterium will receive input at the beginning of its turn in the format: (turn number, current points, enemies points, your previous moves \[in a string, using the character "c" for cooperate, and the character "d" for defect\], enemies previous moves \[in the same format\]).

Here are four sample strategies that will be entered. I actually think that Defector might win, even though it is extremely simple.

### Tit for Tat

```
def titfortatfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter==0 or enlist[counter-1] == "c":
        return "c"
    else:
        return "d"

```

### RandomPick

```
from random import choice
def randompickfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter == 199:
        return "d"
    else:
        return choice(["d", "c"])

```

### Cooperator

```
def cooperatorfunc(counter, mypoints, enpoints, mylist, enlist):
    return "c"

```

### Defector

```
def defectorfunc(counter, mypoints, enpoints, mylist, enlist):
    return "d"

```

All submissions must be in the form of a Python 2.7 function, with the name being the name of the submission with no spaces, with `func` on the end. If someone would like to submit an answer in a different language, please enter it in pseudo-code, for me to convert to Python in an edit to your answer once I have time, or give me instructions on interfacing your language with my controller which is found below set up for all submissions as of June 4.

```
from titfortat import titfortatfunc
from randompick import randompickfunc
from cooperator import cooperatorfunc
from defector import defectorfunc
from luckytitfortat import luckytitfortatfunc
from randomtitfortat import randomtitfortatfunc
from remorsefulaggressor import remorsefulaggressorfunc
from everyother import everyotherfunc
from niceguy import niceguyfunc
from titfortatbackstab import titfortatbackstabfunc
from gentleDefector import gentleDefectorfunc
from anticapitalist import anticapitalistfunc
from grimtrigger import grimtriggerfunc
from bizzaro import bizzarofunc
from neoanticapitalist import neoanticapitalistfunc
from bittertat import bittertatfunc
from teamer import teamerfunc
from copyfirst import copyfirstfunc
from exploitivetat import exploitativetatfunc
from defectorv2 import defectorv2func
from crazytat import crazytatfunc
from randomchoicev2 import randomchoicev2func
from twotitsforatat import twotitsforatatfunc
from threetitsforatat import threetitsforatatfunc
from fourtitsforatat import fourtitsforatatfunc
from fivetitsforatat import fivetitsforatatfunc
from sixtitsforatat import sixtitsforatatfunc
from tentitsforatat import tentitsforatatfunc
from theelephant import theelephantfunc
from xbittertat import xbittertatfunc
from fifteentitsforatat import fifteentitsfortatfunc
from twentytitsforatat import twentytitsforatatfunc
from fox import foxfunc
from onehundredfortysixtitsforatat import onehundredfourtysixtitsforatatfunc
from gameofthrones import gameofthronesfunc
from boy import boyfunc
from grimace import grimacefunc
from fiftytitsforatat import fiftytitsfortatfunc
from soreloser import soreloserfunc
from everyotherd import everyotherdfunc
from fiftythreetitsfortat import fiftythreetitsfortatfunc
from twentyfivetitsfortat import twentyfivetitsfortatfunc
from handshake import handshakefunc
from anty import antyfunc
from fiftyfourtitsforatat import fiftyfourtitsfortatfunc
from kindatitsfortat import kindatitsfortatfunc

import random

players = 38

rounds = players*10

def runcode(num, points1, points2, history1, history2, cell):
    ans = ""
    if cell == 0:
        ans = titfortatfunc(num, points1, points2, history1, history2)
    elif cell == 1:
        ans = randompickfunc(num, points1, points2, history1, history2)
    elif cell == 2:
        ans = cooperatorfunc(num, points1, points2, history1, history2)
    elif cell == 3:
        ans = defectorfunc(num, points1, points2, history1, history2)
    elif cell == 4:
        ans = luckytitfortatfunc(num, points1, points2, history1, history2)
    elif cell == 5:
        ans = randomtitfortatfunc(num, points1, points2, history1, history2)
    elif cell == 6:
        ans = remorsefulaggressorfunc(num, points1, points2, history1, history2)
    elif cell == 7:
        ans = everyotherfunc(num, points1, points2, history1, history2)
    elif cell == 8:
        ans = niceguyfunc(num, points1, points2, history1, history2)
    elif cell == 9:
        ans = titfortatbackstabfunc(num, points1, points2, history1, history2)
    elif cell == 10:
        ans = gentleDefectorfunc(num, points1, points2, history1, history2)
    elif cell == 11:
        ans = anticapitalistfunc(num, points1, points2, history1, history2)
    elif cell == 12:
        ans = grimtriggerfunc(num, points1, points2, history1, history2)
    elif cell == 13:
        ans = bizzarofunc(num, points1, points2, history1, history2)
    elif cell == 14:
        ans = neoanticapitalistfunc(num, points1, points2, history1, history2)
    elif cell == 15:
        ans = tentitsforatatfunc(num, points1, points2, history1, history2)
    elif cell == 16:
        ans = bittertatfunc(num, points1, points2, history1, history2)
    elif cell == 17:
        ans = copyfirstfunc(num, points1, points2, history1, history2)
    elif cell == 18:
        ans = exploitativetatfunc(num, points1, points2, history1, history2)
    elif cell == 19:
        ans = sixtitsforatatfunc(num, points1, points2, history1, history2)
    elif cell == 20:
        ans = fifteentitsfortatfunc(num, points1, points2, history1, history2)
    elif cell == 21:
        ans = fivetitsforatatfunc(num, points1, points2, history1, history2)
    elif cell == 22:
        ans = twentytitsforatatfunc(num, points1, points2, history1, history2)
    elif cell == 23:
        ans = threetitsforatatfunc(num, points1, points2, history1, history2)
    elif cell == 24:
        ans = fiftyfourtitsfortatfunc(num, points1, points2, history1, history2)
    elif cell == 25:
        ans = theelephantfunc(num, points1, points2, history1, history2)
    elif cell == 26:
        ans = xbittertatfunc(num, points1, points2, history1, history2)
    elif cell == 27:
        ans = foxfunc(num, points1, points2, history1, history2)
    elif cell == 28:
        ans = gameofthronesfunc(num, points1, points2, history1, history2)
    elif cell == 29:
        ans = boyfunc(num, points1, points2, history1, history2)
    elif cell == 30:
        ans = grimacefunc(num, points1, points2, history1, history2)
    elif cell == 31:
        ans = soreloserfunc(num, points1, points2, history1, history2)
    elif cell == 32:
        ans = everyotherdfunc(num, points1, points2, history1, history2)
    elif cell == 33:
        ans = twentyfivetitsfortatfunc(num, points1, points2, history1, history2)
    elif cell == 34:
        ans = fiftythreetitsfortatfunc(num, points1, points2, history1, history2)
    elif cell == 35:
        ans = handshakefunc(num, points1, points2, history1, history2)
    elif cell == 36:
        ans = antyfunc(num, points1, points2, history1, history2)
    elif cell == 37:
        ans = kindatitsfortatfunc(num, points1, points2, history1, history2)

    return ans

def fight(l1,l2):
    num1,num2=l1[0],l2[0]
    points1,points2=l1[1],l2[1]
    history1 = ""
    history2 = ""

    for num in range(200):
        p1 = runcode(num, points1, points2, history1, history2, num1)
        p2 = runcode(num, points2, points1, history2, history1, num2)

        history1+=p1
        history2+=p2

        if p1 == "c" and p2 == "c":
            points1 += 1
            points2 += 1
        elif p1 == "c" and p2 == "d":
            points1 -= 3
            points2 += 2
        elif p1 == "d" and p2 == "c":
            points1 += 2
            points2 -= 3
        elif p1 == "d" and p2 == "d":
            points1 -= 1
            points2 -= 1

    if points1 > points2:
        return [l1[0], points1/10], [l1[0], points1/10]
    elif points1 < points2:
        return [l2[0], points2/10], [l2[0], points2/10]
    else:
        return [l1[0], points1/10], [l2[0], points2/10]

def rounddoer(bots):
    bots2=[]
    for x in range(len(bots)):
        if x%2==0:
            out1, out2 = fight(bots[x], bots[x-1])
            bots2.append(out1)
            bots2.append(out2)

    return bots2

def gamedoer():

    bots=[[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0]]
    random.shuffle(bots)
    counter=0

    while counter < rounds:

        counter += 1
        bots = rounddoer(bots)

        if random.randint(0,10) == 9:
            bots[random.randint(0, players*5)-1] = [random.randint(0, players-1), 0]

        random.shuffle(bots)

##        for item in bots:
##            print str(item[0]) + " with " + str(item[1]) + " bonus points."

    return bots

a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,mycounter=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

while mycounter < 1000:
    mycounter += 1
    bots = gamedoer()

    print "Game: " + str(mycounter)

    for item in bots:
        if item[0]==0:
            a0 += 1
        if item[0]==1:
            a1 += 1
        if item[0]==2:
            a2 += 1
        if item[0]==3:
            a3 += 1
        if item[0]==4:
            a4 += 1
        if item[0]==5:
            a5 += 1
        if item[0]==6:
            a6 += 1
        if item[0]==7:
            a7 += 1
        if item[0]==8:
            a8 += 1
        if item[0]==9:
            a9 += 1
        if item[0]==10:
            a10 += 1
        if item[0]==11:
            a11 += 1
        if item[0]==12:
            a12 += 1
        if item[0]==13:
            a13 += 1
        if item[0]==14:
            a14+=1
        if item[0]==15:
            a15+=1
        if item[0]==16:
            a16+=1
        if item[0]==17:
            a17+=1
        if item[0]==18:
            a18 += 1
        if item[0]==19:
            a19+=1
        if item[0]==20:
            a20+=1
        if item[0]==21:
            a21+=1
        if item[0]==22:
            a22+=1
        if item[0]==23:
            a23+=1
        if item[0]==24:
            a24+=1
        if item[0]==25:
            a25+=1
        if item[0]==26:
            a26+=1
        if item[0]==27:
            a27+=1
        if item[0]==28:
            a28+=1
        if item[0]==29:
            a29+=1
        if item[0]==30:
            a30+=1
        if item[0]==31:
            a31+=1
        if item[0]==32:
            a32+=1
        if item[0]==33:
            a33+=1
        if item[0]==34:

```

## This Contest is now Finished

If you would like to add an answer, I'll see if I can get around to adding a post-challenge scoreboard under the one for the original contestants. I'll be adding that one as soon as the testing program finishes (probably 2-3 more days).

## FINAL SCORES!!!!!

```
Tit for Tat: 18
Random Pick: 28
Cooperator: 19
Defector: 24
Lucky Tit for Tat: 23
Random Tit for Tat: 23
Remorseful Aggressor: 22
Every Other C: 23
Nice Guy: 18
Tit for Tat Backstab: 15
Gentle Defector: 22
Anticapitalist: 27
Grim Trigger: 19
Bizzaro: 21
NeoAnticapitalist: 24
Ten Tits for a Tat: 240
Bitter Tat: 12
Copy First: 30
Exploitative Tat: 19
Six Tits for a Tat: 16
Thirty Tits for Tat: 4129
Five Tits for a Tat: 22
Forty Tits for a Tat: 1972
Three Tits for a Tat: 22
Fifty Four Tits for a Tat: 25805
The Elephant: 31
Extra Bitter Tat: 28
Fox: 35
Game of Thrones: 11297
The Boy: 31
Grimace: 26
Sore Loser: 39
Every Other D: 18
Twenty Five Tits for a Tat: 2399
Fifty Three Tits for a Tat: 5487
Handshake: 28
Anty: 26
Kinda Tits for Tat: 20
Prudent Defector: 154539
Bizzarro Trigger: 25
Young Mathematician: 21
Older Mathematician: 16
Perfect Gentleman: 1953341

```

So, it appears that Perfect Gentleman is the winner. Congratulations to Draco18, who definitely deserves his green checkmark.

# Answer
> 9 votes
# The Perfect Gentleman

I don't have a good description for this bot. I stumbled into a couple of potential optimizations, tested them, fine tuned, and ended up with a bacteria that *utterly destroys* the competition. Instead, I've commented the code itself to explain what it does.

```
import random
def perfectgentlemanfunc(num, i, d, c, en):
    if num>0 and i < 0 and d > 0 and -i%3 == 0 and d%2 == 0 and en[0] == "d":
        #probably very first iteration, probably facing a defector: feed it free points
        #    defector cannot be beaten by *any* bot unless that bot
        #    entered with a point lead. defector does some of our work for us
        if num >= 140:
            #140 threshold restricts how much we feed
            return "d"
        return "c"
    turn_to_betray = 130
    if num > turn_to_betray and en[turn_to_betray -2] == "c" and
     en[turn_to_betray -1] == "c" and en[turn_to_betray] == "d":
        #if self, then sacrifice the lower point bot to raise the points of the higher
        #(better net outcome than "c/c" cooperation)
        #    Handshake independently arrived at this same optimization
        if i == d:
            #max 50% probability of choosing different possible. May as well take it
            #    "ccd" has a 55% chance of choosing the same
            #    better outcomes for splitting early
            return "cd"[random.randint(0,1)]
        if i > d:
            return "d"
        return "c"
    #betray after betray point, or if behind by >200
    #performs 6 percentage points better than not having the condition
    if num >= turn_to_betray or i + 200 < d
        return "d"
    else:
        #be nice the first turn
        if num == 0:
            return "c";
        #finally, be tit-for-tat
        return en[-1]

```

Several values were arbitrarily chosen with alternatives tested and the values here are near-optimal at this point. Against the current spread of opposing factions, The Perfect Gentleman achieves complete dominance (100% of bacteria population) about 90% of the time (plus or minus 3 percentage points).

I have not added in the Mathematicians to my tests yet, however those two should only serve to feed existing strategies and not alter the outcome greatly.

It does manage a good portion of its control via propping up Defector, but that was allowed per the rules (the example strategies were fair game for targeting). It has a side effect of *also* propping up Game of Thrones, but that was unintentional as the two are indistinguishable based on the criteria I chose. Those "defector types" then have a point-advantage in round 2 and take out several troublesome neighbors as a result (the N-T4T types) and when they reface The Perfect Gentleman, they've expended their point advantage and are swiftly consumed.

There is an approximate 5% chance that all Perfect Gentlemen end up paired with Defector-types in the first round and end up committing mass suicide. In which case, one of the n-T4t types achieves total domination (196 cells of 196). Very rarely one of the other types (Game of Thrones, Boy, Grimace, Sore Loser...) manage to not go completely extinct and score a point or two.

Current simulation (still in progress towards 200 total games). All entries scoring 0 removed. Looks like Game of Thrones and 54-T4T split a round (195 points between them) after PG was eliminated.

```
Game: 90

Cooperator: 1
Remorseful Aggressor: 1
Copy First: 1
Six Tits for a Tat: 1
Thirty Tits for Tat: 393
Five Tits for a Tat: 1
Fifty Four Tits for a Tat: 538
Game of Thrones: 248
Perfect Gentleman: 16456 (93.2)%

##Simulation Terminated: Adding new bots

```

# Backstabbing Tit for Tat (with Forgiveness)

This is basically Lucky Tit for Tat (aka Tit for Tat with Forgiveness) which is the "solved" optimal solution (for some value of "lucky"), with a twist. As we *know exactly how many rounds* the game will last, this bacteria backstabs on the final round thus ensuring a net-beneficial outcome against any other Tit for Tat and Cooperator bacteria (against itself it ends with a net zero, same as if it had cooperated). Due to the 10% carryover, this results in a long-term advantage.

```
from random import randint
def titfortatbackstabfunc(num, i, d, c, enlist):
    if num == 199:
        return "d";
    lucky = randint(0, 200)
    if lucky == 0:
        return "c"
    if num == 0 or enlist[-1] == "c":
        return "c"
    else:
        return "d"

```

# Bitter Tat

Bitter Tat takes advantage of *any* attempts of cooperation given by the enemy when the enemy is ahead in points. Most bacteria offer an olive branch at least once during the 200 rounds, and as Bitter Tat is behind overall, it will milk those 5 points in a desperate bid for recovery.

Otherwise, it tit-for-tats per the usual dominant strategy. Also, it's a little bit more of a jerk than its cousin and backstabs a round earlier and offers no forgiveness.

```
def bittertatfunc(num, i, d, c, enlist):
    if i < d:
        return "d";
    if num >= 198:
        return "d";
    if num == 0 or enlist[-1] == "c":
        return "c"
    else:
        return "d"

```

Bitter Tat was designed via looking at the behaviors of other bots against Tit for Tat and the patterns expressed in those results, but is not designed to explicitly counter those strategies: it is still a general purpose formula.

# Extra Bitter Tat

```
def xbittertatfunc(num, i, d, c, enlist):
    if i < d:
        return "d";
    if num >= 188:
        return "d";
    if num == 0 or enlist[-1] == "c":
        return "c"
    else:
        return "d"

```

Extra bitter by defecting extra early.

# Answer
> 8 votes
# Anticapitalist

Another simple one. For even matches (starting at the same score) behaves pretty much like TitForTat, but the main idea is trying to survive the match.

```
def anticapitalistfunc(counter, mypoints, enpoints, mylist, enlist):
    if mypoints >= enpoints:
        return "c"
    else:
        return "d"

```

---

# Gentle Defector

My idea here is to defect except if my enemy is usually cooperating. Though, it begins cooperating.

```
def gentleDefectorfunc(counter, mypoints, enpoints, mylist, enlist):
    if enlist.count("d") * 4 > len(enlist):
        return "d"
    else:
        return "c"

```

---

# NeoAnticapitalist

An improvement of the Anticapitalist (or so I think). I see no reason to collaborate on last turn. I also see no reason to collaborate when I am pretty sure my opponent won't.

```
def neoanticapitalistfunc(counter, mypoints, enpoints, mylist, enlist):
    if mypoints >= enpoints:
        if counter > 1:
            if counter == 199 or (enlist[-1] != "c" and enlist[-2] != "c"):
                return "d"
        return "c"
    else:
        return "d"

```

# Answer
> 6 votes
# Remorseful Aggressor

```
from random import randint
def remorsefulaggressorfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter == 0:
        return "d"
    if (counter > 195 and mylist[-1] == "d"):
        return "d"
    if ((counter == 1 or counter > 2) and enlist[-1] == "d"):
        return "d"
    if (counter == 2 and enlist[-1] == "d" and enlist[-2] == "d"):
        return "d"
    if (counter >= 195 and randint(0, 200 - counter) == 0):
        return "d"
    else:
        return "c"

```

This is designed to "keep up" with Defector, by defecting every time against it, and also to beat tit-for-tat-based strategies.

The basic idea is that we start by defecting, but if the opponent cooperated turn 1, we then cooperate twice to avoid a mutual recrimination cycle, thus avoiding too large a point penalty. (If, however, the opponent defects later on, we don't break the cycle ourself; we'll make them do it and likely lose the game as a result.) Then at the end of the game, we pick a random time within the last 5 turns to backstab the enemy, giving us one more defection than them and thus meaning that as long as we weren't too far behind on carryover points, we end up winning, without sacrificing much in terms of carryover in the process. (Randomizing the time period means that we're very likely to get in first with the backstab, also that this strategy can't be "tuned against" by aiming to backstab it one turn earlier.)

# Answer
> 6 votes
# Grim Trigger

Simplistic bot, to try and fill out the competition

It will cooperate, unless the enemy defects, in which case it defects unforgivingly

```
def grimtriggerfunc(I, Do, Not, Care, enlist): return "d" if "d" in enlist else "c"

```

well, seems like this doesn't work because of the ntitsfortat meta of defecting early

# Answer
> 5 votes
# Game of Thrones

```
def gameofthronesfunc(counter, mypoints, enpoints, mylist, enlist):
    turn_to_betray = 140
    if counter >= turn_to_betray or mypoints > enpoints or "d" in enlist:
        return "d"
    else:
        return "c"

```

Idea here is that you can never lose by betraying, so the only reason to cooperate is if you're behind. It also has the general framework of the other T4T answers (without any forgiveness, because I'm not sure if there's much point with the other contenders here).

The turn to betray might need to be changed to win, since in an even race, the T4Ter who betrays first will win, but against a very cooperative bot, you will miss out on some lifetime points. I'm not sure the right apex for this hill, so I'm just going for 140. I wouldn't be surprised if it were much earlier, though.

If this ends up in a petri dish with a T4Ter who betrays earlier or a defector (ie 146 T4T), then it depends entirely on if the GoT is already ahead (it will stay ahead) or if they're even/GoT is behind, in which case the early betrayer will win.

# Answer
> 4 votes
# Lucky Tit For Tat

```
import os
def luckytitfortatfunc(num, i, d, c, enlist):
    lucky = ord(os.urandom(1))
    lucky = int(round(200 * float(lucky - 0) / 255.0))
    if lucky == 0:
        return "c"
    if num == 0 or enlist[-1] == "c":
        return "c"
    else:
        return "d"

```

I'm pretty sure I read somewhere that tit for tat was the best strategy. I decided to make it a possibility for other programs to redeem themselves just to add some variety. Now with a proper random number generator (it gives me an advantage right?).

# Answer
> 4 votes
# 54 Tits for a Tat

```
def fiftyfourtitsfortatfunc(num, more, fun, me, en):
    tits = 54
    if "d" in en[-tits:] or num >= (200-tits):
        return "d"
    return "c"

```

# Answer
> 4 votes
# The Elephant

The Elephant never forgets!

```
import re
def theelephantfunc(counter, mypoints, enpoints, mylist, enlist):
    interwoven = "".join(i for j in zip(mylist, enlist) for i in j)
    backwoven = interwoven[::-1]
    predict = re.match("^((?:..)*).*?(.).\\1(?:..)*$",backwoven)
    if(predict is None):
        return "c"
    predict = predict.groups()[1]
    if(predict == "d"):
        return "d"
    if(mypoints - enpoints >= 6):
        return "c"
    return "d"

```

The Elephant looks at the history of the fight, and tries to figure out what the enemy has planned. He looks at both his moves and his enemies!

He tries to find the longest concurrent group that matches what's just happened, and takes what the enemy did just after that.

If he can't work it out, the Elephant will just Cooperate, as friendship is always the answer.

If he thinks his opponent will defect, he too will defect, not wanting to lose his hard earned points.

If he thinks his opponent will cooperate, but his less than or exactly 6 points lead, then he will defect, to gain some foothold.

And lastly, if he thinks his opponent will cooperate, and he has a strong lead, he will cooperate.

# Answer
> 3 votes
# Every Other D

```
def everyotherdfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter % 2 == 0:
        return "d"
    else:
        return "c"

```

# Every Other C

```
def everyotherdfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter % 2 == 0:
        return "c"
    else:
        return "d"

```

# Answer
> 3 votes
# Nice Guy

```
def niceguyfunc(counter, mypoints, enpoints, mylist, enlist):
  if counter < 2:
    return "c"

  mylast = mylist[-1]
  enlast = enlist[-1]
  last_found_index = -1

  for i, item in enumerate(mylist):
    if i == counter - 1:
      break
    if mylist[i] == mylast and enlist[i] == enlast:
      last_found_index = i

  if last_found_index == -1:
    return "c"
  else:
    if enlist[last_found_index + 1] == "c":
      return "c"
    else:
      return "d"

```

Tries to predict the opponents output by looking at the history. For example, if the last moves were (`c`, enemy `d`), it tries to find the last occurrence of the exact same moves.

# Answer
> 3 votes
# ~~Hackman~~ \[disqualified as expected\]

Ok, this one will probably be ruled out of the contest, but I really feel like trying it out:

```
def hackmanfunc(counter, mypoints, enpoints, mylist, enlist):
        if enlist.count("#") > 0:
                return "c"
        elif counter >= 2 and enpoints > mypoints:
                return "d"
        elif counter == 198:
                return "d"
        elif counter == 199:
                return "#"
        elif counter == 0 or enlist[-1] == "c":
                return "c"
        elif counter >= 2 and enlist[-2] != "c":
                return "#"
        else:
                return "d"

```

Here I'm taking as base the BackstabbingTitForTat that proved to be the best in my simulations. Also, it's heavily based in using a non-used symbol `"#"`(that's why I say it will be probably ruled out).

Now let me explain the conditions here:

1st: Ensure two Hackman cooperate if something went wrong.

2nd: If I'm going to lose against a different bot, at least make him lose as many points as possible, so it's not a huge enemy afterwards.

3rd: Betray one turn before, so wins vs Backstabbing

using "#" instead of "d" makes me get 0 points instead of -1 and also communicate with other Hackman who has less points, so he stops defecting.

# Answer
> 3 votes
# Bizzaro

Does the exact opposite of tit for tat. When someone is kind to him he shows his love by being evil, and when someone is mean he shows revenge by being good. Heavily based on tit for tat.

```
def bizzarofunc(counter, mypoints, enpoints, mylist, enlist):
    if counter==0 or enlist[counter-1] == "c":
        return "d"
    else:
        return "c"

```

# Answer
> 3 votes
## Ten Tits for a Tat

```
def tentitsforatatfunc(num, more, fun, me, en):
    if "d" in en[-10:] or num >= 190:
        return "d"
    return "c"

```

Defects earlier, and also defects if its opponent has defected in the last ten turns.

## CopyFirst

```
def copyfirstfunc(num, mypoints, enpoints, myhistory, enhistory):
    if num == 0 or num >= 197:
        return "d"
    else:
        return enhistory[0]

```

This defects the first round, then does whatever the opponent did the first round, until the 197th round, when it backstabs.

## Forty Tits for a Tat

```
def fourtytitsforatatfunc(num, mypoints, enpoints, myhistory, enhistory):
    if "d" in en[-40:] or num >= 150:
        return "d"
    return "c"

```

If the opponent defected in the last 40 turns, defect, otherwise cooperate. Backstab on the last 50 turns.

## Three Tits for a Tat

If the opponent defected in the last 3 turns, defect, otherwise cooperate. Backstab on the last 5 turns. This program has stolen the lead from Tit for Two Tats by a narrow margin.

```
def threetitsforatatfunc(num, mypoints, enpoints, myhistory, enhistory):
    if num == 0 or num==1 and enhistory[-1]=="c" or num==2 and enhistory[-1]=="c" and enhistory[-2]=="c":
        return "c"
    if enhistory[-1] == "d" or enhistory[-2] == "d" or enhistory[-3] == "d" or num >= 195:
        return "d"
    else:
        return "c"

```

## Five Tits for a Tat

```
def fivetitsforatatfunc(num, more, fun, me, en):
    if "d" in en[-5:] or num >= 194:
        return "d"
    return "c"

```

If you can't figure out what this one does, you're an idiot. Also backstabs one round earlier.

# Answer
> 3 votes
# 6 Tits for a Tat

```
def sixtitsforatatfunc(num, more, fun, me, en):
    if "d" in en[-6:] or num >= 194:
        return "d"
    return "c"

```

Tit for Tat arms race is happening :)

# Answer
> 3 votes
# Grimace

```
def grimacefunc(I, Do, Not, Care, enlist):
    if round < 123: return "d" if "d" in enlist else "c"
    return "d"

```

# Answer
> 3 votes
# Predictable Mathematicians:

## Young Mathematician

New to the harshness of the world

```
import math
def ymathfunc(num, mpoints, enpoints, mlist, enlist):
  if(math.sin(num) + 0.8 > 0):
    return 'c'
  else:
    return 'd'

```

## Older Mathematitian

More experienced in these matters

```
import math
def omathfunc(num, mpoints, enpoints, mlist, enlist):
  if(math.cos(num) + 0.8 > 0):
    return 'd'
  else:
    return 'c'

```

I doubt either of these will do well, but at least they'll add ways for others to get points!

# Answer
> 2 votes
# Randomized Tit For Tat

```
import os
def randomtitfortatfunc(forgot, ten, var, iables, enlist):
    luck = enlist.count("d") + 1
    choice = ord(os.urandom(1))
    choice = int(round(luck * float(choice - 0) / 255.0))
    if choice == 0:
        return "c"
    return "d"

```

Tit For Tat, but randomized. This is not going to win any prizes (unless I'm really lucky). Now with random numbers generated from a proper source.

# Answer
> 2 votes
# Exploitative Tat

Exploitative Tat tries to play the following strategies:

* Defect when behind. It's the only way to catch up.
* Cooperate against tit-for-tat and similar strategies. It's the only way to get a good long-term score.
* Defect against always-cooperators and other chumps.
* Defect 5 rounds early.

Here's the code:

```
def exploitativetatfunc(num, mypoints, enpoints, mylist, enlist):
    if mypoints < enpoints:
        return "d"
    if num >= 195:
        return "d"
    if num == 0:
        return "c"
    # Test defect, and keep defecting as long as they'll allow
    if (num == 5 or num >= 8) and all(choice == "c" for choice in enlist):
        return "d"
    # Recover if that goes wrong, and they were nice.
    if (num == 6 or num == 7) and all(choice == "c" for choice in enlist[:4]):
        return "c"
    # Otherwise, tit for tat.
    return enlist[-1]

```

# Answer
> 2 votes
# 30 Tits for a Tat

```
def thirtytitsfortatfunc(num, more, fun, me, en):
    tits = 30
    if "d" in en[-tits:] or num >= (200-tits):
        return "d"
    return "c"

```

# Answer
> 2 votes
## Fox

```
def foxfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter > enpoints:
        return "d"
    return "c"

```

Defects if the round number is greater than the enemies points, cooperates otherwise.

## The Boy

```
def boyfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter!=0 and enlist[-1]=="c" and counter <= 194 or enpoints+10<mypoints:
        return "c"
    return "d"

```

Cooperates first round, then acts for tit for tat but backstabs on the last five rounds, and defects if it isn't ten points ahead.

## 53 tits for a tat

```
def fiftythreetitsfortatfunc(num, more, fun, me, en):
    tits = 53
    if "d" in en[-tits:] or num >= (200-tits):
        return "d"
    return "c"

```

You all know what this is :)

# Answer
> 2 votes
# Prudent Betrayer

```
def PrudentBetrayer(counter, mypoints, enpoints, mylist, enlist):
    # Am I ahead, even if he betrays first?
    if mypoints > enpoints + 5:
        if counter == 0:
            return "c"
        else:
            return enlist[-1]
    # Can I catch up if I betray first?
    elif mypoints + 5 > enpoints:
        if counter == 0:
            return "c"
        elif counter > 130:
            return "d"
        else:
            return "d" if "d" in enlist else "c"
    # can't win -> kill his score
    else:
        return "d"

```

Assumes it is fighting an `n-tits-for-a-tat` bot. If it has the score to be betrayed and still win, it will let the other bot hit it first (playing as tit for tat.) If it can win only when it betrays first, It will betray on round 130, well before any current bot. If it is many points behind its opponent, it will just play defector in an attempt to lower the unsuspecting bots score.

---

# Handshake

```
import random
def handshakefunc(num, me, him, m, en):
    handshake = "cdccd"
    # For the first few rounds, give the handshake.
    if num < len(handshake):
        if m == en:
            return handshake[num]
        return "d"
    if en[:len(handshake)] == handshake:
        if me > him:
            return "d"
        if me == him:
            return "ccd"[random.randint(0,2)]
        return "c"
    return "d"

```

Uses the pattern `cdccd` on the first five rounds, to find out if it is with itself. If so, it will try to max its points by having the bot with more points always defect, while the other always cooperates. If it finds it is fighting an enemy, it will play the defector.

In my tests, I find it dose well if it makes up a significant portion of the population. When it dose not have a chance to fight itself, it will basically be reduced to a defector.

EDIT: Clearly from the scores, their are to many bots for this to work well. It will still win if fighting just the top few...

---

# Bizzaro Trigger

```
def bizzaroTriggerfunc(round,ms,ts,mm,tm):
  if round==1:return 'c'
  if 'c' in tm:return'd'
  return 'c'

```

Always cooperate, unless your opponent ever cooperates with you, in which case you defect. Always.

# Answer
> 2 votes
# Twentyfivetitsforatat

```
def twentyfivetitsfortatfunc(num, more, fun, me, en):
    tits = 25
    if "d" in en[-tits:] or num >= (200-tits):
        return "d"
    return "c"

```

# Kinda titsforatat

```
def kindatitsfortatfunc(num, more, fun, me, en):
    tits = 54
    if "c" in en[-tits:] or num >= (200-tits):
        return "c"
    return "d"

```

# Answer
> 2 votes
but what if... the next answer was not grim trigger or something for tat

I present

# Anty

```
def antyfunc(counter, mypoints, enpoints, mylist, enlist):
    if counter > 150: return "d"
    if not "c" in enlist[-2:]:
        return "d"
    if enpoints >= mypoints:
        return "d"
    else:
        return "c"

```

# Answer
> 0 votes
# FakeShake

takes advantage of handshake- does a handshake then just defects while handshake trusts it. When it meets itself, however, it does the 'real' handshake. If it meets a different bot it plays tit for tat, with a betrayal at the end. This feels kinda mean...

```
import random
def fakeshakefunc(num, i, d, m, enlist):
      secret_handshake="cdccdd"
      handshake= "cdccd"
      #checks if it is meeting itself
      if enlist[:len(secret_handshake)] == secret_handshake:
          if me > him:
            return "d"
          if me == him:
             return "ccd"[random.randint(0,2)]
          return "c"
      #does handshake's handshake,if the bot is not handshake or fakeshake it plays T4T
      if num < len(handshake):
            if m == enlist:
                return handshake[num]
            if i < d or num>= 198:
                return "d";
            if num == 0 or enlist[-1] == "c":
                return "c"
            else:
                return "d"
            if enlist[:len(handshake)] == handshake:
                return "d"
            if i < d or num>= 198:
                return "d";
            if num == 0 or enlist[-1] == "c":
                return "c"
            else:
                return "d"

```

One problem with this is that if it meets handshake and it has more points, it thinks its playing itself. I'm a newbie to python and this site (in fact this is my first answer) so make sure to tell me if I've made any stupid mistakes!

---
Tags: king-of-the-hill, python
---


title: Unminify a Pythlike String

text:
# Question
Title: Unminify a Pythlike String
Pyth is perhaps the most successful general-purpose golfing language. Though it is somewhat in decline as a result of newer languages, from 2014 to 2016 Pyth's concise syntax, constant updates, overloading, and (for its era) many builtins made it a favorite for the majority of questions.

Pyth code is often difficult to read. Even the output of the debug mode (transpiled Python) often consists of a long line, sometimes with parentheses nested ten deep. However, correctly formatted Pyth is very readable.

Here's a piece of Pyth code, written by @isaacg in Play the Word Chain.

```
.MlZfqhMtTeMPT+Lzs.pMyQ

```

It's much more readable like this.

```
.M                     Filter by gives-maximal-value of
   l Z                   lambda Z:length(Z) over
   f                     filter by (lambda T:
     q                     equal
       hM t T                head-map tail T
       eM P T                end-map Pop T)
     +L                    Append z to each element in
        z
        s .pM y Q            flattened permutations of each subset of Q

```

For this challenge, we eliminate the aspect of categorizing Pyth characters and focus on formatting. Instead of being Pyth code, the input will consist of characters in `0123456789M`. The digit `n` represents a function of arity `n`, and `M` represents an operator. For example, the above code is represented as `210221M101M102M011M10`. Here are the steps to unminify:

### Separate the string into tokens.

A token matches `[0-9]M*`. `0M` will not occur in input.

### Add trailing 0s.

When there are not enough arguments, Pyth appends as many implicit variables (lambda variables or `Q`s) to the code as are necessary to fill the arguments of the program; these should be represented by `0`s.

### Group tokens into lines.

The arity of a token is the value of its digit.

* An arity-0 token (i.e. a 0) ends a line.
* For an arity-1 token the next token should go on the same line, separated by a space.
* For an arity \>=2 token, its arguments go on separate lines, in the order they appear in the code, each followed by their own subarguments and so on. Arguments to a token are indented to the end of that token plus one space.

## Input

A nonempty string (or char array, array of length-1 strings, etc. as allowed by Standard I/O Methods) consisting of `0123456789M`, which will not contain the substring `0M`.

## Output

The string formatted according to the above rules.

## Test cases

```
210221M101M102M011M10

2
  1 0
  2
    2
      1M 1 0
      1M 1 0
    2M
       0
       1 1M 1 0

123M4M

1 2
    3M
       4M
          0
          0
          0
          0
       0
       0
    0

2MM

2MM
    0
    0

11011100

1 1 0
1 1 1 0
0

9000000

9
  0
  0
  0
  0
  0
  0
  0
  0
  0

```

# Answer
> 1 votes
# Haskell, ~~192~~ ~~190~~ 187 bytes

```
unlines.snd.f
f(n:r)|(m,t)<-span(>'9')r,(s,l)<-n#t=(s,n?((n:m):map((' '<$(n:n:m))++)l))
f e=(e,["0"])
'1'?(a:b:r)=(a++drop(length a)b):r
_?s=s
'0'#s=(s,[])
n#s|(r,l)<-f s=(l++)<$>pred n#r

```

Try it online!

There has to be a better way to handle the arity-1 case, it currently takes up 45 bytes.

**Edits:**

* -2 bytes by switching to a different method of handling 1, though the previous method has probably more optimization potential.
* -3 bytes by not converting the character digits to numbers and using `pred` instead of `n-1`.

```
unlines.snd.f
f(n:r)|(m,t)<-span(>'9')r,(s,l)<-read[n]#t,w<-map((' '<$(n:n:m))++)=(s,last$((n:m):w l):[(n:m++' ':h):w t|n<'2',h:t<-[l]])
f e=(e,["0"])
0#s=(s,[])
n#s|(r,l)<-f s=(l++)<$>(n-1)#r

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES8), ~~160~~ 159 bytes

```
f=(s,a=[d=0,p=[1]])=>s.replace(/(.)M*/g,(s,c)=>(g=_=>a[d]?s+(P=p[d]-=c--&&~s.length,c?`
`.padEnd(P):' '):g(d--))(a[d]--,a[++d]=+c,p[d]=p[d-1]))+(d?f('0',a):'')

```

Try it online!

### Commented

```
f = (                          // f = recursive function taking:
  s,                           //   s   = input string
  a = [                        //   a[] = array holding the number of expected arguments
    d = 0,                     //   d   = current depth, initialized to 0
    p = [1]                    //   p[] = array holding the padding values
  ]                            //
) =>                           //
  s.replace(                   // search in s all substrings
    RegExp('(.)M*', 'g'),      // consisting of a digit followed by 0 to N 'M' characters
    (s, c) =>                  // for each substring s beginning with the digit c:
      ( g = _ =>               //   g = recursive function
          a[d] ?               //     if we're still expecting at least one argument at
                               //     this depth:
            s + (              //       append s
              P = p[d] -=      //       update the padding value P = p[d] for this depth:
                c-- &&         //         decrement c; unless c was equal to 0,
                ~s.length,     //         add the length of s + 1 to p[d]
              c ?              //       if c is not equal to 0 (i.e. was not equal to 1):
                `\n`.padEnd(P) //         append a linefeed followed by P - 1 spaces
              :                //       else:
                ' '            //         append a single space
            )                  //
          :                    //     else (all arguments have been processed):
            g(d--)             //       decrement the depth and call g again
      )(                       //   before the initial call to g:
        a[d]--,                //     decrement the number of arguments at depth d
        a[++d] = +c,           //     set the number of arguments for the next depth
        p[d] = p[d - 1]        //     set the padding value for the next depth,
      )                        //     using a copy of the previous depth
  ) + (                        // end of replace()
    d ?                        // if we're not back at depth 0:
      f('0', a)                //   do a recursive call to f with an extra '0'
    :                          // else:
      ''                       //   stop recursion
  )                            //

```

# Answer
> 1 votes
# Charcoal, 75 bytes

```
ＦＳ⊞υ⎇⁼ιM⁺⊟υιι≔⮌υυ≔⟦⟧θ≔⟦⟧ηＷ∨υη«≔⎇υ⊟υ0ιι¿⊖Σι↘→⊞θι⊞ηΣιＷ∧η¬§η±¹«⊟ηＭ⊕Ｌ⊟θ←¿η⊞η⊖⊟η

```

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

```
ＦＳ⊞υ⎇⁼ιM⁺⊟υιι

```

Loop over the input characters and turn them into a list of digits with optional `M` suffixes.

```
≔⮌υυ

```

Reverse this list so that we can use `Pop` to consume it.

```
≔⟦⟧θ

```

This variable is a stack of tokens whose arity has not yet been fulfilled.

```
≔⟦⟧η

```

This variable is a stack of the remaining arity of the unfulfilled tokens.

```
Ｗ∨υη«

```

Repeat until we have consumed all of the tokens and emptied the stack.

```
     ≔⎇υ⊟υ0ι

```

Get the next token or `0` if none.

```
     ι¿⊖Σι↘→

```

Print the token and then move the cursor horizontally if it begins with `1` otherwise diagonally.

```
     ⊞θι⊞ηΣι

```

Add the token and its arity to the appropriate variables.

```
     Ｗ∧η¬§η±¹«

```

Repeat while the arity stack is nonempty but the top arity is zero.

```
              ⊟η

```

Discard the zero arity.

```
              Ｍ⊕Ｌ⊟θ←

```

Remove its token and move that many characters left.

```
              ¿η⊞η⊖⊟η

```

If there are any arities left then decrement the top arity.

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


title: Number of transformations until repeat

text:
# Question
Title: Number of transformations until repeat
Given a sequence of integers or to be more specific a permutation of `0..N` transform this sequence as following:

* output\[x\] = reverse(input\[input\[x\]\])
* repeat

For example: `[2,1,0]` becomes `[0,1,2]` and reversed is `[2,1,0]`. `[0,2,1]` becomes `[0,1,2]` and reversed `[2,1,0]`.

**Example 1**

```
In:   0 1 2
S#1:  2 1 0
S#2:  2 1 0
Output: 1

```

**Example 2**

```
In:   2 1 0
S#1:  2 1 0
Output: 0

```

**Example 3**

```
In:   3 0 1 2
S#1:  1 0 3 2
S#2:  3 2 1 0
S#3:  3 2 1 0
Output: 2

```

**Example 4**

```
In:   3 0 2 1
S#1:  0 2 3 1
S#2:  2 1 3 0
S#3:  2 0 1 3
S#4:  3 0 2 1
Output: 3

```

Your task is to define a function (or program) that takes a permutation of integers `0..N` and returns (or outputs) the number of steps until a permutation occurs that has already occured. If `X` transforms to `X` then the output should be zero, If `X` transforms to `Y` and `Y` to `X` (or `Y`) then the output should be 1.

```
Y -> Y: 0 steps
Y -> X -> X: 1 step
Y -> X -> Y: 1 step
A -> B -> C -> D -> C: 3 steps
A -> B -> C -> D -> A: 3 steps
A -> B -> C -> A: 2 steps
A -> B -> C -> C: 2 steps
A -> B -> C -> B: also 2 steps

```

**Testcases:**

```
4 3 0 1 2 -> 0 3 4 1 2 -> 4 3 2 1 0 -> 4 3 2 1 0: 2 steps
4 3 2 1 0 -> 4 3 2 1 0: 0 steps
4 3 1 2 0 -> 4 1 3 2 0 -> 4 3 2 1 0 -> 4 3 2 1 0: 2 steps
1 2 3 0 4 -> 4 1 0 3 2 -> 0 3 4 1 2 -> 4 3 2 1 0 -> 4 3 2 1 0: 3 steps
5 1 2 3 0 4 -> 0 5 3 2 1 4 -> 1 5 3 2 4 0 -> 1 4 3 2 0 5 ->
  5 1 3 2 0 4 -> 0 5 3 2 1 4: 4 steps

```

If your language doesn't support "functions" you may assume that the sequence is given as whitespace seperated list of integers such as `0 1 2` or `3 1 0 2` on a single line.

*Fun facts:*

* the sequence 0,1,2,3,..,N will always transform to N,...,3,2,1,0
* the sequence N,..,3,2,1,0 will always transform to N,..,3,2,1,0
* the sequence 0,1,3,2,...,N+1,N will always transform to N,...,3,2,1,0

**Bonus task**: Figure out a mathematical formula.

**Optional rules**:

* If your language's first index is 1 instead of 0 you can use permutations `1..N` (you can just add one to every integer in the example and testcases).

# Answer
# JavaScript (ES6), 54 bytes

```
a=>~(g=a=>g[a]||~-g(g[a]=a.map(i=>a[i]).reverse()))(a)

```

Try it online!
> 4 votes

# Answer
# Python 2, 67 bytes

```
f=lambda l,*h:len(h)-1if l in h else f([l[i]for i in l][::-1],l,*h)

```

Try it online!
> 4 votes

# Answer
# Pyth, ~~10~~ ~~9~~ 8 bytes

```
tl.u@LN_

```

Explanation:

```
t               One less than
 l              the number of values achieved by
  .u            repeating the following lambda N until already seen value:
    @LN_N         composing permutation N with its reverse
         Q      starting with the input.

```

Test suite.
> 3 votes

# Answer
# Perl 6, ~~44~~ 35 bytes

*-9 bytes thanks to nwellnhof*

```
{($_,{.[[R,] |$_]}...{%.{$_}++})-2}

```

Try it online!

### Explanation:

```
{                              }  # Anonymous code block
                  ...    # Create a sequence where:
  $_,  # The first element is the input list
     {.[[R,] |$_]} # Subsequent elements are the previous element reverse indexed into itself
                     {        }    # Until
                      %.{$_}       # The index of the listt in an anonymous hash is non-zero
                            ++     # Then post increment it
 (                            )-2  # Return the length of the sequence minus 2

```
> 3 votes

# Answer
## Haskell, 52 bytes

```
([]#)
a#x|elem x a= -1|n<-x:a=1+n#reverse(map(x!!)x)

```

Try it online!

```
a # x                -- function '#' takes a list of all permutations
                     -- seen so far (-> 'a') and the current p. (-> 'x')
  | elem x a = -1    -- if x has been seen before, return -1
  | n<-x:a =         -- else let 'n' be the new list of seen p.s and return
    1 +              -- 1 plus
       n #           -- a recursive call of '#' with the 'n' and
        reverse ...  -- the new p.

([]#)                -- start with an empty list of seen p.s

```
> 3 votes

# Answer
# J, ~~33~~ ~~27~~ 26 bytes

*-7 thanks to bubbler*

```
_1(+~:i.0:)|.@C.~^:(<@!@#)

```

Try it online!

## how

original explanation. my last improvement only changes the piece which finds "the index of the first element we've seen already". it now uses the "nub sieve" to do it in fewer bytes.

```
1 <:@i.~ [: ({: e. }:)\ |.@C.~^:(<@!@#)
                        |.@C.~          NB. self-apply permutation and reverse
                              ^:        NB. this many times:
                                (<@!@#) NB. the box of the factorial of the
                                        NB. the list len.  this guarantees
                                        NB. we terminate, and the box means
                                        NB. we collect all the results
         [: ({: e. }:)\                 NB. apply this to those results:
                      \                 NB. for each prefix
             {: e. }:                   NB. is the last item contained in
                                        NB. the list of previous items?
1 <:@i.~                                NB. in that result find:
1    i.~                                NB. the index of the first 1
  <:@                                   NB. and subtract 1

```

Note the entire final phrase `1<:@i.~[:({:e.}:)\` is devoted to finding "the index of the first element which has already been seen." This seems awfully long for obtaining that, but I wasn't able to golf it more. Suggestions welcome.
> 2 votes

# Answer
# Jelly, 6 bytes

```
Ṛị$ƬL’

```

Try it online!

1-indexed.
> 1 votes

# Answer
# Dyalog APL, ~~29~~ ~~28~~ 27 bytes

```
¯2∘+∘≢{⍵,⍨⊂⌽(⍋⍳⊢)⊃⍵}⍣{⍺≢∪⍺}

```

Takes boxed arrays. Will trainify and explain later.

Try it here as a test suite.
> 1 votes

# Answer
# Clean, 90 bytes

```
import StdEnv
$l=length(until(\[h:t]=any((==)h)t)(\[h:t]=[reverse(map((!!)h)h),h:t])[l])-2

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Blink the webcam light!

text:
# Question
Title: Blink the webcam light!
*This challenge is inspired by Blink the CAPS LOCK by zeppelin.*

Most webcams feature a small integrated LED light, indicating if the webcam is in use, as controlled by a hardware mechanism to prevent spying.

Your task is to blink it:

1. Turn it on.
2. Wait for 0.5 (±0.1) seconds.
3. Turn it off again.
4. Wait for 0.5 (±0.1) seconds;
5. Repeat.

Please include a GIF or video of the webcam blinking, if possible. If an answer doesn't have the GIF, please add a GIF of the program running.

## Rules

* If your language is missing a subsecond `sleep` command, your program may use a 1 second delay instead, at a penalty of an additional byte. (replacing `.5` with `1`)
    + If your language, for some reason, doesn't support `.5`, your penalty is 2 bytes. (replacing `0.5` with `1`)
* Your program must loop unless halted by the user.
* Your LED can start either on or off; whichever is more beneficial can be used.
* If your LED has a turning-off delay, then it doesn't have to be taken into account, unless if you want to provide an additional version.

### Scoring

This is , which means the shortest answer in bytes wins.

# Answer
> 8 votes
# MATLAB, 40 bytes

```
while 1;w=webcam;pause(.5);delete(w);end

```

Creates an infinite `while` loop and each time through the loop, a `webcam` object is initialized (turns on the webcam), the script is paused for 0.5 seconds using `pause`, and then the `webcam` object is deleted (turning the webcam off).

# Answer
> 7 votes
# Python, 82 bytes

(Uses OpenCV for accessing the webcam.)

```
import cv2,time
s=time.sleep
while 1:w=cv2.VideoCapture(0);s(.5);w.release();s(.5)

```

# Answer
> 4 votes
# Javascript (ES6), 100 bytes

```
(f=_=>navigator.getUserMedia({video:1},x=>s(_=>x.getTracks()[0].stop(s(f,500)),500),s=setTimeout))()

```

During my testing, I saw a delay between the camera being activated and the LED turning on, so the timing may not be perfect. It also must run on an https:// page.

# Answer
> 1 votes
## Scratch in scratchblocks2, 61 bytes

```
when gf clicked
turn video[on v
wait(.5)secs
turn video[off v

```

Sorry about the absolutely terrible video. My LED has a slight turning-on delay, it is very faint, and the GIF is 18 MB.

---
Tags: code-golf, hardware
---


title: Splitting The Bill

text:
# Question
Title: Splitting The Bill
### Task

Suppose that `p` pepole have to split a bill; each of them is identified by a triple `(Name, n, k)` made up of:

* `Name`: *the name*;
* `n`: *the amount she/he has to pay*;
* `k`: *the amount she/he actually paid*.

The challenge here is to find out how much who owes whom.

### Assumptions

* Input and output can be in any convenient format.
* `p` \\$\in \mathbb{N}, \\,\\;\\;\\$`n` \\$\in \mathbb{N}^{+},\\;\\$ `k` \\$\in \mathbb{N}.\\$
* `p` \\$\gt 1.\\$
* Names are unique strings of arbitrary length, composed of lower case alphabet characters.

### Solution

The solution is represented by the minimum set of transactions among the `p` people; in particular they are triples `(from, to, amount)`

* `from`: `name` of the person that gives money;
* `to`: `name` of the person that receives money;
* `amount`: amount of money of the transaction.

**NOTE**: The sum of all the debts (`n`) can differ from the sum of all the already payed amounts (`k`). In this case, you must add in the output `('owner', Name, amount)` or `(Name, 'owner', amount)` in the format you have chosen. Any name will never be `owner`.The string 'owner' is flexible.

If several mimimum sets exist, select the one with the minimum sum of all the transaction amounts (absolute values); in case of a tie, choose one of them.

### Test Cases:

```
inputs(Name,n,k):
[('a',30,40),('b',40,50),('c',30,15)]
[('a',30,30),('b',20,20)]
[('a',30,100),('b',30,2),('c',40,0)]
[('a',344,333),('b',344,200),('c',2,2)]
[('a',450,400),('b',300,300),('c',35,55)]

outputs(from, to, amount):
[('c','a',10),('c','b',5),('owner','b',5)] or [('c','b',10),('c','a',5),('owner','a',5)]
[]
[('owner','a',2),('b','a',28),('c','a',40)] PS: [('owner','a',2),('b','a',68),('c','b',40)] has the same number of transactions, but it is not a valid answer, because the total amount of its transaction is greater than that of the proposed solution.
[('a','owner',11),('b','owner',144)]
[('a','owner',30),('a','c',20)]

```

**This is code-golf: shortest code wins**.

# Answer
> 2 votes
# JavaScript (ES6),  ~~252 227 223 222~~  215 bytes

Takes input as `[[n0, k0, name0], [n1, k1, name1], ...]`.

Transactions in the solution may be either positive or negative. The owner is called *undefined*.

```
a=>(m=g=(B,t,s)=>B.some(x=>x)?B.map((b,x)=>B.map((c,y)=>b*c<0&b*b<=c*c&&g(C=[...B],[...t,[a[x][2],b,a[y][2]]],s+a.length-1/b/b,C[C[y]+=b,x]=0))):m<s||(r=t,m=s))([...a.map(([x,y])=>t-(t+=y-x),t=0),t],[],a.push(g))&&r

```

Try it online!

### Commented

```
a => (                              // a[] = input array
  m =                               // initialize m to a non-numeric value
  g = (B, t, s) =>                  // g = function taking: B = balances, t = transactions,
                                    //     s = score of the current solution
    B.some(x => x) ?                // if at least one balance is not equal to 0:
      B.map((b, x) =>               //   for each balance b at position x:
        B.map((c, y) =>             //     for each balance c at position y:
          b * c < 0 &               //       if b and c are of opposite sign
          b * b <= c * c &&         //       and |b| <= |c|,
          g(                        //       do a recursive call to g:
            C = [...B],             //         - with a copy C of B
            [ ...t,                 //         - append the new transaction to t[]
              [a[x][2], b, a[y][2]] //           in [from_name, amount, to_name] format
            ],                      //
            s + a.length - 1/b/b,   //         - add (a.length - 1/b²) to s
            C[C[y] += b, x] = 0     //         - update C[y] and clear C[x]
          )                         //       end of recursive call
        )                           //     end of inner map()
      )                             //   end of outer map()
    :                               // else:
      m < s ||                      //   if the score of this solution is lower than m,
      (r = t, m = s)                //   update r to t and m to s
)(                                  // initial call to g:
  [                                 //   build the list of balances:
    ...a.map(([x, y]) =>            //     each balance is equal to:
      t - (t += y - x),             //     due_value - paid_value
      t = 0                         //     keep track of the total t ...
    ),                              //
    t                               //   ... which is appended at the end of this array
  ],                                //   (this is the balance of the owner)
  [],                               //   start with t = []
  a.push(g)                         //   append a dummy owner to a[]; start with s = 1
) && r                              // return r

```

---
Tags: code-golf
---