title: How fast is my Hot Wheels car?

text:
# Question
Title: How fast is my Hot Wheels car?
Several years back, Hot Wheels made a simple flash game called "Formula Fuelers Racers"\*. To play the game, you select three ingredients from a fridge to put into your car, which is then raced against the computer's randomly-generated car. It turns out the mechanics of this game are pretty simple. First off, the actual race "time" of your car is randomly generated and has no bearing on whether or not you win the race. Secondly, the winner of the race is determined by a score which is calculated from the selected ingredients (duplicate ingredients are allowed, and the order matters). Each ingredient has an associated "value" and an associated "operation" as shown in the following table:

```
#   ingredient     val  op
1   Hot Salsa       2   +
2   Root Beer       1   +
3   Milk            1   +
4   Pickle Juice    2   +
5   Mystery Lunch   -3  *
6   BBQ Sauce       2   +
7   Egg             1   +
8   Ketchup         2   +
9   Mustard         -1  *
10  Melon           1   +
11  Chocolate Milk  1   +
12  Mayonnaise      -2  *
13  Baby Food       0   +
14  Pepper          1   +
15  Salt            2   +
16  Syrup           -1  *
17  Salad Dressing  2   +
18  Orange Juice    1   +
19  Soy Sauce       2   +

```

For convenience, this challenge will be referring to ingredients by their number and not their name. Here are the steps to compute a score:

1. First, initialize the score with the value of the first ingredient.
2. Then, use the second ingredient's operation to combine the current score and the second ingredient's value to get an updated score.
3. Finally, use the third ingredient's operation to combine the current score and the third ingredient's value to get the final score.

Higher scores are better and always beat lower scores.

For example, the ingredients `1 2 3` have a score of `(2+1)+1 = 4`. The ingredients `7 5 6` have a score of `(1*-3)+2 = -1`. Therefore, `1 2 3` beats `7 5 6`.

**Challenge**

In this challenge, you shall write a program which takes an ordered list of 3 integers and outputs the corresponding score.

**Input**

Your program may accept a list of three integers in the most convenient format. You are allowed to use either 1-indexing for the ingredient names (as above) or 0-indexing (subtract 1 from every index above).

**Ouput**

Your program must output a single integer indicating the score.

**Test Cases**

```
4 5 5  =>  18 // max score
5 5 5  =>  -27 // min score
13 13 13  =>  0
1 2 3  =>  4
7 5 6  =>  -1
16 2 19  =>  2
19 7 12  =>  -6

```

*\*This page is pretty outdated and doesn't work in some browsers, but you don't need to play the game for this challenge.*

# Answer
# Jelly, 24 bytes

```
“zẈ€$ụ¤’b6’ị@µỊị⁾+×żCFḊV

```

Takes a list of 0-indexed ingredients.

**Try it online!** or see a test suite

### How?

Uses a slightly convoluted form of compressing the values as a base-6 number and the fact that the multiplicative entries are the negative ones. Instead of simply shifting up by 3 to get the base-6 digits, the complemented values incremented are used - this saves bytes by allowing the  atom to pick out the negative entries prior to the complement step while also saving a byte in the base-250 compression.

```
“zẈ€$ụ¤’b6’ị@µỊị⁾+×żCFḊV - Main link: 0-based ingredient list  e.g. [6,4,5]
“zẈ€$ụ¤’                 - base 250 compressed number: 120851767994004
        b6               - convert to base 6: [1,1,0,5,0,1,0,3,1,1,4,2,1,0,3,0,1,0,0]
          ’              - decrement: [0,0,-1,4,-1,0,-1,2,0,0,3,1,0,-1,2,-1,0,-1,-1]
           ị@            - index into [reversed @rguments]          [0,4,-1]
             µ           - monadic chain separation (call that x)
              Ị          - insignificant(x)? (abs(x)<=1)            [1,0,1]
                ⁾+×      - ['+','×']
               ị         - index into                               ['+','×','+']
                    C    - complement(x) (1-x)                      [1,-3,2]
                   ż     - zip                                      [['+',1],['×',-3],['+',2]]
                     F   - flatten                                  ['+',1,'×',-3,'+',2]
                      Ḋ  - dequeue                                  [1,'×',-3,'+',2]
                       V - evaluate as Jelly code                   -1

```
> 14 votes

# Answer
## JavaScript (ES6), ~~89~~ ~~84~~ ~~82~~ ~~78~~ 73 bytes

Takes input as an array of 3 integers, using 0-indexing.

```
a=>(o=a=>F()<0?a*n:a+n)(o((F=_=>n='5445054524413452545'[a.shift()]-3)()))

```

### Test cases

```
let f =

a=>(o=a=>F()<0?a*n:a+n)(o((F=_=>n='5445054524413452545'[a.shift()]-3)()))

console.log(f([3, 4, 4]))     // =>  18
console.log(f([4, 4, 4]))     // =>  -27
console.log(f([12, 12, 12]))  // =>  0
console.log(f([0, 1, 2]))     // =>  4
console.log(f([6, 4, 5]))     // =>  -1
console.log(f([15, 1, 18]))   // =>  2
console.log(f([18, 6, 11]))   // =>  -6
```

## Previous version, 78 bytes

Takes the 3 integers in currying syntax `(a)(b)(c)`, using 0-indexing.

```
a=>b=>(o=a=>b=>(n=F(b))<0?a*n:a+n)(o((F=n=>'5445054524413452545'[n]-3)(a))(b))

```

### How it works

One slightly unusual thing about this code is that it only takes 2 arguments in 'common' currying syntax `a => b =>` and eventually returns a function that takes the 3rd one.

**Breakdown**

```
F = n => '5445054524413452545'[n] - 3
o = a => b => (n = F(b)) < 0 ? a * n : a + n
f = a => b => o(o(F(a))(b))

```

```
f(a)(b)(c)
  |  |  |
  |  |  +-- 'b' argument of the function returned by the outer call to 'o'
  |  +----- 'b' argument of the function returned by 'f'
  +-------- 'a' argument of 'f'

```

### Test cases

```
let f =

a=>b=>(o=a=>b=>(n=F(b))<0?a*n:a+n)(o((F=n=>'5445054524413452545'[n]-3)(a))(b))

console.log(f(3)(4)(4))     // =>  18
console.log(f(4)(4)(4))     // =>  -27
console.log(f(12)(12)(12))  // =>  0
console.log(f(0)(1)(2))     // =>  4
console.log(f(6)(4)(5))     // =>  -1
console.log(f(15)(1)(18))   // =>  2
console.log(f(18)(6)(11))   // =>  -6
```
> 11 votes

# Answer
# PHP, 128 Bytes

```
$i="5445054524413452545";[,$a,$b,$c]=$argv;echo(bc.($i[$c]-3<0?mul:add))((bc.($i[$b]-3<0?mul:add))($i[$a]-3,$i[$b]-3),$i[$c]-3);

```

## PHP, 138 Bytes

```
$d=decbin(506743);$i="5445054524413452545";[,$a,$b,$c]=$argv;echo(bc.($d[$c]?add:mul))((bc.($d[$b]?add:mul))($i[$a]-3,$i[$b]-3),$i[$c]-3);

```

Online Version

Expanded

```
$d=decbin(506743);
$i="5445054524413452545";
[,$a,$b,$c]=$argv;
echo(bc.($d[$c]?add:mul))((bc.($d[$b]?add:mul))($i[$a]-3,$i[$b]-3),$i[$c]-3);

```
> 6 votes

# Answer
# Befunge, ~~74~~ 73 bytes

```
>&:0`!#^_1g68*-^:0`!#v_+
^2112-212/11.012/212 >*
^   @.$<       >">"35*0p

```

Try it here! It's weird that my code works on this one interpreter only.

The second row basically contains all of the values from the table. The non-numeric values are actually negative values as they come before the digits on the ASCII table. There's a bit of logic there that determines if the number is negative or not, and if it is, this number is multiplied by the result.

The right side of the third row initializes the first number. If I didn't have to do that, I could save a lot of bytes.
> 6 votes

# Answer
# Python 2, ~~123~~ ~~110~~ 107 bytes

```
a,b,c=input()
s=[int(i)-3for i in'05445054524413452545']
n=s[a]
for i in s[b],s[c]:n=[n*i,n+i][n>0]
print n

```

Try it online!

---

-3 bytes thanks to @mathjunkie
> 6 votes

# Answer
# 05AB1E, 29 bytes

```
•6SÚ²ÄOÃ•6BS3-©¹è|v®yèD0‹i*ë+

```

Try it online!

```
•6SÚ²ÄOÃ•6BS3-©               # Push [2, 1, 1, 2, -3, 2, 1, 2, -1, 1, 1, -2, 0, 1, 2, -1, 2, 1, 2] and store.
               ¹è             # Get first score.
                 |v           # Iterate through remaining scores.
                   ®yèD0‹i*ë+ # Push score list, grab relevant score.
                              # If negative, multiply, else add.

```

This actually works for as many or as few inputs as you'd like, so you can have cars with 4 or more traits or cars with just 2. This was not intentional, just how it ended up.
> 6 votes

# Answer
# CJam, ~~43~~ 38 bytes

```
q~[YXXY-3YXYWXX-2TXYWYXY]f={_W>42+c~}*

```

There might be a way to compress the list further...

Uses 0-based indexing.

Try it online!

**Explanation**

This program makes use of the fact that a value is multiplicative instead of additive if and only if its negative.

```
q~                     e# Get the list from input
  [...]                e# Push the list of values for each ingredient. T=0, W=-1,
                       e#   X=1, Y=2.
       f=              e# Get the elements at the given indices
         {             e# Reduce over this block:
          _W>          e#  Check if the second number is > -1 (returning 0 or 1)
             42+c      e#  Add the result to 42 and cast to a char.
                       e#    (ASCII 42 is * and 43 is +)
                 ~     e#  Eval the char (* is multiply, + is add)
                  }*   e# (end block)

```
> 5 votes

# Answer
# Lua, ~~140~~ 131 bytes

~~```
i={2,1,1,2,-3,2,1,2,-1,1,1,-2,0,1,2,-1,2,1,2}function f(a,b,c)loadstring(("print("..i[a].."+"..i[b].."+"..i[c]..")"):gsub('%+%-','*-'))()end

```~~
```
i={2,1,1,2,-3,2,1,2,-1,1,1,-2,0,1,2,-1,2,1,2}function f(a,b,c)x,y,z=i[a],i[b],i[c]v=y>0 and x+y or x*y;print(z>0 and v+z or v*z)end

```
> 3 votes

# Answer
# JavaScript, 85 72 bytes

```
a=a=>eval(a.map(x=>(b="5445054524413452545"[x]-3,b<0?"*":"+")+b).join``)

```

Takes input in format `[a,b,c]`
-13 bytes thanks to ETHproductions
> 3 votes

# Answer
# R, ~~125~~ 123 bytes

```
function(a,b,c){v=c(5,4,4,5,0,5,4,5,2,4,4,1,3,4,5,2,5,4,5)-3
o=rep("+",19)
o[v<0]="*"
get(o[c])(get(o[b])(v[a],v[b]),v[c])}

```

Anonymous function that takes three integers as input. Defines a list of values and operations, and then just evaluates the ones called by the input, i.e. `o3(o2(v1,v2),v3)`. There's almost definitely a golfier way to do this!

**Update:** after some re-working, I have an alternative, also **123 bytes**. Again, an anonymous function, but takes input as a single vector of three values. Uses the same approach, defining a list of values and operations and evaluating it.

```
function(x,f=c(sum,prod)[x[-1]%in%c(5,9,12,16)+1],s=c(5,4,4,5,0,5,4,5,2,4,4,1,3,4,5,2,5,4,5)[x]-3)f[[2]](el(f)(s[-3]),s[3])

```
> 2 votes

# Answer
# Haskell, ~~186~~ ~~116~~ ~~112~~ 108 bytes

```
o x|x<0=(*)|0<1=(+)
v=(map((-51+).fromEnum)"95445054524413452545"!!)
w [x,y,z]=(o z)((o y)x y)z
k=w.map v

```

Main function is `k`. New to Code Golf so I am sure there are a few bytes I could shave off with clever use of `$` operator versus parentheses. I will probably update the answer as I continue to find improvements.

Essentially the program can be broken down like this:

* v is a function that takes a 1 based index and returns the value of that food id.
* o is a function that takes the food value and returns the appropriate operator (Eg. negative values are always `*` where positive values are always `+`)
* w is a function that takes a List of 3 partial functions of `v` mapped to input integers and fetches the appropriate operations and values from each and returns the proper output.
* k is the main function in point free style that maps v to input and composes this list for w to return the output.

**UPDATE**

Special thanks for pointing out the fromEnum trick! That worked out nicely. Also I missed the part in the rules that stated an acceptable solution could be a function that takes a list of integers. That saved a tremendous amount of work.

**UPDATE 2**

As per other suggestions, shaved a handful of bytes by reordering operations, creating an else guard that always evaluates to True, and a pattern matching on W that pattern matches on a List of 3 elements. Thanks for the suggestions!

**UPDATE 3**

Another thanks to Laikoni for pointing out more code golf rules that I was not aware of. Also mapping v to my input to create a list of partially applied functions was a phenomenal idea and saved me 4 additional bytes!
> 2 votes

# Answer
## Haskell, ~~92~~ 87 bytes

```
x#y|x<0=(y*)|0<1=(y+)
k[x,y,z]=z#z$y#x$y
k.map([read[q]-3|q<-"95445054524413452545"]!!)

```

Try it online!

Based on @maple\_shaft's answer, I just factorized it a bit.

Thanks to @Laikoni for 5 bytes!
> 1 votes

# Answer
# 8086 machine code, 62 bytes

```
00000000  be 3b 01 31 c0 86 c4 ac  e8 0a 00 81 fe 3e 01 72  |.;.1.........>.r|
00000010  f4 b4 4c cd 21 bb 32 01  d0 e8 d7 73 03 c0 e0 04  |..L.!.2....s....|
00000020  c0 f8 04 e3 05 31 c9 c3  86 c4 78 03 00 e0 c3 f6  |.....1....x.....|
00000030  ec c3 21 12 d2 12 f1 1e  01 2f 12 00 00 00        |..!....../....|
0000003e

```

The last three bytes contain the (zero-indexed) input. Hey, you told me I could use the most convenient input format. In this case, that's hardcoding!
Output is the error code returned to the shell.

How it works:

```
            |   org 0x100
            |   use16
be 3b 01    |       mov si, input   ; source = input
31 c0       |       xor ax, ax      ; clear ax
86 c4       |   @@: xchg al, ah     ; swap al/ah (ah = total value)
ac          |       lodsb           ; al = *si++
e8 0a 00    |       call fn
81 fe 3e 01 |       cmp si, input+3 ; end of input?
72 f4       |       jb @b           ; repeat if not
b4 4c       |       mov ah, 0x4c    ; dos function: exit with al=error code
cd 21       |       int 0x21        ; syscall
            |
bb 32 01    |   fn: mov bx, table   ; pointer to lookup table
d0 e8       |       shr al, 1       ; divide input by 2
d7          |       xlatb           ; al = *(bx + al)
73 03       |       jnc @f          ; skip next instruction if input was odd
c0 e0 04    |       shl al, 4       ; shift low nibble to high nibble
c0 f8 04    |   @@: sar al, 4       ; shift high nibble to low nibble with sign-extension
e3 05       |       jcxz @f         ; return if cx is non-zero (only happens for the first input)
31 c9       |       xor cx, cx      ; clear cx
c3          |       ret
86 c4       |       xchg al, ah     ; swap al/ah (al = total value)
78 03       |   @@: js @f           ; multiply if negative, add if positive
00 e0       |       add al, ah      ; al = al+ah
c3          |       ret
f6 ec       |   @@: imul ah         ; ax = al*ah
c3          |       ret
21 12 d2 12 |   table db 0x21, 0x12, 0xd2, 0x12, 0xf1, 0x1e, 0x01, 0x2f, 0x12
f1 1e 01 2f |                       ; each value is stored in a 4-bit nibble
12          |
00 00 00    |   input db 3 dup(0)

```
> 0 votes

# Answer
# C, ~~171~~ 161 bytes

```
#include<stdio.h>
r,z[3],*a=z,i;f(x){i?x<0?r*=x:(r+=x):(r=x);}main(){scanf("%d %d %d",a,a+1,a+2);for(;i++<3;f("05445054524413452545"[*a++]-51));printf("%d",r);}

```
> 0 votes

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


title: Simulate my keyboard

text:
# Question
Title: Simulate my keyboard
I have an issue with my keyboard (more likely an issue with my browser). Some times when I click on a new text field and begin typing all my text comes out backwards. After a very short amount of time (for the purpose of the challenge we will say it is 10 milliseconds) it resumes typing forwards again. It seems that at first my cursor does not move when I begin to type so all the letters get inserted at the beginning of the textfield.

For example if I were typing `python` and I typed `pyt` in the first 10 milliseconds the result would be

```
hontyp

```

# Task

Your job is to simulate this behavior in as few bytes as possible.

## Input

You may take input in any reasonable method. You may not however take the input as two separate fields. The 10 millisecond delay should start when the program begins to allow input. That is you may have preprocessing to do before input is allowed, which should not be counted towards the 10 milliseconds.

Some leniency is permitted in the timing as long as it averages 10 milliseconds and is off by more than 1 milliseconds no more than 1% of the time on a reasonably speced computer.

## Output

You may output the string in whatever method you see fit. You may either update live as the user is typing or output the result after you are finished taking input (either by a newline or end of file `^D`).

# Test cases

*Some of these were generated by this CMC in The Nineteenth Byte*

```
First 10  | after   | result
bra         in-flak   in-flakarb
ap          ple       plepa
code-       golf      golf-edoc
no          ne        neon
we          st        stew
ai          med       media
draw        back      backward

```

# Answer
# VimScript, 48 47 bytes

Vim has some nice builtins for this. Requires Vim 8.

```
se ri|cal timer_start(10,{->execute("se ri&")})

```

Expects text entered in insert mode, a very reasonable input for VimScript. Explanation:

```
se ri " short for 'set revins', or 'reverse insert'
cal timer_start(10, " Start a timer that fires after 10ms
                 {->execute("se ri&")}) " Give it a lambda that unsets ri

```

My initial approach, `se ri|sl10m|se ri&`, doesn't work because the text is buffered until after the sleep command, and I couldn't find a way around this.
> 7 votes

# Answer
## HTML (JS), 96 bytes

```
<input id=i oninput=i.d=i.d||Date.now()+1e3;Date.now()<i.d&&(i.selectionEnd=i.selectionStart=0)>
```

Starts timing for 1s from the first keypress to give you a chance to see it in action.
> 5 votes

# Answer
## JavaScript (ES6), 88 bytes

```
p=s='',t=+new Date,document.onkeyup=k=>console.log(+new Date-t>9?(s+=k.key)+p:p=k.key+p)

```

### Demo

The way the snippet is working, you'll need to **click inside its frame** so that it gets focus *after* clicking on the *Run* button and *before* you can start typing.

There's no way to do that in less that 10ms. So, I've set the delay to 1 second in this demo -- and even so, you'd better hurry.

```
p=s='',t=+new Date,document.onkeyup=k=>console.log(+new Date-t>999?(s+=k.key)+p:p=k.key+p)
```
> 4 votes

# Answer
# Processing, ~~167~~ ~~165~~ 146 bytes

```
String a="",b="";long m=0;void setup(){size(9,9);}void draw(){m=m<1?millis():m;println(b+a);}void keyTyped(){if(millis()-m>9)b+=key;else a=key+a;}

```

Takes input as keystrokes and outputs to the console. It updates every frame.

### Explanation

```
String a="",b="";                // a contains the reversed (in the 10 milliseconds) string, b contains the text that is typed after the 10 milliseconds.
long m=0;                        // Store the start milliseconds in variable m
void setup() {
  size(9,9);                     // set the dimensions of the window
}

void draw() {                    // loop forever
  m=m<1?millis():m;              // update m
  println(b+a);                  // print the string b+a
}

void keyTyped() {                // this function gets called whenever a key is typed
  if(millis() - m) >9)           // if over 9 milliseconds have elapsed then
    b+=key;                      //   add the key to the end of b
  else                           // else (if less than 10 milliseconds have elapsed)
    a=key+a;                     //   prepend the key to a
}

```
> 3 votes

# Answer
# C - 169 bytes

Well C is not the best for this as it has no platform-independent way of doing this. Works under MSVC.

```
#include<time.h>
#include<conio.h>
l,k,b[9];main(a){for(a=clock();clock()-a<100;(k=_getch())?b[l++]=k:0);for(;(k=_getch())-13;k?putchar(k):0);for(;l;putchar(b[--l]));}

```

Bit of a hacky approach, if you can type more than 9 characters in 10 ms, this will crash. Updates after a newline character.
> 1 votes

# Answer
# Python 2, ~~112~~ 106

```
import msvcrt as m,time
a=b=''
T=time.time
t=T()
while 1:c=m.getch();exec'ba=+c=+cb'[T()-t>1::2];print a+b

```

If you want the output to be flush, without flooding with lines, use `print'\r'+a+b,` instead

You'll need to kill the process to stop it
> 1 votes

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


title: Generate a 5-pointed star

text:
# Question
Title: Generate a 5-pointed star
Your challenge is generate a 5 pointed star like below. The star doesn't need to be filled. Shortest code wins.

# Answer
# PHP, 1 character

Although very short it will probably not become the accepted answer.

(this is U+2606). May work also in other languages (untested).
> 30 votes

# Answer
## LOGO, ~~32~~ 29 bytes

```
REPEAT 5[FW 9LT 144FW 9RT 72]

```

Run at logo.twentygototen.org
> 20 votes

# Answer
# VBA PowerPoint, 92 bytes

```
Sub s()
ActivePresentation.Slides(1).Shapes.AddShape msoShape5pointStar, 0, 0, 99, 99
End Sub

```

Because everything looks better in PowerPoint:
> 18 votes

# Answer
# Mathematica, ~~19~~ 18 bytes

This is easy, using `CirculantGraph`.

I drew a pentagram as defined in the link the OP used.

```
5~CirculantGraph~2

```

---

A slightly longer way, but equally straightforward, is to use the curated "Lamina" entity. This returns a filled pentagram.

```
 "FilledPentagram"~LaminaData~"Image"

```

or

```
 EntityValue[Entity["Lamina","FilledPentagram"],"Image"]

```

---
> 11 votes

# Answer
# Python 3, 137 bytes

Polar plot.

```
import pylab as P,numpy as N
S=N.sin
p=N.pi
a=.9*p
d=8e-4*p
A=lambda t:N.arange(0,t,d)
P.polar(A(4*p),list(S(a)/S(a-A(.8*p)))*5)
P.show()

```
> 10 votes

# Answer
# Small Basic, 50 bytes

```
For i=1To 5
Turtle.Move(9)
Turtle.Turn(144)
EndFor

```

A verbose language, but it has built in turtle functionality. Slowly draws a very, very tiny pentagram.
> 8 votes

# Answer
# HTML & CSS: ~~270~~ 269 bytes

```
<p id=a/><p id=b></p><p id=c></p><p id=d></p><p id=e></p><style>p{position:absolute;width:300px;border-top:solid #000;margin:100px;transform-origin:50% 1666%}#b{transform:rotate(72deg)}#c{transform:rotate(144deg)}#d{transform:rotate(216deg)}#e{transform:rotate(288deg)}

```

Sample run:

## HTML & CSS: 139 bytes

Impressing rewrite by Neil.

```
div{height:20px;width:300px;border-bottom:solid #000;margin:100px;transform-origin:33% 5%;transform:rotate(72deg)}
```

```
<div><div><div><div><div>
```

(Since first posted, all desktope browsers dropped vendor prefixes, so now one CSS code fits all.)
> 7 votes

# Answer
# Scratch, 4-6 blocks (52-79 scratchblocks code)

This produces this
If anyone's interested, here's the project.
EDIT: To golf it, remove the pen down. You could remove the then flag clicked, too but it would only run if you clicked it. To golf the scratch blocks version, change "100" to "1", although you get a microscopic pentagram.

Nongolfed scratchblocks:

```
when gf clicked
clear
pen down
repeat (5
move (100) steps
turn cw (144) degrees

```
> 7 votes

# Answer
# HTML5, 37 bytes

```
<svg><path d="M4,0 7,8 0,3 8,3 1,8"/>

```
> 6 votes

# Answer
## Tcl/Tk, 57 bytes

```
pack [canvas .c]
.c cr po 72 0 114 130 3 49 140 49 29 130

```
> 4 votes

# Answer
# Ruby with Shoes, 36 bytes

```
Shoes.app{star(points:5).move 99,99}

```
> 4 votes

# Answer
# TurtleGolf, 70 24 22 bytes

Note: This is non-competing, as this language was made after this challenge was posted (though specifically for this challenge).

```
0;
aa*^aa*4b*+>1+:5=?;

```

Explaination:

```
0; - Initialize the loop counter and go to the next line.
aa* - Get the value 100
^ - Move forward by 100px
aa*4b*+ - Get the value 144
> - Rotate 144 degrees to the right
1+ - Increment the loop counter by 1
: - Duplicate it cause we need a copy of it.
5= - Check if the loop counter equals 5, push 1 if it is.
?; - If the top of the stack equals 1, terminate the line.

```

### Old, loopless version.

`aa*^aa*4a*+4+>aa*^aa*4a*+4+>aa*^aa*4a*+4+>aa*^aa*4a*+4+>aa*^aa*4a*+4+>`

I didn't add loops yet, so the code is kind of repetitive right now.

Explaination

```
aa*^              Move aa*(100) pixels forward
aa*4a*+a+         Get the value 144
>                 Turn 144 pixels to the right

```

EDIT: Shaved off lots of bytes.
EDIT2: Shaved off two more bytes.
> 4 votes

# Answer
# \[C (msvc)\], 88 bytes

```
#include<Windows.h>
main(){int p[]={50,1,20,91,97,35,2,35,79,91};Polygon(GetDC(0),p,5);}

```
> 4 votes

# Answer
## PostScript, 27 bytes

```
$ hexdump -C pentagram_binary.ps
00000000  39 20 39 92 ad 30 20 39  92 6b 36 7b 30 20 39 92  |9 9..0 9.k6{0 9.|
00000010  63 31 34 34 92 88 7d 92  83 92 a7                 |c144..}....|
0000001b

```

Download to try.

Output:

Un-golfed ASCII version:

```
9 9 translate
0 9 moveto
6{
  0 9 lineto
  144 rotate
}repeat
stroke

```
> 3 votes

# Answer
# Desmos, 46 characters

```
r=\sec\left(.4\arccos\left(\cos2.5\theta\right)\right)

```

Here is a longer version that allows you to choose some `n`:

```
r=\sec\left(\frac{2}{n}\arccos\left(\cos\frac{n\theta}{2}\right)\right)

```
> 3 votes

# Answer
# Python, 47 bytes

```
from turtle import*
for i in[144]*5:fd(i);rt(i)

```

**Try it online**

The following (**42 bytes**) also works (Python 2 only), but Trinket doesn't allow `exec`, so you can't run it online. Also, the result is much smaller.

```
from turtle import*
exec'fd(9);rt(144);'*5

```
> 3 votes

# Answer
# Shell, 60 bytes

(Coordinates shamelessly stolen from user1455003's SVG answer. For artistic merits upvote his answer.)

```
convert -size 9x9 xc: -draw 'polygon 4,0 7,8 0,3 8,3 1,8' x:

```

Sample output:
> 2 votes

# Answer
# R, ~~50~~ 54 bytes

```
plot(1:9,t="n",as=1);polygon(c(5,8,1,9,2),c(1,9,4,4,9))

```

Output:
> 2 votes

# Answer
# Google Blockly, 3 blocks

In response to the Scratch answer

Blockly turtle doesn't need "so much" boilerplate code.

This "code" can be ran here and produces this pentagram

# Five pointed star, 5 blocks

The five pointed star can be tested here
> 2 votes

# Answer
# R, 40 bytes

```
symbols(1,st=cbind(8,3,8,3,8,3,8,3,8,3))

```
> 2 votes

# Answer
# Swift 3, ~~394~~ 370 bytes

```
import UIKit
UIGraphicsBeginImageContextWithOptions(CGSize(width:2,height:2),false,100)
let c1=0.3,c2=0.8,s1=1.0,s2=0.6,o=(0.0,1.0),p=[o,(s2,-c2),(-s1,c1),(s1,c1),(-s2,-c2),o].map{CGPoint(    x:$0.0,y:$0.1)},c=UIGraphicsGetCurrentContext()!
c.translateBy(x:1,y:1)
c.setLineWidth(1/100)
c.move(to:p[0])
p.forEach{c.addLine(to:$0)}
c.fillPath()
UIImage(cgImage:c.makeImage()!)

```
> 2 votes

# Answer
# Octave, 24 bytes

```
polar(t=[1:.8:5]*pi,~~t)

```

Output:

Or, for 36 bytes you can have just the outline:

```
polar(t=[0:.2:2]*pi,1-mod(t,pi/2.5))

```
> 1 votes

# Answer
# Excel VBA, <sub>~~37~~</sub> 35 Bytes

Anonymous VBE immediates window function that takes no input and outputs a five pointed star to the top left of the `Sheet1` (default sheet) object

```
Sheet1.Shapes.AddShape 92,0,0,99,99

```

## Sample Output
> 1 votes

# Answer
# Tikz, ~~126~~ ~~120~~ 125 bytes

*5 bytes saved thanks to Julian Wolf*

```
\documentclass[tikz]{standalone}\usetikzlibrary{shapes}\begin{document}\tikz{\node[draw=red,star]{};}\end{document}

```

This draws a red star shaped node at `(0,0)`.
> 1 votes

# Answer
# Python 2, 52 bytes

```
from turtle import*;exec('fd(99);rt(144);'*5);done()

```
> 0 votes

# Answer
# JavaFX / FXML, 138 bytes

```
<?import javafx.scene.layout.*?><?import javafx.scene.shape.*?><Pane><children><SVGPath content="M4,0 7,8 0,3 8,3 1,8"/></children></Pane>

```

I haven't tested it yet, though

```
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>

<Pane>
   <children>
      <SVGPath content="M4,0 7,8 0,3 8,3 1,8" stroke="BLACK"/>
   </children>
</Pane>

```
> 0 votes

# Answer
# Python \+ Pylab, 48-byte copout answer

```
from pylab import*
plot(0,0,marker=(5,1))
show()

```

Plots a single point using a five-pointed star as a marker.
> 0 votes

# Answer
# TI-83/84 Basic, 32 bytes

```
Line(0,1,1,1:Line(0,0,.5,1.5:Line(1,0,.5,1.5

```

Note I haven't actually tested this out but I'm assuming it's going to show up as a low resolution, distorted star-shaped object.

* Line( command is one byte
> -1 votes

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


title: Incremental Cipher

text:
# Question
Title: Incremental Cipher
This task is rather simple, and makes use of three distinct "operator" characters. Your task is, given a simple sequence of letters, perform the following task to encode it using `<`,`>`,`*`. You may choose to use either upper or lowercase letters, you do not have to handle both.

---

# Cipher Explanation

The cipher is simple, you're using increment and decrement operations to traverse from letter 1 to the end letter, with `*` being your "submit" function. The operator for "increment" will be `>` and "decrement" will be `<`.

An example using the word `adbc`:

* Start with the first letter of the word, output that letter. `a`
* Next, use `>` and `<` (like brainfuck) to "navigate" the current letter to the next one. `a>` would result in 'raising' `a` by 1 to the letter `b`. `a<` would result in `z` because you're lowering the letter (it wraps, you must always choose the direction resulting in the LEAST number of operations).
* After outputting the correct minimalized combination of `<` and `>` output a `*` to denote that we've reached the next letter.

The steps to encode `adbc` would be:

```
a          # a
a>>>*      # ad
a>>>*<<*   # adb
a>>>*<<*>* # adbc

```

# Examples

The steps to encode `aza` would be:

```
a       # a
a<*     # az
a<*>*   # aza

```

More examples:

```
"abcdef"    =  "a>*>*>*>*>*"
"zyaf"      =  "z<*>>*>>>>>*"
"zzzzzz"    =  "z*****"
"z"         =  "z"
"zm"        =  "z<<<<<<<<<<<<<*" or "z>>>>>>>>>>>>>*" (equidistant)
"zl"        =  "z>>>>>>>>>>>>*"
"alphabet"  =  "a>>>>>>>>>>>*>>>>*<<<<<<<<*<<<<<<<*>*>>>*<<<<<<<<<<<*"
"banana"    =  "b<*>>>>>>>>>>>>>*<<<<<<<<<<<<<*>>>>>>>>>>>>>*<<<<<<<<<<<<<*" OR "b<*<<<<<<<<<<<<<*>>>>>>>>>>>>>*<<<<<<<<<<<<<*>>>>>>>>>>>>>*"
"abcdefghijklmnopqrstuvwxyz" = "a>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*"
"abcdefz"   =  "a>*>*>*>*>*<<<<<<*"

```

# Rules

* We are **encoding** not decoding, so don't mess that up.
* You may assume the message will contain letters `[A-Z]` or `[a-z]`, your choice.
* You may use any non-letter/numeric/reserved character to denote `*` (E.G. `$`).
* You must have the ending `*`, it isn't implicit on repeats.
* You may assume no empty strings, but a single character is possible.
* If it is equidistant either way to the next letter, you may choose a direction.
* This is , lowest byte-count wins.

*Please explain your answer, it helps others learn this way.*

# Answer
> 2 votes
# Jelly, 17 bytes

```
OIżN$ẋ"@€⁾><;€⁶ṭḢ

```

Uses a space character in place of `*` (a space, , or a newline, , saves one byte over `”*`).

Works with *either* uppercase-only *or* lowercase-only input.

**Try it online!** or see a test suite (where those spaces are post-replaced by `*` for reading ease).

### How?

```
OIżN$ẋ"@€⁾><;€⁶ṭḢ - Main link: string s          e.g. "adbc"
O                 - cast s to ordinals                [97,100,98,99]
 I                - incremental differences           [3,-2,1]
    $             - last two links as a monad:
   N              -     negate                        [-3,2,-1]
  ż               -     zip together                  [[3,-3],[-2,2],[1,-1]]
         ⁾><      - literal ['>','<']                 "><"
      "@€         - using reversed @arguments for €ach zip with("):
     ẋ            -     repeat (-n are like zeros)    [[">>>",""],["","<<"],[">",""]]
            ;€    - concatenate €ach with:
              ⁶   -     literal ' '                   [[">>>","",' '],["","<<",' '],[">","",' ']]
               ṭ  - tack to:
                Ḣ -     head of s (1st char)          [['a'],[">>>","",' '],["","<<",' '],[">","",' ']]
                  - implicit print   (" not printed:) "a>>> << > "

```

# Answer
> 11 votes
# 8086 machine code, ~~70 68~~ 67 bytes

```
00000000  be 82 00 bf 43 01 57 31  d2 ac 3c 0d 74 2c 89 d1  |....C.W1..<.t,..|
00000010  88 c2 aa e3 f4 4f 28 c1  9f 88 e7 79 02 f6 d9 83  |.....O(....y....|
00000020  f9 0d 9f 76 05 83 e9 1a  f6 d9 30 fc 9e b0 3c 78  |...v......0...<x|
00000030  02 b0 3e f3 aa b0 2a aa  eb cf c6 05 24 b4 09 5a  |..>...*.....$..Z|
00000040  cd 21 c3                                          |.!.|
00000043

```

How it works:

```
            |   org 0x100
            |   use16
be 82 00    |       mov si, 0x82        ; source = command line arguments
bf 43 01    |       mov di, result      ; destination = result
57          |       push di
31 d2       |       xor dx, dx          ; clear dx
ac          |   n:  lodsb               ; al = *si++
3c 0d       |       cmp al, 0x0d        ; end of input reached? (newline)
74 2c       |       je q                ; jump to exit in that case
89 d1       |   @@: mov cx, dx          ; store last char in cl
88 c2       |       mov dl, al          ; and store the current char in dl
aa          |       stosb               ; *di++ = al
e3 f4       |       jcxz n              ; skip encoding this char if cx == 0 (only happens for the first char)
4f          |       dec di              ; move di pointer back
28 c1       |       sub cl, al          ; take the difference between this char and the last one
9f          |       lahf                ; store flags from last subtraction in bh
88 e7       |       mov bh, ah
79 02       |       jns @f
f6 d9       |       neg cl              ; make sure cl is positive
83 f9 0d    |   @@: cmp cl, 13          ; which way is shorter?
9f          |       lahf                ; also store these flags
76 05       |       jbe @f
83 e9 1a    |       sub cl, 26          ; invert cl if we're going backwards
f6 d9       |       neg cl
30 fc       |   @@: xor ah, bh          ; xor saved flags together
9e          |       sahf                ; load flags register with the result
b0 3c       |       mov al, '<'
78 02       |       js @f               ; now the sign flag tells us which operator to use
b0 3e       |       mov al, '>'
f3 aa       |   @@: rep stosb           ; while (cx--) *di++ = al
b0 2a       |       mov al, '*'         ; mark the end with an asterisk
aa          |       stosb
eb cf       |       jmp n               ; repeat
c6 05 24    |   q:  mov byte [di], '$'  ; mark end of string
b4 09       |       mov ah, 0x09        ; dos function: print string
5a          |       pop dx              ; dx = string pointer
cd 21       |       int 0x21            ; syscall
c3          |       ret
            |   result rb 0

```

# Answer
> 10 votes
# Python 3, 87 bytes

```
r,*s=input();p=r
for c in s:d=(ord(p)-ord(c)-13)%26-13;r+='<'*d+'>'*-d+'*';p=c
print(r)

```

Try it online!

Works with either lowercase or uppercase.

The program builds the output string `r` as it iterates over the characters in the input string. It stores the previous character as `p`, and computes the incrementing operation to get from `p` to the new character `c`.

The interval between the characters is `ord(c)-ord(p)`, and `(ord(c)-ord(p)-13)%26-13` takes it modulo 26 to the interval `[-13..12]`. A negative result means it's shorter to step down, and a positive result means to step up. This needs to be converted to a string of `>` or `<` depending on the sign. Rather than using `abs` or a conditional, we take advantage of Python's string multiplication `s*n` giving the empty string when `n` is negative. In the expression `'<'*-d+'>'*d`, the wrong-signed part does not contribute.

The initial state is handled by splitting the input into its first character and the rest with Python 3's unpacking `r,*s=input()`. The initial character is used to start building the string, as well as the initial "previous" char.

Thanks to ovs for suggesting switching to Python 3 to do this unpacking.

# Answer
> 6 votes
# Python 3, ~~110~~ 93 bytes

```
r,*s=input()
b=r
for a in s:d=(ord(a)-ord(b))%26;r+=['>'*d,'<'*(26-d)][d>13]+'*';b=a
print(r)

```

Try it online!

# Answer
> 3 votes
## JavaScript (ES6), ~~118~~ ~~109~~ 107 bytes

The input string is case insensitive.

```
s=>s.replace(/./g,(c,i)=>(d=~~s-(s=parseInt(c,36)),i)?'<><>'[k=d/13+2|0].repeat([d+26,-d,d,26-d][k])+'*':c)

```

### How it works

Unlike Python, the JS modulo operator returns a number having the same sign as the dividend rather than the divisor. Also, the JS `repeat()` method throws an error when given a negative number, rather than returning an empty string (and it's significantly longer than a simple `*` anyway).

These are rather unfavorable behaviors for this challenge. So, we'd better identify in which exact case we are rather than relying on math tricks. (Which doesn't mean that such tricks do not exist, but rather that I failed to find them.)

Below is a table describing the 4 possibles cases, where `d` is the signed distance between the current character and the previous one:

```
d           | floor(d / 13) + 2 | direction | repeat
------------+-------------------+-----------+-------
-25 ... -14 |         0         |     <     | d + 26
-13 ... -1  |         1         |     >     | -d
 +0 ... +12 |         2         |     <     | +d
+13 ... +25 |         3         |     >     | 26 - d

```

### Test cases

```
let f =

s=>s.replace(/./g,(c,i)=>(d=~~s-(s=parseInt(c,36)),i)?'<><>'[k=d/13+2|0].repeat([d+26,-d,d,26-d][k])+'*':c)

console.log(f("abcdef"));
console.log(f("zyaf"));
console.log(f("zzzzzz"));
console.log(f("z"));
console.log(f("zm"));
console.log(f("zl"));
console.log(f("alphabet"));
console.log(f("banana"));
console.log(f("abcdefghijklmnopqrstuvwxyz"));
console.log(f("abcdefz"));
```

# Answer
> 2 votes
# PHP, 127 Bytes

```
for($l=ord($r=($s=$argn)[0]);$x=ord($s[++$i]);$l=$x)$r.=str_pad("",($a=abs($n=$l-$x))<14?$a:26-$a,"><"[$n>0^$a>13])."*";echo$r;

```

Testcases

## PHP, 137 Bytes

```
for($l=$r=($s=$argn)[0];$s[++$i];$l=$s[$i])$r.=str_pad("",$d=min($a=abs(ord($l)-ord($s[$i])),$b=26-$a),"><"[$d<$b^$l<$s[$i]])."*";echo$r;

```

Testcases

# Answer
> 2 votes
## Haskell (lambdabot), ~~161~~ 153 bytes

```
w(s:n)=s:(join.snd$mapAccumL(ap(,).g)s n);g c n|q<-[c..'z']++['a'..c],(Just l,s)<-minimum$first(elemIndex n)<$>[(q,'>'),(reverse q,'<')]=(s<$[1..l])++"*"

```

Try it online!

Explanation:

```
-- Encode a single letter
g c n | q          <- [c..'z']++['a'..c]        -- The alphabet starting from letter c, looping around
      , (Just l,s) <- minimum                   -- Choose the smallest of ..
                    $ first(elemIndex n)        -- the index of the letter n ..
                  <$> [(q,'>'),(reverse q,'<')] -- from the alphabet q and its reverse

      = (s<$[1..l]) -- Repeat < or > the same number of times as the index of n ..
     ++ "*"         -- and append *

-- Encode the whole string
w (s:n) = s                                -- Yield the first char of the input
        : ( join . snd                     -- Concatinate the result of ..
          $ mapAccumL (\a b->(b,g a b))s n -- executing the g function on each letter of the input string ..
                                           -- except the first, passing the previous letter as the 'c' ..
                                           -- argument on each iteration
          )

```

# Answer
> 2 votes
## JavaScript (ES6), ~~111~~ 103 bytes

```
f=
s=>s.replace(/./g,(c,i)=>(p=(n+26-(n=parseInt(c,36)))%26,i?'<>'[p+3>>4].repeat(p>13?26-p:p)+'*':c),n=0)
```

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

```
s=>[...s].map(c=>(n=parseInt(c,36),p&&(p=(n+26-p)%26,s+='><'[p+3>>4].repeat(p>13?26-p:p)+'*'),p=n),s=s[p=0])&&s

```

Originally version that took 111 bytes before I adapted @Arnauld's trick of setting `n` while computing `p`, I think there's probably another trick using `s` instead of `n` but it's getting late so I won't bother.:

# Answer
> 2 votes
## EXCEL VBA 130 bytes

```
s="":p=Mid(s,1,1):For i=1 To Len(s)-1:b=Asc(Mid(s,i+1,1)):a=Asc(Mid(s,i,1)):p=p &String(abs(b-a),IIf(b>a,">","<"))&"*":Next:[a1]=p

```

Run it from Excel VBA Immediate window.

Explanation:

Simple for loop that with String function to repeat the "\>" or "\<" n number of times where n is the ascii difference between the i and i+1 character string.

# Answer
> 2 votes
# C, 170 bytes

```
e(c){putchar(c);}i;m(a,b){i=b-a?a>b?b-a<14?b-a:-(a+26-b):a-b<14?-(a-b):b+26-a:0;while(i>0)e(62),i--;while(i<0)e(60),i++;}f(char*l){e(*l);while(l[1])m(*l,l[1]),e(42),l++;}

```

**Detailed** Live

```
e(c){ putchar(c); } // encode

g(a,b) // obtain required transition
{
    return (b-a) // calculate distance

         ? (a > b // distance is non-zero

             // if b comes after a
             ? (b-a < 14 // if forward is a shorter path
                 ? b-a // go forward
                 : -(a+26-b)) // otherwise go backward

             // if b comes before a
             : (a-b < 14 // if backward is a shorter path
                 ? -(a-b) // go backward
                 : b+26-a)) // otherwise go forward

         : 0; // if distance is 0
}

// transition
i;m(a,b)
{
    // obtain required transition
    i=g(a,b);

    // encode forward transition
    while(i>0)e('>'), i--;

    // encode backward transition
    while(i<0)e('<'),i++;
}

// incremental cipher function
f(char*l)
{
    e(*l); // encode first character

    while(*(l+1)) // while next character is not END-OF-STRING
        m(*l,*(l+1)), // do transition from current to next character
        e('*'), // encode
        l++; // next
}

```

# Answer
> 2 votes
# Java 7-, 232 bytes

```
class C{static void main(String[]a)throws Exception{int i=System.in.read(),j,d,c;p(i);while((j=System.in.read())>10){d=(j-i+26)%26;c=d>13?-1:1;while(d%26>0){d-=c;p(61+c);}p(42);i=j;}}static void p(int k){System.out.print((char)k);}}

```

Pretty much the trivial solution. Ungolfed and commented:

```
class C {
    static void main(String[] a) throws Exception {
        int i = System.in.read(), j, d, c; // i is the last character. j is the current character. d is the difference. c is the direction (-1 is left, 1 is right)
        p(i); // print the starting character first
        while ((j = System.in.read()) > 10) { // keep going until a newline is hit (or an EOF/EOL for -1)
            d = (j - i + 26) % 26; // get the difference (always positive) by wrapping around
            c = d > 13 ? -1 : 1; // get the direction by finding which way is shorter, going right when it's a tie
            while (d % 26 > 0) { // keep going until the current character is reached
                d -= c; // reduce d in the right direction
                p(61 + c); // < is 60 = 61 + (-1), > is 62 = 61 - (-1)
            }
            p(42); // print an asterisk
            i = j; // set the current character to the new reference point
        }
    }

    static void p(int k) {
        System.out.print((char) k);
    }
}

```

# Answer
> 2 votes
**C++ ,~~210~~ 190 bytes**

My First Try At Golfing !

```
#include<iostream>
int g(char*a){char k,j,d;std::cout<<*a;a++;for(;*a;a++){for(j=*(a-1),d=j-*a,k=d>0?d>13?62:60:d<-13?60:62;j!=*a;j+=k-61,j=j<97?122:j>122?97:j)std::cout<<k;std::cout<<'*';}}

```

k stores which of \< , \> or * to print .At first it simply prints the first element of array then runs a loop for a from first to last element of array . j stores the previous element and then by comparing if j closer to \*a by \< or \> set k to \< ,\> respectively and then print k then run this loop until j becomes equal to p . Then after every ending of second loop print * .

# Answer
> 1 votes
# 05AB1E, 17 bytes

```
¬sÇ¥v„<>y0›èyÄ×ðJ

```

Try it online!

**Explanation**

Uses `>`, `<` and `<space>` to denote *increment*, *decrement*, *submit*

```
¬                  # get the first letter of the input string
 sÇ¥               # push a list of delta's of the character codes in the input string
    v              # for each delta
     „<>           # push the string "<>"
        y0›        # check if the delta is positive
           è       # use this to index into the string
            yÄ×    # repeat it abs(delta) times
               ðJ  # join to string with a space

```

# Answer
> 1 votes
# JavaScript (ES6), ~~140~~ ~~128~~ ~~129~~ ~~111~~ 113 bytes

I went down a different route to the other JS solutions but it didn't work out too well - here's what I have so far:

```
f=

([x,...s])=>x+s.map(y=>`<><>`[r=(d=y[c=`charCodeAt`]()-x[c](x=y))/13+2|0].repeat([d+26,-d,d,26-d][r])+`*`).join``

i.addEventListener("input",()=>o.innerText=i.value&&f(i.value))
console.log(f("adbc"))
console.log(f("aza"))
console.log(f("abcdef"))
console.log(f("zyaf"))
console.log(f("zzzzzz"))
console.log(f("z"))
console.log(f("zm"))
console.log(f("zl"))
console.log(f("alphabet"))
console.log(f("banana"))
console.log(f("abcdefghijklmnopqrstuvwxyz"))
console.log(f("abcdefz"))
```

```
<input id=i>
<pre id=o>
```
* Saved 12 bytes thanks to a suggestion from Luke on destructuring the string.
* Added 1 byte fixing a misreading of the challenge, which I thought allowed for an implicit final print character.
* Saved another 18 bytes thanks to an extensive rewrite by Luke.
* Added 2 bytes as it seems numbers are not valid print characters.

---

## Original, 131 bytes

```
f=

([x,...s])=>x+s.map(y=>(t=(d=y[c=`charCodeAt`]()-x[c](x=y))<0?-d:d,`<>`[+((r=t<13)&&d>0)||+(!r&&d<0)].repeat(r?t:26-t)+`*`)).join``

i.addEventListener("input",()=>o.innerText=i.value&&f(i.value))
console.log(f("adbc"))
console.log(f("aza"))
console.log(f("abcdef"))
console.log(f("zyaf"))
console.log(f("zzzzzz"))
console.log(f("z"))
console.log(f("zm"))
console.log(f("zl"))
console.log(f("alphabet"))
console.log(f("banana"))
console.log(f("abcdefghijklmnopqrstuvwxyz"))
console.log(f("abcdefz"))
```

```
<input id=i>
<pre id=o>
```

# Answer
> 1 votes
# Haskell, ~~167~~ ~~168~~ 126 bytes

```
f=fromEnum
r=replicate
a?b=mod(f a-f b-13)26-13
c#x=r(c?x)'<'++r(-c?x)'>'
s(c,s)x=(x,s++c#x++"*")
e(x:y)=x:snd(foldl s(x,[])y)

```

Now using xnor's arithmetic solution. Call with `e str` where `str :: String` is the string to be encoded.

# Answer
> 1 votes
# Haskell, 109 bytes

```
a#b=mod(a-b-13)26-13
r=replicate
h(a:b:s)=r(a#b)'>'++r(-a#b)'<'++'*':h(b:s)
h e=""
f(a:r)=a:h(fromEnum<$>a:r)

```

Try it online! Uses xnor's approach. Call with `f "somestring"`.

---
Tags: code-golf, cipher
---


title: Self Referential Puzzle - medium 2

text:
# Question
Title: Self Referential Puzzle - medium 2
The following puzzle was asked in puzzling SE. This puzzle is quite hard to solve by hand because every answer depends on another answer. So, for example, a solution with all answers being A does not work because then the question 7 would contradict question 8, for example.

One of the answers there at puzzling SE suggested to write a program to test all possible answers and show one of them (if it exists). So, I'm bringing this to the experts :)

The puzzle consists in finding an array of ten characters (each one of them being either A, B, C, D or E) that satisfies all the following questions (where each character in the array is an "answer" and its index is a "question") **without contradiction**:

1. The first question whose answer is D is the question

> A. 8
> B. 7
> C. 6
> D. 5
> E. 4
2. Identical answers have questions

> A. 3 and 4
> B. 4 and 5
> C. 5 and 6
> D. 6 and 7
> E. 7 and 8
3. The number of questions with the answer E is

> A. 1
> B. 2
> C. 3
> D. 4
> E. 5
4. The number of questions with the answer A is

> A. 1
> B. 2
> C. 3
> D. 4
> E. 5
5. The number of questions with the answer A equals the number of questions with the answer

> A. A
> B. B
> C. C
> D. D
> E. none of the above
6. The last question whose answer is B is the question

> A. 5
> B. 6
> C. 7
> D. 8
> E. 9
7. Alphabetically, the answer to this question and the answer to the following question are

> A. 4 apart
> B. 3 apart
> C. 2 apart
> D. 1 apart
> E. the same
8. The answer to this question is the same as the answer to the question

> A. 1
> B. 2
> C. 3
> D. 4
> E. 5
9. The number of questions whose answers are consonants

> A. 3
> B. 4
> C. 5
> D. 6
> E. 7
10. The answer to this question is

> A. A
> B. B
> C. C
> D. D
> E. E

The objective of this chalenge is to write the **shortest program** that can **generate all the possible answers** and **check how many of them** (if any) satisfy what every one of the previous questions are asking (the output of the program would be the list of the answers that satisfy all the questions without contradiction).

The original test can be found here (although it is irrelevant for this chalenge).

# Answer
> 0 votes
# Pyth, 104 bytes

```
f!s[nhd-8xd3@.+d+3@d1nh@d2/d4nh@d3/d0!&/3@d4!-/d0/d@d4!-10x_d1@d5n@d6a4@.+d6n@d7@d@d7!+3@d8@ds/LdS3)^U5T

```

It... uh... takes a while to run. Try it online... if the server doesn't time out or run out of memory.

Explanation coming SoonTM. Prints all the valid solutions as a 0-based list (ten elements long in which `A` is represented by `0`, `B` by `1`, and so on).

This is a naive solution that can probably be golfed a lot. Just wanted to get something out there.

---
Tags: code-golf, game, combinatorics, permutations
---


# Question
Title: Function/macro that returns true if one of its arguments contains a call to itself
Write a function (or macro) that returns true **if and only if** at least one of its arguments contains a call to the function itself and **false otherwise**.

For example:

```
int a=function(); //a==false
int b=function(0); //b==false
int c=function(function(0)); //c==true
int d=function(3*function(1)+2); //d==true (weakly-typed language)
bool e=function(true||function(1)); //e==true (strongly-typed language)
```

EDIT: The function/macro may call other auxiliary function/macros.

EDIT 2: The function must take at least one argument, unless the language used behaves like C, where a function that takes no arguments may still be called with arguments nonetheless.

# Answer
> 11 votes
# Mathematica...

...was *made* for this.

```
SetAttributes[f, HoldAll]
f[x___] := ! FreeQ[Hold@x, _f]

f[]             (* False *)
f[0]            (* False *)
f[f[0]]         (* True *)
f[3 f[1] + 2]   (* True *)
f[True || f[1]] (* True *)

```

Everything is an expression, and an expression has a Head and a number of elements. So `1+2` is actually `Plus[1,2]`, and `{1,2}` is actually `List[1,2]`. This means we can match any expression for the head we're interested in - in this case the function `f` itself.

All we need to do is find a way to prevent Mathematica from evaluating the function arguments before the function is called, such that we can analyse the expression tree within the function. What's what `Hold` and `HoldAll` is for. Mathematica itself uses this to all over the place to provide special cases for certain implementations. E.g. if you call `Length[Permutations[list]]` it will never actually create all those permutations and waste loads of memory, but instead realise that it can simply compute this as `Length[list]!`.

Let's look at the code above in detail, using the last call `f[True || f[1]]` as an example. Normally, Mathematica will evaluate function arguments first, so this would simply short-circuit and call `f[True]`. However we have set

```
SetAttributes[f, HoldAll]

```

This instructs Mathematica not to evaluate the arguments, so the `FullForm` of the call (i.e. the internal expression tree, without any syntactic sugar) is

```
f[Or[True,f[1]]]

```

And the argument will actually be received by `f` in this form. The next issue is that, within `f`, as soon as we use the argument, Mathematica will again try to evaluate it. We can suppress this locally with `Hold@x` (syntactic sugar for `Hold[x]`). At this point we've got a handle on the original expression tree and do with it whatever we want.

To look for a pattern in an expression tree we can use `FreeQ`. It checks that a given pattern is not found in the expression tree. We use the patter `_f`, which matches any subexpression with head `f` (exactly what we're looking for). Of course, `FreeQ` returns the opposite of what we want, so we negate the result.

One more subtlety: I've specified the argument as `x___`, which is a sequence of 0 or more elements. This ensures that `f` works with any number of arguments. In the first call, `f[]` this means that `Hold@x` will simply become `Hold[]`. If there were multiple arguments, like `f[0,f[1]]`, then `Hold@x` would be `Hold[0,f[1]]`.

That's really all there is to it.

# Answer
> 6 votes
## C++11

Similar to expression templates we can propagate the fact that we did call the function inside a functions parameters list in its return type.

At first we need some helper classes and functions:

```
#include <iostream>

template <bool FunctionWasInParameters> struct FunctionMarker {
  operator bool() const { return FunctionWasInParameters; }

  operator int() const { return FunctionWasInParameters; }
};

template <bool... values> struct Or;

template <bool first, bool... values> struct Or<first, values...> {
  static constexpr bool value = first || Or<values...>::value;
};

template <> struct Or<> { static constexpr bool value = false; };

template <class T> struct is_FunctionMarker {
  static constexpr bool value = false;
};

template <bool B> struct is_FunctionMarker<FunctionMarker<B>> {
  static constexpr bool value = true;
};

#define OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(OPERATOR)                        \
  template <bool B, class T>                                                   \
  FunctionMarker<B> operator OPERATOR(FunctionMarker<B>, T) {                  \
    return {};                                                                 \
  }                                                                            \
  template <bool B, class T>                                                   \
  FunctionMarker<B> operator OPERATOR(T, FunctionMarker<B>) {                  \
    return {};                                                                 \
  }                                                                            \
  /* to break ambiguity by specialization */                                   \
  template <bool B, bool B2>                                                   \
  FunctionMarker<B || B2> operator OPERATOR(FunctionMarker<B>,                 \
                                            FunctionMarker<B2>) {              \
    return {};                                                                 \
  }

OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(|| )
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(+)
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(*)
// TODO: overload all other operators!

```

Now, we can use it for the exact same code as in the question:

```
template <class... Args>
auto function(Args... args)
    -> FunctionMarker<Or<is_FunctionMarker<Args>::value...>::value> {
  return {};
}

FunctionMarker<false> function() { return {}; }

int main() {
  int a = function();
  int b = function(0);
  int c = function(function(0));
  int d = function(3 * function(1) + 2);
  bool e = function(true || function(1));

  // clang-format off
  std::cout << a << "//a==false\n"
            << b << "//b==false\n"
            << c << "//c==true\n"
            << d << "//d==true (weakly-typed language)\n"
            << e << "//e==true (strongly-typed language)\n";
}

```

Output from ideone:

```
0//a==false
0//b==false
1//c==true
1//d==true (weakly-typed language)
1//e==true (strongly-typed language)

```

# Answer
> 4 votes
# C#

```
public PcgBool f(params object[] args)
{
    return args.Any(p => p is PcgBool);
}

public class PcgBool
{
    public PcgBool() { }
    public PcgBool(bool value)
    {
        Value = value;
    }

    private bool Value;

    public static implicit operator bool(PcgBool pcgBool)
    {
        return pcgBool.Value;
    }

    public static implicit operator PcgBool(bool value)
    {
        return new PcgBool(value);
    }
}

```

**Usage** (in LINQPad):

```
void Main()
{
    Console.WriteLine(f(1,2,f(3),4)); // True
    Console.WriteLine(f(1,2,3,"4")); // False
}

```

The trick here is to make `f` more aware of the parameters, by passing a custom type (`PcgBool`) which is kind-of-like a boolean.

P.S. I hope returning a custom type which is implicitly castable from and to a bool is not considered as cheating. Technically you can use the return value as if it was of bool type, and the question asked to "return true if and only if" etc., but never stated the return type must be bool.

# Answer
> 3 votes
# Lua

```
local x
local function f()
    local y = x
    x = true
    return y
end
debug.sethook(function()
        if debug.getinfo(2).func ~= f then
            x = false
        end
    end, "l")
print(f())
print(f(0))
print(f(f()))
print(f(f(0)))
print(f("derp" .. tostring(f())))

```

# Answer
> 3 votes
**C++11 TMP**

This one is a bit longer. Because of some limitations in C++ templates I had to do everything with types. Thus "True" as well as the numbers were turned into bool and int. Also The operations +, - and || were turned into add, mul and or\_.

I hope this still qualifies as a valid answer.

```
template <typename... Args>
struct foo;

template <>
struct foo<>
{
    static bool const value = false;
};

template <typename T>
struct is_foo
{
    static bool const value = false;
};

template <typename... Args>
struct is_foo<foo<Args...>>
{
    static bool const value = true;
};

template <typename T>
struct is_given_foo
{
    static bool const value = false;
};

template <template <typename...> class T, typename... Args>
struct is_given_foo<T<Args...>>
{
    static bool const value = foo<Args...>::value;
};

template <typename Head, typename... Tail>
struct foo<Head, Tail...>
{
    static bool const value = is_foo<Head>::value || is_given_foo<Head>::value || foo<Tail...>::value;
};

template <typename... Args>
struct add {};

template <typename... Args>
struct mul {};

template <typename... Args>
struct or_ {};

static_assert(foo<>::value == false, "int a=function(); //a==false");
static_assert(foo<int>::value == false, "int b=function(0); //b==false");
static_assert(foo<foo<int>>::value == true, "int c=function(function(0)); //c==true");
static_assert(foo<add<mul<int, foo<int>>, int>>::value == true, "int d=function(3*function(1)+2); //d==true (weakly-typed language)");
static_assert(foo<or_<bool,foo<int>>>::value == true, "bool e=function(true||function(1)); //e==true (strongly-typed language)");

// just for the sake of C++
int main()
{
    return 0;
}

```

# Answer
> 2 votes
# C

I don't think it can be done with procedures, but we can always (ab)use macros.

```
#include <stdio.h>
#define f(x) ((max_depth = ++depth), (x), (depth-- < max_depth))

int depth = 0;
int max_depth = 0;

char* bool(int x) { // Helper - not necessary for solution
  return x ? "true" : "false";
}

int main() {
  printf("f(1): %s\n", bool(f(1)));
  printf("f(f(1)): %s\n", bool(f(f(1))));
  printf("f(bool(f(1))): %s\n", bool(f(bool(f(1)))));
  printf("f(printf(\"f(1): %%s\\n\", bool(f(1)))): %s\n", bool(printf("f(1): %s\n", bool(f(1)))));
}

```

This outputs:

```
f(1): false
f(f(1)): true
f(bool(f(1))): true
f(1): false
f(printf("f(1): %s\n", bool(f(1)))): true

```

Our macro `f` keeps track of the current depth, and the maximum depth achieved since it was invoked. If the latter is greater than the former, then it has been called recursively.

# Answer
> 2 votes
# C, 13

```
#define F(X)0

```

The argument is never expanded, so it cannot call any macros. It is nothing more than a bunch of plain text. Thus, the answer is always false.

# Answer
> 1 votes
# C

```
#include <stdio.h>

int a, b;
#define foo(x) (b=a++,(void)x,a--,!!b)

int
main(int argc, char **argv)
{
        printf("%d\n", foo(1));
        printf("%d\n", foo(0));
        printf("%d\n", foo(foo(1)));
        printf("%d\n", foo(foo(foo(1))));
        return 0;
}

```

We can count the recursion depth in the macro. We then overwrite the return value of the outer macro in the inner macro. `!!b` is to normalize the return value to a boolean. The preprocessed code ends up like this:

```
int a, b;

int
main(int argc, char **argv)
{
 printf("%d\n", (b=a++,(void)1,a--,!!b));
 printf("%d\n", (b=a++,(void)0,a--,!!b));
 printf("%d\n", (b=a++,(void)(b=a++,(void)1,a--,!!b),a--,!!b));
 printf("%d\n", (b=a++,(void)(b=a++,(void)(b=a++,(void)1,a--,!!b),a--,!!b),a--,!!b));
 return 0;
}

```

# Answer
> 1 votes
# C

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BLAH(x) (strncmp( "BLAH(", #x, strlen("BLAH(")) == 0)

int main(int argc, char** argv)
{
  printf("%d\n", BLAH(1));
  printf("%d\n", BLAH("1234"));
  printf("%d\n", BLAH("BLAH"));
  printf("%d\n", BLAH(BLAHA));
  printf("%d\n", BLAH(BLAHB()));
  printf("%d\n", BLAH(BLAH));
  printf("%d\n", BLAH(BLAH()));
  printf("%d\n", BLAH(BLAH("1234")));
  return 0;
}

```

The macro compares if its argument starts with "BLAH(".

# Answer
> 1 votes
# Algol 60

Here's a `boolean procedure` that does what the question asks for (note: Algol 60 is defined in terms of a list of tokens without fixing syntax for them, the below uses Marst syntax to represent the individual tokens that make up the program):

```
boolean procedure recursion detector(n);
  boolean n;
  begin
    own boolean nested, seen nested;
    boolean was nested, retval;
    was nested := nested;
    begin if nested then seen nested := true end;
    nested := true;
    retval := n; comment "for the side effects, we ignore the result";
    nested := was nested;
    retval := seen nested;
    begin if ! nested then seen nested := false end;
    recursion detector := retval
  end;

```

## Verification

Here's the test code I used:

```
procedure outboolean(c, b);
  integer c;
  boolean b;
  begin
    if b then outstring(c, "true\n") else outstring(c, "false\n")
  end;

begin
  outboolean(1, recursion detector(false));
  outboolean(1, recursion detector(true));
  outboolean(1, recursion detector(recursion detector(false)));
  outboolean(1, recursion detector(false | recursion detector(true)));
  outboolean(1, recursion detector(false & recursion detector(true)));
  outboolean(1, recursion detector(recursion detector(recursion detector(false))))
end

```

As expected, the output is:

```
false
false
true
true
true             comment "because & does not short-circuit in Algol 60";
true

```

## Explanation

Algol 60 has a different evaluation order from most languages, which has a logic of its own, and is actually much more powerful and general than the typical evaluation order, but is fairly hard for humans to get their head around (and also fairly hard for computers to implement efficiently, which is why it got changed for Algol 68). This allows for a solution with no sort of cheating (the program doesn't need to look at the parse tree or anything like that, and unlike almost all the other solutions here, this would work just fine if the nested call were made via an FFI).

I also decided to show off a few other quirks of the language. (Notably, variable names can contain whitespace; this is fairly useful for readability, because they *can't* contain underscores. I also love the fact that the comment indicator is the literal word `comment` in most syntax encodings. Algol 68 found this fairly awkward for short comments, and introduced `¢` as an alternative. The quotes around the comment body aren't normally needed, I just add them for clarity and to prevent the comment accidentally ending when I type a semicolon.) I actually really like the broad concepts of the language (if not the details), but it's so verbose that I rarely get to use it on PPCG.

The main way in which Algol 60 differs from the languages it inspired (such as Algol 68, and indirectly C, Java, etc; people who know K&R C will probably recognise this syntax for functions) is that a function argument is treated a bit like a little lambda of its own; for example, if you give the argument `5` to a function that's just the number 5, but if you give it the argument `x+1` you get exactly what you specified, the concept of "`x` plus 1", rather than the *result* of `x` plus 1. The difference here is that if `x` changes, then attempts to evaluate the function argument in question will see the *new* value of `x`. If a function argument isn't evaluated inside the function, it won't be evaluated outside the function either; likewise, if it's evaluated multiple times inside the function, it'll be evaluated separately each time (assuming that this can't be optimised out). This means that it's possible to do things like capture the functionality of, say, `if` or `while` in a function.

In this program, we're exploiting the fact that if a call to a function appears in an argument to that function, that means that the function will run recursively (because the argument is evaluated at exactly the point or points that the function evaluates it, no earlier or later, and this must necessarily be inside the function body). This reduces the problem to detecting if the function is running recursively, which is much easier; all you need is a thread-local variable that senses if there's a recursive call (plus, in this case, another one to communicate information back the other way). We can use a static variable (i.e. `own`) for the purpose, because Algol 60 is single-threaded. All we have to do after that is to put everything back the way it was, so that the function will function correctly if called multiple times (as required by PPCG rules).

The function doesn't return the desired value from the inside calls at the moment (at least if you assume they should look for self-calls in only *their* arguments, rather than counting themselves); making that work is fairly easy using the same general principles, but more complex and would obscure the workings of the function. If that's deemed necessary to comply with the question, it shouldn't be too hard to change.

# Answer
> 0 votes
## Java

```
public class FuncOFunc{

private static int count = 0;

public static void main(String[] args){

    System.out.println("First\n" + function());
    reset();

    System.out.println("Second\n" + function(1));
    reset();

    System.out.println("Third\n" + function(function(1)));
    reset();

    System.out.println("Fourth\n" + function(3*function(1)+2));
    reset();

    System.out.println("Fifth\n" + function(function(1), function(), 4));
}

/**
 * @param args
 */
private static int function(Object...args) {
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    count+=stackTraceElements.length;
    if(count>3) return 1;
    else return 0;
}

static void reset(){
    count = 0;
}
}

```

can `reset()` be counted as auxiliary?

**Output:**

```
First
0
Second
0
Third
1
Fourth
1
Fifth
1

```

## EDIT

Here is another version that doesn't use the `reset()` method, but a lot of madness. It creates and compiles at runtime the above code with the call to the function passed as an argument in stdin. I wanted a more elegant solution but sadly I don't have too much time for this :(

To run it simply call for example `javac FuncOFunc.java function(function(1),function(),4)`.

```
import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class FuncOFunc {
    public static void main(String[] args) throws Exception {
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
        File jf = new File("FuncOFuncOFunc.java");
        PrintWriter pw = new PrintWriter(jf);
        pw.println("public class FuncOFuncOFunc{"
                + "public static void main(){ "
                + "     System.out.println("+ args[0] +");"
                + "}"
                + "     private static int function(Object...args)     {"
                + "         StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();"
                + "         if(stackTraceElements.length>3) return 1;"
                + "         else return 0;"
                + "     }"
                + "}");
    pw.close();
    Iterable<? extends JavaFileObject> fO = sjfm.getJavaFileObjects(jf);
    if(!jc.getTask(null,sjfm,null,null,null,fO).call()) {
        throw new Exception("compilation failed");
    }
    URL[] urls = new URL[]{new File("").toURI().toURL()};
    URLClassLoader ucl = new URLClassLoader(urls);
    Object o= ucl.loadClass("FuncOFuncOFunc").newInstance();
    o.getClass().getMethod("main").invoke(o);
    ucl.close();
}
}

```

# Answer
> 0 votes
# Python

```
import ast, inspect

def iscall(node, name, lineno=None):
    return isinstance(node, ast.Call) \
            and (node.lineno == lineno or lineno is None) \
            and hasattr(node.func, 'id') \
            and node.func.id == name

def find_call(node, name, lineno):
    for node in ast.walk(node):
        if iscall(node, name, lineno):
            return node

def is_call_in_args(call):
    descendants = ast.walk(call);
    name = next(descendants).func.id
    return any(map(lambda node: iscall(node, name), descendants))

def function(*args):
    this = inspect.currentframe()
    _, _, funcname, _, _ = inspect.getframeinfo(this)
    outer = inspect.getouterframes(this)[1]
    frame, filename, linenum, _, context, cindex = outer
    module = ast.parse(open(filename).read())
    call = find_call(module, funcname, linenum)
    return is_call_in_args(call)

if __name__ == '__main__':

    print("Works with these:")
    assert(function() == False)
    assert(function(3*function(1)+2) == True)
    assert(function(0) == False)
    assert(function(function(0)) == True)
    assert(function(True or function(1) == True))

    print("Does not work with multiple expressions on the same line:")
    assert(function(function()) == False); function()
    function(); assert(function(function()) == False)

```

Save it as `selfarg.py` and run it or `from selfarg import function` in another script. It does not work in the repl.

Using the current and outer stack frames `function` obtains its name and place of call (file and line number). It then opens the obtained file and parses it into an abstract syntax tree. It skips to the function call identified by the line number and inspects if it has another function call with the same name in its arguments.

*edit*: It's OK with python2 too. Changed python3 to python in the title.

---
Tags: popularity-contest, function
---


# Question
Title: Evaluate the Riemann Zeta Function at a Complex Number
# Introduction

I found this question that was closed because it was unclear, yet it was a nice idea. I'll do my best to make this into a clear challenge.

The Riemann Zeta function is a special function that is defined as the analytical continuation of

to the complex plane. There are many equivalent formulas for it which makes it interesting for code golf.

# Challenge

Write a program that takes 2 floats as input (the real and imaginary part of a complex number) and evaluates the Riemann Zeta function at that point.

**Rules**

* Input and output via console OR function input and return value
* Built in complex numbers are not allowed, use floats (number, double, ...)
* No mathematical functions except `+ - * / pow log` and real valued trig functions (if you want to integrate, use the gamma function, ... you must include this functions definition in the code)
* Input: 2 floats
* Output: 2 floats
* Your code must contain value that gives theoretically arbitrary precision when made arbitrary large/small
* The behaviour at input 1 is not important (this is the only pole of this function)

Shortest code in bytes wins!

# Example Input and Output

Input:

> 2, 0

Output:

> 1.6449340668482266, 0

Input:

> 1, 1

Output:

> 0.5821580597520037, -0.9268485643308071

Input:

> -1, 0

Output:

> -0.08333333333333559, 0

# Answer
> 8 votes
# Python - 385

This is a straightforward implementation of Equation 21 from http://mathworld.wolfram.com/RiemannZetaFunction.html This uses Python's convention for optional arguments; if you want to specify a precision, you can pass a third argument to the function, otherwise it uses 1e-24 by default.

```
import numpy as N
def z(r,i,E=1e-24):
 R=0;I=0;n=0;
 while(True):
  a=0;b=0;m=2**(-n-1)
  for k in range(0,n+1):
   M=(-1)**k*N.product([x/(x-(n-k))for x in range(n-k+1,n+1)]);A=(k+1)**-r;t=-i*N.log(k+1);a+=M*A*N.cos(t);b+=M*A*N.sin(t)
  a*=m;b*=m;R+=a;I+=b;n+=1
  if a*a+b*b<E:break
 A=2**(1-r);t=-i*N.log(2);a=1-A*N.cos(t);b=-A*N.sin(t);d=a*a+b*b;a=a/d;b=-b/d
 print(R*a-I*b,R*b+I*a)

```

# Answer
> 4 votes
# Python 3, ~~303~~ ~~297~~ 298 bytes

This answer is based on R.T.'s Python answer with several modifications:

* First, `Binomial(n, k)` is defined as `p = p * (n-k) / (k+1)` which changes `Binomial(n,k)` to `Binomial(n,k+1)` with every pass of the for loop.
* Second, `(-1)**k * Binomial(n,k)` became `p = p * (k-n) / (k+1)` which flips the sign at every step of the for loop.
* Third, the `while` loop has been changed to immediately check if `a*a + b*b < E`.
* Fourth, the bitwise not operator `~` is used in several places where they would aid in golfing, using identities such as `-n-1 == ~n`, `n+1 == -~n`, and `n-1 == ~-n`. This only works for ints, however, and not floats.

Several other small modifications were made for better golfing, such as putting the `for` loop on one line and the call to `print` on one line with the code before it.

Golfing suggestions welcome. Try it online!

**Edit:** -6 bytes from a number of small changes.

**Edit:** +1 byte from fixing an error with float handling, with thanks to mostlyWright for pointing out the error.

```
import math as N
def z(r,i,E=1e-40):
 R=I=n=0;a=b=1
 while a*a+b*b>E:
  a=b=0;p=1;m=2**~n
  for k in range(1,n+2):M=p/k**r;p*=(k-1-n)/k;t=-i*N.log(k);a+=M*N.cos(t);b+=M*N.sin(t)
  a*=m;b*=m;R+=a;I+=b;n+=1
 A=2**(1-r;t=-i*N.log(2);x=1-A*N.cos(t);y=A*N.sin(t);d=x*x+y*y;return(R*x-I*y)/d,(R*y+I*x)/d

```

# Answer
> 1 votes
# Axiom, ~~413 315~~ 292 bytes

```
p(n,a,b)==(x:=log(n^b);y:=n^a;[y*cos(x),y*sin(x)]);z(a,b)==(r:=[0.,0.];e:=10^-digits();t:=p(2,1-a,-b);y:=(1-t.1)^2+t.2^2;y=0=>[];m:=(1-t.1)/y;q:=t.2/y;n:=0;repeat(w:=2^(-n-1);abs(w)<e=>break;r:=r+w*reduce(+,[(-1)^k*binomial(n,k)*p(k+1,-a,-b) for k in 0..n]);n:=n+1);[r.1*m-q*r.2,m*r.2+r.1*q])

```

This would implement too the equation 21 from http://mathworld.wolfram.com/RiemannZetaFunction.html The above should be the one iterpreted Axiom function z(a,b) here 16x slower than this below function Zeta(a,b)\[that should be the one compiled\] all ungolfed and commented \[1 second for Zeta() against 16 seconds for z() for one value of 20 digits afther the float point\]. For the digit question, one would choose the precision by calling digits(); function, for example digits(10);z(1,1) should print 10 digits after the point, but digits(50);z(1,1) should print 50 digits after the point.

```
-- elevImm(n,a,b)=n^(a+i*b)=r+i*v=[r,v]
elevImm(n:INT,a:Float,b:Float):Vector Float==(x:=log(n^b);y:=n^a;[y*cos(x),y*sin(x)]::Vector Float);

--                      +oo               n
--                      ---              ---
--             1        \       1        \            n
--zeta(s)= ---------- * /     ------  *  /    (-1)^k(   )(k+1)^(-s)
--          1-2^(1-s)   ---n  2^(n+1)    ---k         k
--                       0                0

Zeta(a:Float,b:Float):List Float==
  r:Vector Float:=[0.,0.]; e:=10^-digits()

  -- 1/(1-2^(1-s))=1/(1-x-i*y)=(1-x+iy)/((1-x)^2+y^2)=(1-x)/((1-x)^2+y^2)+i*y/((1-x)^2+y^2)

  t:=elevImm(2,1-a,-b);
  y:=(1-t.1)^2+t.2^2;
  y=0=>[]
  m:=(1-t.1)/y;
  q:=t.2/y
  n:=0
  repeat
     w:=2^(-n-1)
     abs(w)<e=>break  --- this always terminate because n increase
     r:=r+w*reduce(+,[(-1)^k*binomial(n,k)*elevImm(k+1,-a,-b) for k in 0..n])
     n:=n+1
  -- (m+iq)(r1+ir2)=(m*r1-q*r2)+i(m*r2+q*r1)
  [r.1*m-q*r.2,m*r.2+r.1*q]

this is one test for the z(a,b) function above:

(10) -> z(2,0)
   (10)  [1.6449340668 482264365,0.0]
                                              Type: List Expression Float
(11) -> z(1,1)
   (11)  [0.5821580597 520036482,- 0.9268485643 3080707654]
                                              Type: List Expression Float
(12) -> z(-1,0)
   (12)  [- 0.0833333333 3333333333 3,0.0]
                                              Type: List Expression Float
(13) -> z(1,0)
   (13)  []

```

---
Tags: code-golf, math, complex-numbers, calculus
---


# Question
Title: Optimize sorting, using "Sub-vector reversals"
This is a challenge where the objective is to sort a vector into ascending order using the fewest reversals. Your algorithm can only sort the vector using "sub-vector reversals"1, but it can use other operations for arithmetic operations, loops, checking if it's sorted etc. **The number of sub-vector reversals your algorithm performs is its score.**

---

1**A "sub-vector reversal":**

* Select a range of numbers in the vector, and reverse the elements in that range.

To give a simple example, if you start with the vector `{4,3,2,1}`, then you can sort it in a lot of different ways:

1. Reverse the entire vector. This is obviously the shortest approach as it only requires one reversal: `{4,3,2,1} -> {1,2,3,4}`
2. You can do a version of the bubble sort, which requires 6 reversals: `{4,3,2,1} -> {3,4,2,1} -> {3,2,4,1} -> {2,3,4,1} -> {2,3,1,4} -> {2,1,3,4} -> {1,2,3,4}`
3. You can start with the first 3 elements, then the three last, and finally the two first and the two last, which requires 4 swaps: `{4,3,2,1} -> {2,3,4,1} -> {2,1,4,3} -> {1,2,4,3} -> {1,2,3,4}`
4. ... and so on. There are an infinite amount of options available (you may repeat any operation if you like).

---

**Rules and requirements:**

* Your code must finish in less than one minute for a list with 100 numbers. You may time this yourself, but please play fair2.
* You must store the start and end indices of all swaps you perform, so that the solution might be verified. (I'll explain what this means below).
* The code must be deterministic.
* You can take the input on any format you want: Numeric vector, linked-list, array with length ... whatever you like.
* You can do whatever you like on a *copy* of the vector. That includes attempting different reversals and check which is most efficient. Brute-forcing is perfectly fine, but stick to the time limit.
* The score is the total number of flips for the 5 test vectors. Tie-breaker will the date stamp.

---

**Example:**

```
4 1 23 21 49 2 7 9 2 |  Initial vector / list
4 1 **2 9 7 2 49 21 23** |  (2, 8)  (flipped the elements between indices 2 and 8)
4 1 2 **2 7 9** 49 21 23 |  (3, 5)
4 1 2 2 7 9 **23 21 49** |  (6, 8)
4 1 2 2 7 9 **21 23** 49 |  (6, 7)
**2 2 1 4** 7 9 21 23 49 |  (0, 3)
**1 2 2** 4 7 9 21 23 49 |  (0, 2)

```

The score would be 6, since you performed 6 reversals. You must store (not print) the indices listed on the right side on a suitable format that can easily be printed/outputted for verification purposes.

**Test vectors:**

```
133, 319, 80, 70, 194, 333, 65, 21, 345, 142, 82, 491, 92, 167, 281, 386, 48, 101, 394, 130, 111, 139, 214, 337, 180, 24, 443, 35, 376, 13, 166, 59, 452, 429, 406, 256, 133, 435, 446, 304, 350, 364, 447, 471, 236, 177, 317, 342, 294, 146, 280, 32, 135, 399, 78, 251, 467, 305, 366, 309, 162, 473, 27, 67, 305, 497, 112, 399, 103, 178, 386, 343, 33, 134, 480, 147, 466, 244, 370, 140, 227, 292, 28, 357, 156, 367, 157, 60, 214, 280, 153, 445, 301, 108, 77, 404, 496, 3, 226, 37

468, 494, 294, 42, 19, 23, 201, 47, 165, 118, 414, 371, 163, 430, 295, 333, 147, 336, 403, 490, 370, 128, 261, 91, 173, 339, 40, 54, 331, 236, 255, 33, 237, 272, 193, 91, 232, 452, 79, 435, 160, 328, 47, 179, 162, 239, 315, 73, 160, 266, 83, 451, 317, 255, 491, 70, 18, 275, 339, 298, 117, 145, 17, 178, 232, 59, 109, 271, 301, 437, 63, 103, 130, 15, 265, 281, 365, 444, 180, 257, 99, 248, 378, 158, 210, 466, 404, 263, 29, 117, 417, 357, 44, 495, 303, 428, 146, 215, 164, 99

132, 167, 361, 145, 36, 56, 343, 330, 14, 412, 345, 263, 306, 462, 101, 453, 364, 389, 432, 32, 200, 76, 268, 291, 35, 13, 448, 188, 11, 235, 184, 439, 175, 159, 360, 46, 193, 440, 334, 128, 346, 192, 263, 466, 175, 407, 340, 393, 231, 472, 122, 254, 451, 485, 257, 67, 200, 135, 132, 421, 205, 398, 251, 286, 292, 488, 480, 56, 284, 484, 157, 264, 459, 6, 289, 311, 116, 138, 92, 21, 307, 172, 352, 199, 55, 38, 427, 214, 233, 404, 330, 105, 223, 495, 334, 169, 168, 444, 268, 248

367, 334, 296, 59, 18, 193, 118, 10, 276, 180, 242, 115, 233, 40, 225, 244, 147, 439, 297, 115, 354, 248, 89, 423, 47, 458, 64, 33, 463, 142, 5, 13, 89, 282, 186, 12, 70, 289, 385, 289, 274, 136, 39, 424, 174, 186, 489, 73, 296, 39, 445, 308, 451, 384, 451, 446, 282, 419, 479, 220, 35, 419, 161, 14, 42, 321, 202, 30, 32, 162, 444, 215, 218, 102, 140, 473, 500, 480, 402, 1, 1, 79, 50, 54, 111, 189, 147, 352, 61, 460, 196, 77, 315, 304, 385, 275, 65, 145, 434, 39

311, 202, 126, 494, 321, 330, 290, 28, 400, 84, 6, 160, 432, 308, 469, 459, 80, 48, 292, 229, 191, 240, 491, 231, 286, 413, 170, 486, 59, 54, 36, 334, 135, 39, 393, 201, 127, 95, 456, 497, 429, 139, 81, 293, 359, 477, 404, 129, 129, 297, 298, 495, 424, 446, 57, 296, 10, 269, 350, 337, 39, 386, 142, 327, 22, 352, 421, 32, 171, 452, 2, 484, 337, 359, 444, 246, 174, 23, 115, 102, 427, 439, 71, 478, 89, 225, 7, 118, 453, 350, 109, 277, 338, 474, 405, 380, 256, 228, 277, 3

```

I'm fairly certain that finding an optimal solution is NP-hard (since regular pancake sorting is).

2Yes, people with very fast computers might have a benefit, due to the time limit of one minute. After much discussion I've figured it's best if everyone does their own benchmarking, it's not a fastest code challenge.

# Answer
> 7 votes
## Java, genetic-ish algorithm, 80+81+79+78+80=398 (previously ~~418~~)

After trying a bunch of different ideas and mostly failing, I settled on this algorithm: start with the input array, try all possible reversals and keep a certain number of results with the smallest number of runs, then do the same for those results, until we get a sorted array.

By "runs" I mean maximal subarrays that appear exactly or reversed in the sorted array. Basically they are maximal sorted subarrays, but in case of repeated elements, the number of elements in the middle should match. E.g. if the sorted array is `2, 2, 3, 3, 4, 4` then `4, 3, 3, 2` is a run but `2, 2, 3, 4` is not (and neither is `2, 3, 2`).

In this version I optimized the algorithm to reverse only at run boundaries and only if a reversed run can be joined with a newly-adjacent run. Also, the runs are adjusted and joined at each step, to avoid recalculating them from the modified array. This allowed me to increase the "population size" from 30 to about 3000, and to run multiple simulations at various sizes.

```
import java.io.*;
import java.util.*;

public class SubReversal {
    static int n;
    static int[] a;
    static int[] srt;
    static List<int[]> rev;
    static Map<Integer, Integer> idx;
    static Map<Integer, Integer> count;

    static final int NB = 2000;
    static State[] best = new State[NB + 1];
    static int ns;

    static class Run {
        int start;
        int end;
        int dir;
        int nstart = 1;
        int nend = 1;

        Run(final int start) {
            this.start = start;
        }

        Run(final Run r) {
            start = r.start;
            end = r.end;
            dir = r.dir;
            nstart = r.nstart;
            nend = r.nend;
        }

        Run copy() {
            return new Run(this);
        }

        Run reverse() {
            int t = start;
            start = end;
            end = t;
            t = nstart;
            nstart = nend;
            nend = t;
            dir = -dir;
            return this;
        }

        boolean canJoin(final Run r) {
            if (dir * r.dir == -1) {
                return false;
            }
            final int t = idx.get(a[r.start]) - idx.get(a[end]);
            if (Math.abs(t) > 1) {
                return false;
            }
            if (t != 0 && dir + r.dir != 0 && t != dir && t != r.dir) {
                return false;
            }
            if (t == 0) {
                if (dir * r.dir == 0) {
                    return true;
                }
                return nend + r.nstart == count.get(a[end]);
            }
            return (dir == 0 || nend == count.get(a[end])) && (r.dir == 0 || r.nstart == count.get(a[r.start]));
        }

        Run join(final Run r) {
            if (a[start] == a[r.start]) {
                nstart += r.nstart;
            }
            if (a[end] == a[r.end]) {
                nend += r.nend;
            }
            else {
                nend = r.nend;
            }
            end = r.end;
            if (dir == 0) {
                dir = r.dir;
            }
            if (dir == 0 && a[start] != a[end]) {
                dir = idx.get(a[end]) - idx.get(a[start]);
            }
            return this;
        }

        @Override
        public String toString() {
            return start + "(" + nstart + ") - " + end + '(' + nend + "): " + dir;
        }
    }

    static class State implements Comparable<State> {
        int[] b;
        int[] rv;
        State p;
        List<Run> runs;

        public State(final int[] b, final int[] rv, final State p, final List<Run> runs) {
            this.b = Arrays.copyOf(b, b.length);
            this.rv = rv;
            this.p = p;
            this.runs = runs;
        }

        @Override
        public int compareTo(final State o) {
            return runs.size() - o.runs.size();
        }

        @Override
        public String toString() {
            return Arrays.toString(b) + " - " + Arrays.toString(rv) + " - " + runs.size();
        }

        int getCount() {
            return p == null ? 0 : p.getCount() + 1;
        }
    }

    static void reverse(int x, int y) {
        while (x < y) {
            int t = a[x];
            a[x] = a[y];
            a[y] = t;
            x++;
            y--;
        }
    }

    static List<Run> runs() {
        final List<Run> l = new ArrayList<>();
        Run run = new Run(0);
        for (int i = 1; i < n; ++i) {
            final int t = idx.get(a[i]) - idx.get(a[i - 1]);
            if (Math.abs(t) > 1) {
                run.end = i - 1;
                l.add(run);
                run = new Run(i);
            }
            else if (t == 0) {
                run.nend++;
                if (run.dir == 0) {
                    run.nstart++;
                }
            }
            else {
                if (run.dir == 0) {
                    run.dir = t;
                }
                else if (run.dir != t || run.nend != count.get(a[i - 1])) {
                    run.end = i - 1;
                    l.add(run);
                    run = new Run(i);
                }
                run.nend = 1;
            }
        }
        run.end = n - 1;
        l.add(run);
        return l;
    }

    static void show() {
        if (!Arrays.equals(a, srt)) {
            System.out.println("bug!");
            System.out.println(Arrays.toString(a));
            throw new RuntimeException();
        }
        System.out.println("Sorted: " + Arrays.toString(a));
        System.out.println(rev.size() + " reversal(s):");
        for (int[] x : rev) {
            System.out.println(Arrays.toString(x));
        }
    }

    static void sort() {
        State bestest = null;
        final int[] a1 = Arrays.copyOf(a, n);
        final int[] sizes = {10, 20, 30, 50, 100, 200, 300, 500, 1000, 2000};

        for (int nb : sizes) {
            System.arraycopy(a1, 0, a, 0, n);
            ns = 1;
            best[0] = new State(a, null, null, runs());
            while (best[0].runs.size() > 1) {
                final State[] s = Arrays.copyOf(best, ns);
                ns = 0;
                for (State x : s) {
                    System.arraycopy(x.b, 0, a, 0, n);
                    final int m = x.runs.size();
                    for (int i = 0; i < m; ++i) {
                        for (int j = i; j < m; ++j) {
                            boolean b = false;
                            if (i > 0) {
                                final Run r = x.runs.get(j);
                                r.reverse();
                                b = x.runs.get(i - 1).canJoin(r);
                                r.reverse();
                            }
                            if (!b && j < m - 1) {
                                final Run r = x.runs.get(i);
                                r.reverse();
                                b = r.canJoin(x.runs.get(j + 1));
                                r.reverse();
                            }
                            if (!b) {
                                continue;
                            }
                            final List<Run> l = new ArrayList<>(x.runs);
                            final int rstart = l.get(i).start;
                            final int rend = l.get(j).end;
                            final int t = rstart + rend;
                            reverse(rstart, rend);
                            for (int k = i; k <= j; ++k) {
                                final Run r = x.runs.get(i + j - k).copy().reverse();
                                r.start = t - r.start;
                                r.end = t - r.end;
                                l.set(k, r);
                            }
                            if (j < m - 1 && l.get(j).canJoin(l.get(j + 1))) {
                                l.get(j).join(l.get(j + 1));
                                l.remove(j + 1);
                            }
                            if (i > 0 && l.get(i - 1).canJoin(l.get(i))) {
                                l.set(i - 1, l.get(i - 1).copy().join(l.get(i)));
                                l.remove(i);
                            }

                            if (ns < nb || l.size() < best[ns - 1].runs.size()) {
                                best[ns++] = new State(a, new int[]{rstart, rend}, x, l);
                                Arrays.sort(best, 0, ns);
                                if (ns > nb) {
                                    ns = nb;
                                }
                            }
                            reverse(rstart, rend);
                        }
                    }
                }

                if (ns == 0) {
                    for (State x : s) {
                        System.arraycopy(x.b, 0, a, 0, n);
                        final List<Run> l = new ArrayList<>(x.runs);
                        final int rstart = l.get(0).start;
                        final int rend = l.get(0).end;
                        final int t = rstart + rend;
                        reverse(rstart, rend);
                        final Run r = x.runs.get(0).copy().reverse();
                        r.start = t - r.start;
                        r.end = t - r.end;
                        l.set(0, r);

                        best[ns++] = new State(a, new int[]{rstart, rend}, x, l);
                        reverse(rstart, rend);
                    }
                    Arrays.sort(best, 0, ns);
                }
            }
            State r = null;
            for (int i = 0; i < ns; ++i) {
                if (Arrays.equals(best[i].b, srt)) {
                    r = best[i];
                    break;
                }
            }
            if (r == null) {
                final State x = best[0];
                System.arraycopy(x.b, 0, a, 0, n);
                reverse(0, n - 1);
                r = new State(a, new int[]{0, n - 1}, x, runs());
            }
            if (!Arrays.equals(r.b, srt)) {
                throw new RuntimeException("bug");
            }

            if (bestest == null || r.getCount() < bestest.getCount()) {
                bestest = r;
            }
        }

        while (bestest.p != null) {
            rev.add(bestest.rv);
            bestest = bestest.p;
        }
        Collections.reverse(rev);
        a = a1;
        for (int[] x : rev) {
            reverse(x[0], x[1]);
        }
        if (!Arrays.equals(a, srt)) {
            throw new RuntimeException("bug");
        }
    }

    static void init(final String s) {
        final String[] b = s.split(s.contains(",") ? "," : " ");
        n = b.length;
        a = new int[n];
        count = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            a[i] = Integer.parseInt(b[i].trim());
            final Integer x = count.get(a[i]);
            count.put(a[i], x == null ? 1 : x + 1);
        }
        srt = Arrays.copyOf(a, n);
        Arrays.sort(srt);
        idx = new HashMap<>();
        int j = 0;
        for (int i = 0; i < n; ++i) {
            if (i == 0 || srt[i] != srt[i - 1]) {
                idx.put(srt[i], j++);
            }
        }
        rev = new ArrayList<>();
    }

    static void test5() {
        final String[] t = {"133, 319, 80, 70, 194, 333, 65, 21, 345, 142, 82, 491, 92, 167, 281, 386, 48, 101, 394, 130, 111, 139, 214, 337, 180, 24, 443, 35, 376, 13, 166, 59, 452, 429, 406, 256, 133, 435, 446, 304, 350, 364, 447, 471, 236, 177, 317, 342, 294, 146, 280, 32, 135, 399, 78, 251, 467, 305, 366, 309, 162, 473, 27, 67, 305, 497, 112, 399, 103, 178, 386, 343, 33, 134, 480, 147, 466, 244, 370, 140, 227, 292, 28, 357, 156, 367, 157, 60, 214, 280, 153, 445, 301, 108, 77, 404, 496, 3, 226, 37",
                "468, 494, 294, 42, 19, 23, 201, 47, 165, 118, 414, 371, 163, 430, 295, 333, 147, 336, 403, 490, 370, 128, 261, 91, 173, 339, 40, 54, 331, 236, 255, 33, 237, 272, 193, 91, 232, 452, 79, 435, 160, 328, 47, 179, 162, 239, 315, 73, 160, 266, 83, 451, 317, 255, 491, 70, 18, 275, 339, 298, 117, 145, 17, 178, 232, 59, 109, 271, 301, 437, 63, 103, 130, 15, 265, 281, 365, 444, 180, 257, 99, 248, 378, 158, 210, 466, 404, 263, 29, 117, 417, 357, 44, 495, 303, 428, 146, 215, 164, 99",
                "132, 167, 361, 145, 36, 56, 343, 330, 14, 412, 345, 263, 306, 462, 101, 453, 364, 389, 432, 32, 200, 76, 268, 291, 35, 13, 448, 188, 11, 235, 184, 439, 175, 159, 360, 46, 193, 440, 334, 128, 346, 192, 263, 466, 175, 407, 340, 393, 231, 472, 122, 254, 451, 485, 257, 67, 200, 135, 132, 421, 205, 398, 251, 286, 292, 488, 480, 56, 284, 484, 157, 264, 459, 6, 289, 311, 116, 138, 92, 21, 307, 172, 352, 199, 55, 38, 427, 214, 233, 404, 330, 105, 223, 495, 334, 169, 168, 444, 268, 248",
                "367, 334, 296, 59, 18, 193, 118, 10, 276, 180, 242, 115, 233, 40, 225, 244, 147, 439, 297, 115, 354, 248, 89, 423, 47, 458, 64, 33, 463, 142, 5, 13, 89, 282, 186, 12, 70, 289, 385, 289, 274, 136, 39, 424, 174, 186, 489, 73, 296, 39, 445, 308, 451, 384, 451, 446, 282, 419, 479, 220, 35, 419, 161, 14, 42, 321, 202, 30, 32, 162, 444, 215, 218, 102, 140, 473, 500, 480, 402, 1, 1, 79, 50, 54, 111, 189, 147, 352, 61, 460, 196, 77, 315, 304, 385, 275, 65, 145, 434, 39",
                "311, 202, 126, 494, 321, 330, 290, 28, 400, 84, 6, 160, 432, 308, 469, 459, 80, 48, 292, 229, 191, 240, 491, 231, 286, 413, 170, 486, 59, 54, 36, 334, 135, 39, 393, 201, 127, 95, 456, 497, 429, 139, 81, 293, 359, 477, 404, 129, 129, 297, 298, 495, 424, 446, 57, 296, 10, 269, 350, 337, 39, 386, 142, 327, 22, 352, 421, 32, 171, 452, 2, 484, 337, 359, 444, 246, 174, 23, 115, 102, 427, 439, 71, 478, 89, 225, 7, 118, 453, 350, 109, 277, 338, 474, 405, 380, 256, 228, 277, 3"};
        int r = 0;
        for (String s : t) {
            init(s);
            sort();
            System.out.println(rev.size());
            r += rev.size();
        }
        System.out.println("total: " + r);
    }

    public static void main(final String... args) throws IOException {
        System.out.print("Input: ");
        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        final String s = br.readLine();
        final long t = System.currentTimeMillis();
        if (s.isEmpty()) {
            System.out.println("Running tests");
            test5();
        }
        else {
            init(s);
            sort();
            show();
        }
        System.out.println("Time: " + (System.currentTimeMillis() - t + 500) / 1000 + " sec");
    }
}

```

Input is a list of numbers separated by comma and/or space (from stdin). If the input is empty, the program runs the 5 tests. Each one takes about 40 sec here.

# Answer
> 5 votes
# One move brute-force then selection sort (also naive solution), 90 + 89 + 88 + 87 + 89 = 443 moves

```
let doReverse = (a, l, r) => {
  a.splice(l, r - l, ...a.slice(l, r).reverse());
};
let selectSubVectorReverseSort = a => {
  let log = [];

  for (let i = 0, l = a.length; i < l; i++) {
    let j, p = i;
    for (j = i; j < l; j++) {
      if (a[j] < a[p]) p = j;
    }
    if (p === i) continue;
    log.push([i, p + 1]);
    doReverse(a, i, p + 1);
  }
  return log;
};

let a = JSON.parse(`[${readline()}]`);
let copiedArray = a => a.map(x => x);
let minLog = selectSubVectorReverseSort(copiedArray(a));
for (let i = 0, l = a.length; i < l; i++) {
  for (let j = i + 1; j < l; j++) {
    let b = copiedArray(a);
    doReverse(b, i, j + 1);
    let log = [[i, j + 1], ...selectSubVectorReverseSort(b)];
    if (log.length < minLog.length) minLog = log;
  }
}

print(minLog.length);

```

for every possible first move, try it, and then, do a selection sort.

Yes, this is another naive solution.

I'm not sure this should be an edit or another post, but it seems the solution is too simple, so editing is chosen.

---

# Selection Sort (Naive Solution), 92 + 93 + 95 + 93 + 96 = 469 moves

```
let log = [];
let doReverse = (a, l, r) => {
  log.push([l, r]);
  a.splice(l, r - l, ...a.slice(l, r).reverse());
}

let a = JSON.parse(`[${readline()}]`);
for (let i = 0, l = a.length; i < l; i++) {
  let j, p = i;
  for (j = i; j < l; j++) {
    if (a[j] < a[p]) p = j;
  }
  if (p === i) continue;
  doReverse(a, i, p + 1);
}
print(log.length)

```

A naive solution use selection sort.

There *MUST* be some better solutions, but post this since I did not find a better one (without brute-force search).

(Above code is JavaScript Shell)

---
Tags: sorting, optimization, restricted-time, fewest-operations
---