# Question
Title: Display a chain of little mountains with an odd number on the top of it!
First line is made with `ceil(n/2)` elements where each element is: `<space><odd-number><space>`

Second line is made with `ceil(n/2)` elements, but each element is `/ \` only.

You may assume `n >= 0` and `n <= 10`.

### Examples

Input: 3

```
 1  3
/ \/ \

```

Input: 10

```
 1  3  5  7  9
/ \/ \/ \/ \/ \

```

---

Example in Python 3, 103 bytes:

```
lambda a:print("".join([" "+str(i)+" "for i in range(1,a+1,2)]+["\n"]+["/ \\"for i in range(1,a+1,2)]))

```

Shortest code in bytes wins :)

# Answer
> 10 votes
# 05AB1E, ~~19~~ ~~15~~ ~~14~~ 12 bytes

05AB1E uses CP-1252 encoding.
Saved 4 bytes thanks to *Adnan*.
Saved 2 bytes thanks to *carusocomputing*

```
ÅÉðìDg…/ \×»

```

Try it online!

**Explanation**

```
ÅÉ               # list of uneven number up to input
  ðì             # prepend a space to each
    Dg           # get length of list
      …/ \       # push the string "/ \"
          ×      # repeat the string length-list times
           »     # join rows by spaces and columns by newlines

```

# Answer
> 10 votes
## Pyke, 16 bytes

```
S2%idm+dJil*"/ \

```

Try it here!

### 17 bytes and more awesome

```
S2%i`~Bd.:il*"/ \

```

Try it here!

This uses IMHO an AWESOME algorithm for making sure the first line is correctly aligned.

```
S                 - range(1, input+1)
 2%               -  ^[::2]
   i              -   i = ^
    `             -    str(^)
     ~Bd.:        -     ^.translate("><+-.,[]", " ") <-- awesome bit here
          il      -  len(i)
            *"/ \ - ^ * "/ \"

```

This replaces all the characters in the stringified list with spaces. `~B` contains all the characters in the Brain\**** language and this is the first time I've used this variable.

The program ``~Bd.:` does this:

```
`~Bd.: - input = [1, 3, 5, 7]
`      - str(input)  # stack now ["[1, 3, 5, 7]"]
 ~B    - "><+-.,[]"  # stack now ["[1, 3, 5, 7]", "><+-.,[]"]
   d   - " "         # stack now ["[1, 3, 5, 7]", "><+-.,[]", " "]
    .: - translate() # stack now [" 1  3  5  7 "]

```

# Answer
> 6 votes
# Python ~~2~~ 3, ~~67~~ ~~65~~ ~~63~~ 60 Bytes

Nothing too crazy here, ~~I think the first section can probably be done shorter but I'm not quite sure how~~. I use the fact that in this case `-~n/2` will work for `ceil`.

```
lambda n:-~n//2*' %d '%(*range(1,n+1,2),)+'\n'+-~n//2*'/ \\'

```

Below are alternative 61 and 65 byte solutions in Python 2:

```
lambda n:-~n/2*' %d '%tuple(range(1,n+1,2))+'\n'+-~n/2*'/ \\'
lambda n:' '+'  '.join(map(str,range(1,n+1,2)))+'\n'+-~n/2*'/ \\'

```

<sup>*Thanks to Rod for saving 2 bytes and Artyer for saving another byte by switching version :)*</sup>

# Answer
> 6 votes
## Python 2, 63 bytes

```
lambda n:' '.join(n%2*`n`for n in range(n+1))+'\n'+-~n/2*'/ \\'

```

Little trick for the first line: it don't print the even numbers, but take them as an empty string, which leads to starting empty space (0 would be there), and double spaces between the numbers without any modification on the range, the downside is a leading space in the even numbered `n`

# Answer
> 6 votes
## JavaScript (ES6), 55 bytes

```
f=n=>n%2?f(n-1).replace(`
`,` ${n}
/ \\`):n?f(n-1):`
`
```

```
<input type=number min=1 max=10 oninput=o.textContent=f(this.value)><pre id=o>
```

Note the space on the end of the second line.

# Answer
> 5 votes
# Vim, ~~73~~ ~~59~~ 56 bytes

This is a really high byte count IMO for what seems like a simple problem. I feel like I'm missing something obvious.

```
caw="/2*2
caw1357911/"
DYp:s;.;/ \\;g
k:s// & /g

```

Try it online!

Unprintables:

```
^Acaw^R=^R"/2*2      # Transform a number into the next odd number (3->5,4>5)
^[^Acaw1357911^[/^R" # Insert 1357911, delete everything after the number above
DYp:s;.;/ \\;g       # Duplicate the line, replace numbers with / \
k:s// & /g           # On the line above, add spaces around numbers
<trailing newline>

```

# Answer
> 5 votes
## Python 2, 53 bytes

```
lambda n:" 1  3  5  7  9"[:-~n/2*3]+'\n'+-~n/2*"/ \\"

```

Takes advantage of the restriction `n <= 10` to generate the top line by chopping off a piece from a hardcoded string.

The outputs for 1 to 10 are

```
 1
/ \
 1
/ \
 1  3
/ \/ \
 1  3
/ \/ \
 1  3  5
/ \/ \/ \
 1  3  5
/ \/ \/ \
 1  3  5  7
/ \/ \/ \/ \
 1  3  5  7
/ \/ \/ \/ \
 1  3  5  7  9
/ \/ \/ \/ \/ \
 1  3  5  7  9
/ \/ \/ \/ \/ \

```

The output for 0 is two empty lines.

# Answer
> 4 votes
# Mathematica, 65 bytes

```
" "<>Range[1,#,2]~StringRiffle~"  "<>"
"<>"/ \\"~Table~⌈#/2⌉&

```

Anonymous function. Takes a number as input and returns a string as output. The Unicode characters, respectively, are U+2308 LEFT CEILING for `\[LeftCeiling]` and U+2309 RIGHT CEILING for `\[RightCeiling]`.

# Answer
> 4 votes
# WinDbg, 100 bytes

```
.echo;.for(r$t1=1;@$t1<=2*@$t0+@$t0%2;r$t1=@$t1+2){j@$t1<=@$t0 .printf"\b %d \n",@$t1;.printf"/ \\"}

```

Input is done by setting a value in the pseudo-register `$t0`.

Looks like it's shortest here just to print the string as it's being built rather than try to build it first and display the whole thing. I'd have a shorter solution if WinDbg would let me write to address `0`.

How it works:

```
.echo;                                            * Print a new line that'll be deleted
.for(r$t1=1; @$t1 <= 2*@$t0+@$t0%2; r$t1=@$t1+2)  * Enumerate 1 to 4*ceil($t0/2), count by 2
{
    j@$t1<=@$t0                                   * If $t1 <= $t0...
        .printf"\b %d \n",@$t1;                   * ...Print $t1 (and newline for last n)
        .printf"/ \\"                             * ...Else print the / \'s
}

```

Output for each value of `n`:

```
0:000> .for(r$t0=0;b>@$t0;r$t0=@$t0+1){.printf"\n\nn=%d\n",@$t0; .echo;.for(r$t1=1;@$t1<=2*@$t0+@$t0%2;r$t1=@$t1+2){j@$t1<=@$t0 .printf"\b %d \n",@$t1;.printf"/ \\"}}

n=0

n=1
 1
/ \

n=2
 1
/ \

n=3
 1  3
/ \/ \

n=4
 1  3
/ \/ \

n=5
 1  3  5
/ \/ \/ \

n=6
 1  3  5
/ \/ \/ \

n=7
 1  3  5  7
/ \/ \/ \/ \

n=8
 1  3  5  7
/ \/ \/ \/ \

n=9
 1  3  5  7  9
/ \/ \/ \/ \/ \

n=10
 1  3  5  7  9
/ \/ \/ \/ \/ \

```

# Answer
> 4 votes
# Java, 118 112 Bytes

*Edit: Saved 6 Bytes thanks to @peech*

Golfed:

```
String M(int n){String o=" ";int i=1;n+=1;for(;i<n;i+=2)o+=i+"  ";o+="\n";for(i=0;i<n/2;i++)o+="/ \\";return o;}

```

Ungolfed:

```
public String M(int n)
{
    String o = " ";
    int i=1;
    n += 1;
    for (; i < n;i+=2)
        o += i + "  ";
    o += "\n";
    for (i = 0; i < n/2; i++)
        o += "/ \\";
    return o;
}

```

Testing:

```
    OddMountains om = new OddMountains();
    System.out.println(om.M(1));
    System.out.println();
    System.out.println(om.M(3));
    System.out.println();
    System.out.println(om.M(5));
    System.out.println();
    System.out.println(om.M(7));
    System.out.println();
    System.out.println(om.M(10));

 1
/ \

 1  3
/ \/ \

 1  3  5
/ \/ \/ \

 1  3  5  7  9
/ \/ \/ \/ \/ \

```

# Answer
> 4 votes
# \>\<\> (FISH), ~~69~~ ~~60~~ ~~68~~ 55 bytes

```
5|v&+%1:,2
1->:?!v:
8~v!?l<on$o:*4
a&/o
1->:?!;"\ /"ooo

```

Paste it into this online interpreter!

The number 5 on the first line is your input value (hard coded as 5, replaced by 0-a or i for user input).

Edit 1: Moved new line placement into the first line space (was empty) to save 9 bytes overall on space from a new line.

Edit 2: As noted by user7150406 the output was wrong (no spaces printing) this has been fixed with a loss of 8 bytes.

Edit 3: completely changed the logic, there is no point checking if the number is odd - rather put all numbers on the stack and remove every second one. Byte saved 13!

# Answer
> 3 votes
# C#6, 95 bytes

```
n=>{var o="";int i=1;for(;i<=n;i+=2)o+=$" {i} ";o+='\n';for(i=1;i<=n;i+=2)o+="/ \\";return o;};

```

Full lambda:

```
Func<int, string> a = n=>
{
    var o="";int i=1;
    for(;i<=n;i+=2)
        o+=$" {i} ";
    o+='\n';
    for(i=1;i<=n;i+=2)
        o+="/ \\";
    return o;
};

```

# Answer
> 3 votes
# CJam, ~~26~~ 23 bytes

```
Sri,:)2%_S2**N@,"/ \\"*

```

Test it!

*-3 thanks to 8478 (Martin Ender)*

# Answer
> 3 votes
# Pyth, ~~24~~ 22 bytes

```
K-SQyMS5+dj*2dK*lK"/ \

```

*Thanks to 42545 (ETHproductions) for -1 byte*

Online interpreter

11 test cases

# Answer
> 3 votes
## Game Maker Language (GM 8.0), 97 bytes

```
m=ceil(argument0/2)e=""for(i=1;i<2*m;i+=2)e+=" "+string(i)+" "return e+"#"+string_repeat("/ \",m)

```

Given that the input is at most 10, `chr(48+i)` will work in place of `string(i)`, although the number of bytes is the same.

Readable:

```
m = ceil(argument0/2)
e = ""
for (i = 1; i < 2*m; i += 2 )
  e += " " + string(i) + " "
return e + "#" + string_repeat("/ \", m)

```

# Answer
> 3 votes
## \>\<\> (Fish) ~~52~~ ~~63~~ 62 bytes

```
<v!?:-1:!?-1%2:
 >~la}}" "72.
v!?-2lno<o"  "
o
>:?!;"\ /"ooo1-

```

Try it online!

To use simply place `n` on the stack and away you go!

Much of this is taken from @Teal-Pelican's answer :).

Edit: The output is actually not aligned correctly in either \>\<\> submission! Fixing...

Edit2: I had to sacrifice some bytes, but the output is actually correct now.

Edit3: No more fun with `\` `/` mirrors and I save 1 byte.

**Output:**

```
 1  3  5  7  9
/ \/ \/ \/ \/ \

```

# Answer
> 2 votes
# C, ~~100~~ ~~79~~ 77 bytes

```
#define P(s)for(i=0;i++<n;printf(s,i++));puts("");
i;f(n){P(" %d ")P("/ \\")}

```

# Answer
> 2 votes
# R, ~~70~~ ~~69~~ ~~68~~ 58 bytes

```
cat(paste("",z<-seq(,scan(),2)),"\n");for(i in z)cat("/ \\")

3:
#>  1  3
#> / \/ \

10:
#>  1  3  5  7  9
#> / \/ \/ \/ \/ \

```

# Answer
> 2 votes
# Ruby ~~82~~ 60 Bytes

Quick and dirty Ruby solution could definitely be better optimized if I was better with Ruby

```
puts "",1.step($*[0].to_i,2).map{|x|$><<" #{x} ";"/ \\"}*""

```

Usage: prog.rb 10
Output:

```
 1  3  5  7  9
/ \/ \/ \/ \/ \

```

edit: numerous edits and optimisations by @Manatwork!

# Answer
> 2 votes
# Bash, ~~64~~, ~~59~~, ~~57~~, ~~51~~, ~~49~~, ~~48~~, 45 bytes

EDIT:

* minus 3 bytes (use $1 instead of STDIN)
* one more byte off by replacing `-s ""` with `-s\`
* minus 2 bytes by replacing *printf* with *seq -f* (Thanks @Adam!)
* refactored to script instead of function (to beat the **\>\<\>**)
* removed superfluous spaces
* optimized the *sed* expression a bit

**Golfed**

Chunk (45 byte):

```
seq -f" %g " -s\  1 2 $1|sed 'p;s| . |/ \\|g'

```

Function (original version) (57 bytes):

```
M() { printf " %s %.0s" `seq 1 $1`|sed 'p;s| . |/ \\|g';}

```

**Test**

```
--- mountains.sh ----
#!/bin/bash
seq -f" %g " -s\  1 2 $1|sed 'p;s| . |/ \\|g'

>./mountains.sh 10
 1  3  5  7  9
/ \/ \/ \/ \/ \

>M 10
 1  3  5  7  9
/ \/ \/ \/ \/ \

```

# Answer
> 2 votes
# Befunge 93, 64 bytes

Try it Online!

```
 &61p1   v+2,,,"/ \"
_v#!`" ":<+2.," ":
 <^p00p10"|<"
@ >91+,$1v

```

# Answer
> 1 votes
# JavaScript (ES6), ~~66~~ 64 bytes

```
n=>(f=n=>n?f(n-1)+(n%2?n+s:s):s=" ")(n)+`
`+"/ \\".repeat(++n/2)

```

Recursively builds the first line, then appends the second. The first line is built with the observation that it's simply the range **\[0...n\]** with each item **n** transformed to a space if even, or **n** concatenated with a space if odd.

# Answer
> 1 votes
# Python 2, 60 bytes

Saved 6 bytes thanks to @Kade!

```
lambda s:" "+"  ".join(`range(s+1)`[4::6])+"\n"+-~s/2*"/ \\"

```

# Answer
> 1 votes
## Batch, 107 bytes

```
@set s=
@set t=
@for /l %%i in (1,2,%1)do @call set s=%%s%%  %%i&call set t=%%t%%/ \
@echo%s%
@echo %t%

```

# Answer
> 1 votes
# Scala, 99 95 Bytes

```
(? :Int)=>for(i<-0 to 1)println(1 to ?filter(c=>c%2>0)map(c=>if(i<1)s" $c "else"/ \\")mkString)

```

Ungolfed

```
(? :Int) =>
    for (i<-0 to 1)
        println(
            1 to ?filter(c=>c%2>0)
                  map(c=>if(i<1)s" $c "else"/ \\")
                  mkString
        )

```

# Answer
> 1 votes
# Ruby, 48 bytes

```
->x{" 1  3  5  7  9 "[0..3*x-=x/2]+?\n+"/ \\"*x}

```

# Answer
> 1 votes
# Octave, 45 bytes

`f=@(n)reshape(sprintf(' /%d \',1:2:n),2,[]);`

Test:
f(8)

```
 1  3  5  7
/ \/ \/ \/ \

```

# Answer
> 1 votes
## QBIC, 35 bytes

```
:[1,a,2|X=X+!b$+@ | Y=Y+@/ \|]?X ?Y

```

Explanation:

```
:           gets a CMD line param as INT 'a'
[1,a,2|     FOR b = 1 to a STEP 2
X=X+!b$+@ | Add to X$ the counter of our FOR loop and a trailing space
            Leading space is provided by the cast-to-string function.
Y=Y+@/ \|   Add to Y$ the mountain.
]           Close the first possible language construct (IF, DO or FOR). In this case: NEXT
?X ?Y       Print X$, Print Y$. The space adds a newline in the resulting QBASIC.

```

# Answer
> 0 votes
# Kitanai, 140 bytes

```
$0[0]$1[int(input":")]$2[""]$3[""]$0#?(mod@2)($2[add(add(@" ")(string($0@)))"  "]
$3[add@"/ \"])?(neq@($1@))([add@1]&1)print($2@)print($3@)%

```

# Answer
> 0 votes
# Perl, 46 + 2 (`-pl` flag) = 48 bytes

```
@_=map$_%2?$_:"",0..$_;$_="@_$/"."/ \\"x(@_/2)

```

Using:

```
perl -ple '@_=map$_%2?$_:"",0..$_;$_="@_$/"."/ \\"x(@_/2)' <<< 7

```

Or 52 bytes:

```
@_=map$_%2?$_:"",0..pop;print"@_$/","/ \\"x(@_/2),$/

```

Using:

```
perl -e '@_=map$_%2?$_:"",0..pop;print"@_$/","/ \\"x(@_/2),$/' 7

```

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


title: PPCG Jeopardy: Cops

text:
# Question
Title: PPCG Jeopardy: Cops
How well do you know the site? Let's find out.

This is a challenge. Robber's thread.

As a cop, you need to:

1. Find a non-deleted, non-closed challenge on this site to answer. The challenge cannot have the following tags: , , , , , , , . The challenge must have restrictions on valid output.
2. Write a valid submission for the challenge, in a free language found on Wikipedia or esolangs.org or tryitonline. The submission does not have to be competitive, only valid. **EDIT: Hashing in your submission is not allowed**
3. Post the submission here, keeping the *challenge* secret. You must post the entire submission, as well as the language (and version, if applicable).

After a week, if nobody has found the challenge you are answering, you may post the challenge that your submission is answering, at which point, your submission is *safe*. **It is worth N points, where N is the number of upvotes on the challenge (as of 2016-11-17)** (Higher is better)

To crack your challenge, a robbers need to find *any* challenge that the submission is a valid submission for.

Notes:

* If a challenge requires an output of `X`, and you output `XY` or `YX` where `Y` is anything besides whitespace, the submission is not valid for that challenge.
* A challenge newer than 2016-11-17 is not allowed.
* Languages newer than the hidden challenge are allowed.
* I reserve the right to ban certain challenges if they are widely applicable (could be applied to the majority of all submissions).
* Thanks to Daniel for the initial idea!

Here's a search query for valid questions.

# Uncracked Submissions:

```
<script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 100357;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```

# Answer
## Pip, 9 bytes (safe, 15 points)

```
(q`\w+`1)

```

*What* it does should be easy to figure out, but the question is *why*... (TIO)

---

The challenge was What's the Language? The goal: parse the name of the programming language out of a PPCG answer header. For instance:

```
Input: <h1>JavaScript, 13 chars / 32 bytes</h1>
Desired Output: JavaScript

```

I'm not sure whether this falls afoul of "The challenge must have restrictions on valid output," since it's a challenge scored by "percent of tests you get correct," and thus doesn't require the output to be correct for all input. However, I will say that the code above gets about a 60% correct rate, which isn't bad for something so simple.
> 11 votes

# Answer
# Perl - Cracked by DLosc

Let's give an easy one for the non-esolang people

Run with `-nl`

```
say $_ ~~ reverse y-"({[]})"-")}][{("-r;;r-")}][{("-"({[]})"-y esrever ~~ _$ yas

```

Challenge: Convenient Palindrome Checker

The code crashes after printing the truthiness, but according to this meta post, as long as it produces the correct output *before* it crashes, and any errors are output to STDERR, it's a valid solution.
> 3 votes

# Answer
# Perl, 56 bytes, Safe (14 points)

```
undef$/;print+(<>^<>)=~y/\x81-\xff\x00-\x80/\x01-\xff/dr

```

The challenge was this one, requiring you to create a diffing algorithm; you need to be able to input two files and output a diff, or input a file and a diff and output the other file. The scoring of that challenge is , making the smallest diff the winner; however, *this* challenge doesn't require the answer to be competitive, simply compliant with the spec, so I wrote a diffing program in a golfed way instead, which simply uses XOR to combine the inputs (meaning that the same program works for diffing and un-diffing).

The hardest part is reproducing the length of the original files. The input is specified as ASCII, which is a seven-bit character set, thus allowing me to use the eighth bit to track the length of the file. When diffing, we set the high bit of every byte using a `y///` instruction (which is slightly more obfuscated than bitwise arithmetic would be). When un-diffing (recognised via noting that the input already has the high bit set), we remove NULs from the output. (I've *just* realised that this would fail if the input contained NUL bytes; however, the challenge is defined in terms of a test battery, and luckily I don't think there are NUL bytes in the battery. If there are, then this program would be incorrect and would need to be disqualified; a problem with a is that nobody else has enough information to point out easily fixed flaws in your answer!)
> 3 votes

# Answer
## Perl, safe, 18 points

*Edit* : I modified the end of the code (see the edit history) to handle an edge case (the challenge doesn't say anything about it, and the author did not answer when asked about it, but at least this code handles it). But the algorithm and the logic of the code remain the same.

```
perl -n0E '/.*/;s/(^0|A)(.{@{+}})?0/A$2A/s||s/0(.{@{+}})?A/A$1A/s?redo:say/A$/+0'

```

This code isn't obfuscated (just golfed). (This implies that `-n0E` aren't optional).

I don't realize whether this is hard or not, but I guess I'll be fixed when someone cracks it.

---

**Explanations:**

The challenge was Can maze be solved?.

This code will find every reachable cell of the maze (and mark them with a `A`): if a cell touches a cell marked with a `A`, the it's reachable and we mark it with a `A` too; and we do that again (`redo`). That's done thanks to two regex: `s/(^0|A)(.{@{+}})?0/A$2A/s` checks if a space is on the right or the bottom of a `A`, while `s/0(.{@{+}})?A/A$1A/s` checks if a space is on the left or on top of a `A`. At the end, if the last cell contains a `A` it's reachable, otherwise it's not (that's what `say/A$/+0` checks; the `+0` is here to make sure the result will be `0` or `1` instead of *empty string* and `1`).
Note that `/.*/` will match an entire line, thus setting `@+` to the index of the end of the first line, which happens to be the size of a line, which allow use to use `.{@{+}}` to match exactly as many character as there are on a line. (`@{+}` is equivalent to `@+`, but only the former can be used in regex)

To run it:

```
$ perl -n0E '/.*/;s/(^0|A)(.{@{+}})?0/A$2A/s||s/0(.{@{+}})?A/A$1A/s?redo:say 1-/0$/' <<< "0000001
0000010
1111011
0000000"
1

```

(and if you replace the `1111011` line with `1111111`, the it's not solvable anymore, and the output will be `0` instead of `1`)
> 3 votes

# Answer
# Octave, 15 points! SAFE

```
@(x,y)find((v=((z=cumsum(x.^2))(y:end)-[0,z(1:end-y)]))==max(v),1)-1

```

Try it online here.

---

### Explanation:

The code takes an input string `x` containing ones and zeros, `10010110110101` and an integer `y`.

To find the moving average of a sequence in MATLAB/Octave you can do:

```
z = cumsum(x);
movmean = z(y:end) - [0 z(1:end-y)];

```

Since we're only interested in the location of the maximum, not the actual values, we don't need to care about converting the string to numbers. `(x.^2)` squares all the ASCII-values `48,49` for `0,1`. This is necessary since Octave can't use `cumsum` directly on characters. `cumsum(+x)` would be two bytes shorter but would reveal that `x` is a string.

This is actually quite well golfed (except for the `.^2` instead of `+`). Of course, convolution would be simpler.
> 3 votes

# Answer
## Hexagony, 548 bytes, Cracked

```
69;{108;\_1$;;;/0;108\56;19|1^\6/15\;72_$23371<};;!;6;33|;;015><;;7;@3?;43+1586;2_3219><11;;'_8;;;2_|3;81|2<|8517;327}1_23;1;4$%;_4{5.1;1332_3;029&;'_};;1..527;2'..35;5212_>97;$;2/0;-;3_2;/233;08.._\901;0/13'}92...>/>/57\53;633;4'22;/|~>;441;45;;$161;371;3/;3.7026;`208;1<}>27;140;217;11.0;/2;692;<01/2;301;18;31/;10;/3;44<1914/111;{98;38;;;13/4;<;3;1;;/;112;<.$13032;..27;1;222/1;0<6..1;0;'..933721389/9<6;.;3;37..;;875;*;;0[1;287]59..902;;2;12;1;59;;3#..4;;1=249$345249;...;012}021#>/;44>114/4201;;;3>0;>;24;3/;;116._4>337;237/$5_>1{32;102;255;'_

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 27 bytes, cracked!

For this submission, input is also required for it to work. Shouldn't be too hard to crack.

```
ávyl•B;£¡´•54B•2ît•‡y.li(}O

```

Explanation (for the challenge):

```
á                             # Keep all the letters of the input string
 vy                           # For each letter...
   l                          #   Convert to lowercase
    •B;£¡´•54B                #   String that turns into 'pnbrqk'
              •2ît•           #   Compressed int: 133591
                   ‡          #   Transliterates the following:
                                    p -> 1
                                    n -> 3
                                    b -> 3
                                    r -> 5
                                    q -> 9
                                    k -> 1
                    y.li }    #   If the current letter is lowercase...
                        (     #     Negate that number
                          O   # Sum up the result

```

Uses the **CP-1252** encoding. Try it online!
> 2 votes

# Answer
# MATL. Cracked

```
&:"@FYAYm7>vs

```

Try it online!

I indicated input and output even if it's not necessary. Since it's in the edit history anyway: the program inputs two numbers and outputs one number.
> 2 votes

# Answer
# C#, 590 bytes, Cracked

```
(I,N)=>{string R="",p="`1234567890-=",P="~!@#$%^&*()_+",q="qwertyuiop[]\\",Q="QWERTYUIOP{}|",a="asdfghjkl;\'",A="ASDFGHJKL:\"",z="zxcvbnm,./",Z="ZXCVBNM<>?";foreach(var c in I){var f=c+"";if(p.Contains(f))R+=p[(p.IndexOf(c)+N)%13];else if(P.Contains(f))R+=P[(P.IndexOf(c)+N)%13];else if(q.Contains(f))R+=q[(q.IndexOf(c)+N)%13];else if(Q.Contains(f))R+=Q[(Q.IndexOf(c)+N)%13];else if(a.Contains(f))R+=a[(a.IndexOf(c)+N)%11];else if(A.Contains(f))R+=A[(A.IndexOf(c)+N)%11];else if(z.Contains(f))R+=z[(z.IndexOf(c)+N)%10];else if(Z.Contains(f))R+=Z[(Z.IndexOf(c)+N)%10];else R+=c;}return R;};

```

Probably pretty easy, also a fairly long program ,\_,
> 2 votes

# Answer
# MATL. Safe, 93 points

```
dP7EGn:q^1J2/h)ts_hX=Gs[BE]Wd=~>~GBz*

```

Try it online!

---

### Explanation

The challenge was *Source code ecological footprint*.

The code computes the Hamming weight (number of ones) in the binary representation of the ASCII codes of the input string; except that the string `test` outputs `0` (instead of its Hamming weight, which is `17`).

The special-casing of that string is a little obfuscated. The program first computes the array of consecutive differences of the ASCII codes of the input and reverses it. For `test` this gives `[1 14 -15]`.

Then, the array formed by the first `n` powers of `14` is computed (`[1 14 196 ...]`), where `n` is input length; and the first `floor(n/2)` values are kept. So for input `test` this gives `[1 14]`. The negated sum is appended to this array, which gives `[1 14 -15]` for input `test`. This is tested for equality with the reversed array of consecutive differences which was previously obtained.

On the other hand, the sum of the ASCII codes of input chars is computed and compared with `448`, generated as the (consecutive) difference of the elements in the array `[2^6 2^9]` (where `^` denotes power).

The input `test` is the only string with reversed consecutive differences of the form `[1 14 -15]` and sum `448`. Differences `[]` or `[1]` (for shorter inoyt strings) are not compatible with a total sum of `448`. Differences `[1 14 196]` or larger cannot be achieved with ASCII characters.

The code checks if the result of the test for the first condition (consecutive differences) is not smaller than the negated result of the second condition (total sum). This gives `0` if and only if both conditions were satisfied. Finally, this is multiplied by the number of ones in the binary representation of the ASCII codes of the input.
> 2 votes

# Answer
# 아희(Aheui), 0 bytes, Cracked

Try it here! (The program is already typed in for you :p )
> 2 votes

# Answer
## CJam (safe, 21 points)

```
{W+W%~1{1$)}{)a1${\(+W%{1$1$-2=>}{+}w}{\;}?)_@*\+~}w+}

```

This is an anonymous block (function).
> 2 votes

# Answer
# Python, 935 Bytes

```
def oo000 ( num ) :
 return - ~ num
def ii ( num ) :
 return - ( oo000 ( oo000 ( ~ num ) ) )
def oOOo ( num1 , num2 ) :
 while num2 > 0 :
  num1 = oo000 ( num1 )
  num2 = ii ( num2 )
 return num1
 if 59 - 59: Oo0Ooo . OO0OO0O0O0 * iiiIIii1IIi . iII111iiiii11 % I1IiiI
def IIi1IiiiI1Ii ( num1 , num2 ) :
 I11i11Ii = num2
 oO00oOo = 0
 while I11i11Ii > 0 :
  oO00oOo = oOOo ( oO00oOo , num1 )
  I11i11Ii = ii ( I11i11Ii )
  if 92 - 92: O0O / oo000i1iIi11iIIi1 % Iii1IIIiiI + iI - Oo / o0O
 return oO00oOo
def hgj ( num1 , num2 ) :
 I11i11Ii = num2
 oO00oOo = 1
 while I11i11Ii > 0 :
  oO00oOo = IIi1IiiiI1Ii ( oO00oOo , num1 )
  I11i11Ii = ii ( I11i11Ii )
  if 48 - 48: iII111i % IiII + I1Ii111 / ooOoO0o * o00O0oo
 return oO00oOo
def O0oOO0o0 ( num1 , num2 ) :
 return oOOo ( num1 , - num2 )
 if 9 - 9: o0o - OOO0o0o
 if 40 - 40: II / oo00 * Iii1IIIiiI * o0o . ooOoO0o
print(hgj ( 9 , 9999 ))
# dd678faae9ac167bc83abf78e5cb2f3f0688d3a3

```

Sorry I used a obfuscator, but it isn't forbidden and way easier. (And I didn't have all that time to do it myself...)
> 2 votes

# Answer
# Ruby (cracked by DLosc)

```
p n = gets.to_i
p n = n*(3*n-1)/2 until n % 7 == 0

```
> 2 votes

# Answer
# Python 3, ~2000 bytes, (safe: 23 points)

---

### Original Program

```
exec("\n))o0000o000o<)]))]00000o000o[0o0o0o0o0o0o0o0o0o(00000000000000o0o(000000000000000o0o ni oooo0oooo rof)))0o0o0o0o0o0o0o0o0o(00000000000000o0o(000000000000000o0o ni 00oo00oo00oo00oo00oo rof]oooo0oooo[]00oo00oo00oo00oo00oo[0o0o0o0o0o0o0o0o0o(000ooo000ooo000o[ +]0o0o0o0o0o0o0o0o0o ni 00oo00oo00oo00oo00oo rof)00oo00oo00oo00oo00oo(000ooo000ooo000o[ni ooo000ooo000o rof)ooo000ooo000o(o0o0o0o0o-o0000o000o(000ooo000ooo000o(00o00o00o(tnirp\n)00000o000o,00000o000o(tresni.o0o0o0o0o0o0o0o0o0o:))00000000000000o0o=yek,0o0o0o0o0o0o0o0o0o(xam(00000000000000o0o<)o0o0o0o0o0o0o0o0o0o(00000000000000o0o elihw \n:)]00000o000o[]o0oooo,0o0o0o0o0o0o0o0o0o[( ni o0o0o0o0o0o0o0o0o0o rof\n;'=01NgwiNgwSNbBibpBybw8GMwAzbw8GM'b,]0o0o0o0o00oo ni ooooo0o00oo rof]]::0oooooo0oooo[))ooooo0o00oo(0oooooo(o0oooo ni ooo000ooo000o rof)ooo000ooo000o(00o00o00o[[=ooooo00oo,0o0o0o0o0o0o0o0o0o\n)'=kSZsBXd0BCLn5WayR3cgwCdulGK'b(0o0o.)(0o0ooo0o00ooo.o000oo esle o0000o000o fi o0000o000o+o0000o000o=0oooooo0oooo;)000000000000000o0o(o00oo00o=000000000000000o0o;)))(edoced.)o0o(0oo000o(000000o(o000oo,))(]o0000o000o[]edoced.)'==QbhRHa'b(0oo000o,'oo0o0o00o'[(oo0o0oo=o0o0o0o0o,oo0o0o0oo\n;)00000000000000o0o(o00oo00o,))(edoced.)'vJHZ'b(0oo000o(o00oo00o,)'bin'(o00oo00o=00000000000000o0o,0oooooo,o0oooo;))0000o0o0o(000000o(o000oo:0000o0o0o adbmal = o00oo00o ;)))(0o0oo00o(0oooooo(0o0oo0oo=0o0o0o0o00oo\n00000000000001**o0000o000o=o0000o000o;))(edoced.)'=cSbhRHanwCd1BnbpxyXfRncvBXbp91Xs4WavpmLnAyJ'b(0oo000o(o000oo=o0oo0oo00o,0o0oo00o,o0oo0oo,0o0oo0oo;edoced46b.)000oo0o(oo0o0oo=0oo000o\n;'==QYsxGKb92bwADMvVCN8EDIm9mcg8GMvBSauBybw82bwADMvBzbdliKq4SN'b ,))0o0oo00oo(000000o(__tropmi__ :0o0oo00oo adbmal,'base64',]0o0oo00oo[:0o0oo00oo adbmal = oo00oo00oo00oo00oo00oo,oo0o0oo,000oo0o,0oooooo\n;tni,'range','len','==Abh1mYkFGIv9GMwAzb682bwADMvBSYuRGIv9GMvBzbw82buYWYjR3bylWYshybvBDMw8WLxkiKqITJv9GMwAzb'b,lave,0**0000000000000009,0 ,]1-::[0o0ooo0o00o0oo:0o0ooo0o00o0oo adbmal,mus = 00o00o00o,000000000000000o0o,00000000000000o0o,o0o,o000oo,o0000o000o,00000o000o,000000o,000ooo000ooo000o\n"[::-1])

```

---

### Challenge

This is in fact an answer for my own challenge, **Primenary Strings**. I chose this as almost everything will output `0`, apart from a few inputs that a robber would be unlikely to enter. The code is a simple algorithm, but heavily obfuscated (by hand).
> 2 votes

# Answer
## Pyke, 3458 bytes, SAFE, score 99

```
wB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddsQI30>Q%)

```

Try it here!

There are a few (30) `0x1b` bytes that seem to have been eaten by SE.
> 1 votes

# Answer
# Haskell, SAFE

```
m f=map(f<$>)
g=reverse.("":)
f s|(f:c:s)<-m fromEnum.g.words$s,
    (f:c:s)<-init.unwords.g.m(\s->toEnum$if c!!0==s||s==sum(-32:c)then(last$f)else s)$s=init$s

```

Try it on Ideone. "Usage":

```
Prelude> f "Programming Puzzles & Code Golf"
"rogramming Puzzles "

```

---

In the String Shenanigans challenge one is given a string and two chars and should then replace every occurrence of the first char with the second. However, the input is one string only containing the actual string in quotation marks and the two characters whitespace separated:

```
Prelude> f "\"Hello, World!\" l r"
"Herro, Worrd!"

```
> 1 votes

# Answer
# Octave, 40 points. SAFE

Slightly obfuscated answer to a fairly popular challenge.

```
y=find((x=mod(input('')*2,32))>12);sign(sum(x.*[1-y:nnz(x+8)-y]))

```

I recommend testing this on octave-online. Ideone is not that good when it comes to STDIN.

---

This was the lever simulator 2015 challenge. Input on the form `'123^32`. Output will be `-1 0 1` for Left-heavy, Balanced and Right-heavy in that order.

It looks like this when it's fully golfed:

```
s=mod(input(''),16);i=find(s>9);s*[1-i:numel(s)-i]'*inf

```

This outputs `-Inf, NaN, Inf` for L,B,R respectively.
> 1 votes

# Answer
# JavaScript, 533 bytes, Cracked! by Dave

```
_=this;[490837,358155,390922].map(y=function(M,i){return _[[
U=[y+[]][+[]]][+[]][i]]=_[M.toString(2<<2<<2)]});function g(
s){return Function("a","b","c","return "+s)};e=g(u(["","GQ9\
ZygiYTwyPzE6YSpk","C0tYSki","SkoYSkvZChhLWIpL2QoYikg"].join(
"K")));h=g("A=a,B=b,g('A(a,B(a))')");j=g("a/b");L=g("Z=a,Y=\
b,g('Z(a,Y)')");k=L(j,T=2);F=g(u("KScpKWIsYShFLCliLGEoQyhEJ\
yhnLGM9RSxiPUQsYT1D").split("").reverse().join(""));RESULT=F
(h(e,k),j,g("_[U[10]+[![]+[]][+[]][++[+[]][+[]]]+[!+[]+[]][\
+[]][+[]]+17..toString(2<<2<<2)].pow(T,a)"));

```

Not my favorite obfuscation of mine, but it's kinda neat. Call as `RESULT(inputs)`.

I might award a +50 point bounty if you explain *in detail* what my code is doing along with your crack. (They do not have to be together, so feel free to FGITW if that suits your whims.)
> 1 votes

# Answer
## Pip, 13 bytes

```
V$.C(A*a-A9)a

```

Try it online (give input as Arguments, not Input).
> 1 votes

# Answer
# TeX, 240 bytes, SAFE, score 129

```
\let\N\newcount\let\I\ifnum\let\A\advance\let\E\else\N\a\N\b\N\c\def\D#1:#2:#3:{\I#1>#2\A#1by-#2\D#1:#2:#3:\E\I#1=#2 #3=1\E#3=0\fi\fi}\def\P#1:#2:{\I#1>#2\a=#1\D\a:#2:\c:\I\c=0\b=#2\A\b by1\P#1:\the\b:\E N\fi\E\I#1=1 N\E Y\fi\fi}\P1:2:\end

```

Save as `jeopardy.tex`, then run `pdftex jeopardy.tex` and open `jeopardy.pdf`.

Outcome: a PDF with the text `N` (and the page number 1).
> 1 votes

# Answer
# Python 3, **Cracked!**

Writing this was hilarious, even though it was easily crackable in the end :)

```
Z,O=__import__('time').strftime,401*5;from base64 import*;Q,I=(Z('%Y')),(O/401)*2;_=int(Q);D,P=(O,-~_),int(Q[~1:]);Q,I=(6+(P-eval(b64decode(b'KHN1bShbeCU0PDEgZm9yIHggaW4gcmFuZ2UobWluKEQpLG1heChEKSldKSk=').decode()+'*-1'*(O>_)))/10,'3'+repr(((P-10)*3)+10));print(Q,I)

```
> 0 votes

# Answer
## Pyke, 42 characters, SAFE, score 85

This was probably unfair as the code stopped working in the try-it link 3 days after this answer was posted. I am happy for this answer to be non-competing

```
cFDhkR.dۢ㒶οd-~o@l3{IoKRKn)R+(Jt~o16q*Q|

```

Try it here!

Subliminal message intended towards cracker.
> 0 votes

# Answer
## Pyke, 20 bytes, SAFE, score 59

```
uÄCMX67+*]mA""R`.:

```

Try it here!
> 0 votes

# Answer
# Pyth - Cracked by Maltysen

If it helps, Pyth was not any of the answers to the hidden challenge.

```
u=.+G.*A

```

Try it out!
> 0 votes

# Answer
# C#, 91 bytes

```
_=>{int b=0,w=0;for(;1>w||0<*(_-1);b+=++w**_++<<(9*w));return b%(3<w?903302656:41458688);};

```
> 0 votes

# Answer
# Mathematica, 34 bytes, Cracked

```
±1={±0={}};±n_:=Array[±#&,n,0]

```

Named function (`±`).
> 0 votes

# Answer
## Pyke, 18 bytes, SAFE, score 54

```
2fm}s"ab"NQlZh.&|!

```

Try it here!
> 0 votes

# Answer
## Pyke, 19 bytes, SAFE, score 51

```
4\Y:\m+Ay""%b%y"cl2

```

Try it here!
> 0 votes

# Answer
# C++14, Cracked

```
#include<vector>

auto h(auto i){return 0;}
auto h(auto i, auto x, auto...p){
 return x+(i-1?h(i-1,p...):0);
}

auto g(auto v){return v;}
auto g(auto v,auto x, auto...p){
 v.push_back(h(x,x,p...));
 return g(v,p...);
}

auto f(auto...p){
 return g(std::vector<int>{},p...);
}

```

Takes a variadic number of parameters and returns a `vector<int>`.

Usage:

```
int main() {
 auto v = f(4,7,3,4,5);
 for (auto i:v) std::cout << i << ", ";
 std::cout << std::endl;
}

```
> 0 votes

# Answer
# BrainFuck - 140 Bytes, Cracked by daHugLenny

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

```

Try It Here!
> 0 votes

# Answer
# Mathematica, 161 bytes

```
Which[LetterQ@#,If[UpperCaseQ@#,ToUpperCase,#&][FromLetterNumber~Array~LetterNumber@#],DigitQ@#,Array[IntegerString,FromDigits@#+1,0],True,#]&/@Characters@#<>""&

```
> 0 votes

# Answer
## Ruby, 50 bytes

```
count = 0; 400.times do count +=1; end; puts count

```

output: `400`
> 0 votes

# Answer
## Python 2.7, 45 bytes

```
import numpy;lambda a,n,t:numpy.arange(a,t,n)

```

Hint (or maybe not): *"the fish is in using numpy."*

2016.11.23 - second hint: *"Don't leave anything floating around!"*
> 0 votes

# Answer
# Jelly, 1 byte, cracked

<sup>Body must be at least 30 characters; you entered 15.</sup>
> -2 votes

---
Tags: cops-and-robbers, obfuscation
---


title: Building Demolition

text:
# Question
Title: Building Demolition
# Challenge

Write a full program/function to Demolish a given building at the rate **1 floor per second**.

# INPUT

Input is a **building** through **STDIN**(or whatever is called in your language) or through an **ARGUMENT** of a function. **t=0 s**

```
   |
  |#|
  {#}
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**input consists of :**

* `|` marks start and end of a floor.
* `{`,`}` marks the floor with explosives.
* `#` is a window which is for decoration .
* is space, which is everywhere inside the floors where `#` is not there.
* `T` marks ground(cannot be demolished).
* `*` marks the detonated floor.

**Input rules :**

* building starts from top with one `|` and ends on ground(with no(`T`)=no (`char used in ground floor`)).
* a window `#` is at every odd place inside every floor.
* `T` marks the end of your input.
* only **one** floor consists of explosives.
* every floor is made of **odd** no. of chars.
* as you ascend down the floors, the floors can either be of **equal size** of that of previous floor or can be **2** chars bigger.
* Input can be taken as an array of `chars` or `strings`.

**Output :**

**t=0.5 s**

```
   |
  |#|
  ***
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=1 s**

```
   |
  |#|
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=1.5 s**

```
   |
  ***
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=2 s**

```
   |
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=2.5 s**

```
   *
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=3 s**

```
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=3.5 s**

```
 *****
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=4 s**

```
|# # #|
|# # #|
|# # #|
TTTTTTT

```

**t=4.5 s**

```
*******
|# # #|
|# # #|
TTTTTTT

```

**t=6.5 s**

```
*******
TTTTTTT

```

**t=7 s**

```
TTTTTTT

```

**Output rules :**

* every floor ends with one `newline` character.
* ground may/may not have a trailing newline.
* output the building(or whats left of it) every 0.5 s.
* **Output** is like animation which is modified every 0.5 s and is displayed.
(Also feel free to post GIFs with your answer)

This is a **Code-Golf** so the code in shortest bytes wins!
*last date of submission is exactly 5 days from now*

(But you know what ? Winning is not everything, feel free to try this challenge in your favorite language, even after a winner has been declared :\] ).

**EDIT :** I changed the way you take input (my bad actually).

# Answer
# Vim, ~~41~~ 38 bytes

```
qw:sl 500m␍q/{␍qqjk^v$r*@wdd:-␍@w@qq@q

```

Here, `^` is used for a literal caret; ␍ is used for CTRL-M.

## Explanation

`qw:sl 500m␍q` sleeps half a second, while recording the half second sleep as macro w. `/{␍` moves to the floor with explosives. `qq` begins recording macro q, which will recursively call itself.

`jk` moves down and up; this generates an error if you're on the last line (ground); the error terminates the recursive macro. `^v$r*` replaces everything from the first non-whitespace character to the end of the line with \*'s. `@w` waits half a second, then `dd` deletes the current floor. `:-␍` moves up a floor without terminating the macro if you're on the top line. `@w` then waits another half second, and `@q` calls the q macro (initially empty).

`q@q` stops recording the macro q, then calls it, triggering the recursion.

## Animation
> 4 votes

# Answer
## JavaScript (ES6), ~~208~~ 198 bytes

```
f=
(t,s=f=>setTimeout(f,500),v=t.value.split(/(\S.*\n)/),i=v.findIndex(s=>/}/.test(s)),c=_=>t.value=v.join``,d=_=>c(v.splice(--i,2),v[3]&&s(e,i?--i:++i)),e=_=>c(v[i]=v[i].replace(/./g,'*'),s(d)))=>s(e)
```

```
<textarea id=t rows=9>
   |
  |#|
  {#}
 |# #|
|# # #|
|# # #|
|# # #|
TTTTTTT
</textarea><input type=button value=Go! onclick=f(t)>
```
> 4 votes

# Answer
# Java 7, ~~589~~ ~~477~~ 476 bytes

```
import java.util.*;void x(List<String>b,int x)throws Exception{Thread.sleep(500);int i=0,l=b.size(),z=x;String w;for(;i<l;i++){System.out.println(w=b.get(i));if(w.contains("{"))x=i;}System.out.println();w=b.get(x);i=w.contains("*")?1:0;if(i>0)b.remove(x);else b.set(x,z<0?r(w,'{','}'):r(w,'|','|'));if(l>1)x(b,i>0&x>0?x-1:x);}String r(String s,char y,char z){int a,b;return s.substring(0,a=s.indexOf(y))+s.substring(a,b=s.lastIndexOf(z)+1).replaceAll(".","*")+s.substring(b);}

```

Ok, it's a mess/long, but this challenge has so many annoying things for Java.. Printing multi-line; `Thread.sleep(500)` which requires a `throws Exception`; replacing a substring between two delimiters with an equal amount of `*`; etc.
All this causes the program to be pretty big.. It can defintely be golfed some more, maybe even halved with a different approach, but at least there is an answer now. ;)

**Ungolfed:**

```
void x(List<String>b, int x) throws Exception{
  Thread.sleep(500);
  int i = 0,
      l = b.size(),
      z = x;
  String w;
  for(;i<l; i++){
    System.out.println(w=b.get(i));
    if(w.contains("{")){
      x = i;
    }
  }
  System.out.println();
  w = b.get(x);
  i = s.contains("*")
       ? 1
       : 0;
  if(i>0){
    b.remove(x);
  }
  else{
    b.set(x, z < 0
              ? r(s, '{', '}')
              : r(s, '|', '|'));
  }
  if(l>1){
    x(b, i > 0 & x > 0
          ? x-1
          : x);
  }
}

String r(String s, chary, char z){
    int a, b;
    return s.substring(0, a=s.indexOf(y)) + s.substring(a, b=s.lastIndexOf(z) + 1).replaceAll(".", "*") + s.substring(b);
}

```

**Test code:**

```
import java.util.*;

class M{
  void x(List<String>b,int x)throws Exception{Thread.sleep(500);int i=0,l=b.size(),z=x;String w;for(;i<l;i++){System.out.println(w=b.get(i));if(w.contains("{"))x=i;}System.out.println();w=b.get(x);i=w.contains("*")?1:0;if(i>0)b.remove(x);else b.set(x,z<0?r(w,'{','}'):r(w,'|','|'));if(l>1)x(b,i>0&x>0?x-1:x);}String r(String s,char y,char z){int a,b;return s.substring(0,a=s.indexOf(y))+s.substring(a,b=s.lastIndexOf(z)+1).replaceAll(".","*")+s.substring(b);}

  public static void main(String[] a){
    try{
        List<String> l = new ArrayList(){{
            add("   |   ");
            add("  |#|  ");
            add("  |#|  ");
            add(" {# #} ");
            add("|# # #|");
            add("|# # #|");
            add("|# # #|");
            add("TTTTTTT");
        }};
        new M().c(l, -1);
    }
    catch(Exception e){}
  }
}

```

**Try it here.** (On ideone it outputs at once and ignores the `sleep`..)
> 2 votes

# Answer
**C, ~~314~~ ~~287~~ ~~281~~ 271 bytes**

```
s,e,t,i;f(char**b){char*p;do{system("CLS");i=0;do{while(!(p=b[i]))i++;if(!*b&&e==1)e=i;while(*p<33)putchar(*p++);if(!t)e=*p=='{'?i:e,s+=2;do{putchar(e==i&&t%2&&*p>16?'*':*p);}while(*p&&*p++>16);}while(*b[i++]-84);if(t++%2)b[e]=0,*b&&e>0?e--:e++;Sleep(500);}while(t<s-1);}

```

-10 after changing `!=` to `-` and avoiding char literals when it is possible, as well as `isspace` (many thanks to H Walters). But ungolfed code remains unchanged.

```
s,e,t,i;f(char**b){char*p;do{system("CLS");i=0;do{while(!(p=b[i]))i++;if(!*b&&e==1)e=i;while(isspace(*p))putchar(*p++);if(!t)e=*p=='{'?i:e,s+=2;do{putchar(e==i&&t%2&&*p>0xF?'*':*p);}while(*p&&*p++>0xF);}while(*b[i++]!='T');if(t++%2)b[e]=0,*b&&e>0?e--:e++;Sleep(500);}while(t<s-1);}

```

-6 bytes after applying coma and deletion of `{}` after two `if`.

```
s,e,t,i;f(char**b){char*p;do{system("CLS");i=0;do{while(!(p=b[i]))i++;if(!*b&&e==1)e=i;while(isspace(*p))putchar(*p++);if(!t){s+=2;e=*p=='{'?i:e;}do{putchar(e==i&&t%2&&*p>0xF?'*':*p);}while(*p&&*p++>0xF);}while(*b[i++]!='T');if(t++%2){b[e]=0;e=*b&&e>0?e-1:e+1;}Sleep(500);}while(t<s-1);}

```

-26 bytes after little optimization, removal unnecessary parentheses, as well as change local variables to global (with auto 0 initialization) and `b[0]` by `*b`.

```
f(char**b){int s=0,e=0,t=0;char*p;do{system("CLS");int i=0;do{if(!t){s+=2;if(strchr(b[i],'}'))e=i;printf(b[i]);}else{while(!(p=b[i]))i++;if(!b[0]&&e==1)e=i;do{putchar((e==i&&t%2&&!isspace(*p))?'*':*p);}while(*p&&*p++!='\n');}}while(b[i++][0]!='T');if(t%2){b[e]=0;e=(b[0]&&e)?e-1:e+1;}t++;Sleep(500);}while(--s>1);}

```

Test code with ungolfed `f`:

```
#include <stdio.h>
#include <windows.h> // to use Sleep and system

s, e, t, i;
f(char**b)
{
    char*p;
    do{
        system("CLS");
        i = 0;
        do
        {
            while (!(p=b[i]))i++; // skip demolished floors
            if (!*b && e==1) e = i;
            while (isspace(*p)) putchar(*p++); // print spaces
            if (!t){ s += 2; e = *p == '{' ? i : e; } // find a bomb and count steps at the first iteration
            do{
                putchar(e == i && t%2 &&*p>0xF ? '*' : *p); // print floor or * for next floor at odd step
            } while (*p && *p++ >0xF); // >0xF is instead of !='\n'
        } while (*b[i++] != 'T'); // until the ground
        if (t++ % 2)
        {
            b[e] = 0; // delete the demolished floor
            e = *b&&e>0 ? e-1 : e+1; // and determine next floor to be demolished
        }
        Sleep(500);
    } while (t<s-1);
}

int main(void)
{
    char * arr[] = { "   |\n",
                     "  |#|\n",
                     "  {#}\n",
                     " |# #|\n",
                     "|# # #|\n",
                     "|# # #|\n",
                     "|# # #|\n",
                     "TTTTTTT" };
    f(arr);
}

```
> 2 votes

# Answer
## Haskell, ~~245~~ 221 bytes

```
import System.Posix.Unistd
r=reverse
c#l|(i,j)<-span(<'!')l=i++(c<$j)
f[b]=[[b]]
f s|(h@(a:b),d:c)<-break(elem '{')s=(h++'*'#d:c):(h++c):f(init h++'{'#last h:c)|1<2=r<$>(f$r s)
mapM((usleep 500000>>).mapM putStrLn).init.f

```

Usage example:

```
mapM((usleep 500000>>).mapM putStrLn).init.f $ ["  |"," {#}"," |#|","|# #|","|# #|","TTTTT"]

```

How it works:

```
c#l|(i,j)<-span(<'!')l=i++(c<$j)    -- helper function that takes a char c and
                                    -- a string l and keeps the leading spaces
                                    -- of l and replaces the rest with c

                                    -- f takes a building (list of strings) and
                                    -- makes the sequence of collapsing buildings
                                    -- as a list of list of strings
f[b]=[[b]]                          -- base case. Stop when there's only a single
                                    -- floor left
f s                                 -- if the building has at least two floors
   |(h@(a:b),d:c)<-break(elem '{')s --   if there is at least one floor above the
                                    --   explosion
        =(h++'*'#d:c) :             --     return the current building with the
                                    --     floor to explode replaced by *
        (h++c) :                    --     followed by the current building with
                                    --     the exploded floor removed
        f(init h++'{'#last h:c)     --     followed by a recursive call
                                    --     with the next to explode floor marked
                                    --     with '{'
   |1<2=r<$>(f$r s)                 --   if all top floors have exploded, reverse
                                    --   the left over floors, let them explode
                                    --   and reverse the floors of each building
                                    --   again.

                      f             -- let the building collapse
                 init               -- f comes with an additional building with
                                    -- a single floor of * only -> drop it
mapM(     )                         -- for every building
     (usleep 500000>>)              --   delay 0.5 sec
             mapM putStrLn          --   and print the floors

```

Note: there's also `threadDelay` from `GHC.Conc` instead of `usleep` from `System.Posix.Unistd` which is a little bit shorter, but it only works with the `GHC` compiler, so it wouldn't be a generic `Haskell` answer.
> 2 votes

# Answer
## Perl, 153 bytes

```
for(@a=<>;$a[$i]!~/{/;$i++){}for(;$a[0]!~/^T/;`sleep .5`){if($P=!$P){$a[$i]=~s/(\S.*\S|\S)/"*" x length($1)/e}else{splice(@a,$i,1);if($i){$i--}}print@a}

```

This uses GNU sleep command to wait for 500 milliseconds.

Ungolfed version

```
for(@a=<>;$a[$i]!~/{/;$i++){}
for(;$a[0]!~/^T/;`sleep .5`){
    if($P=!$P){
       $a[$i]=~s/(\S.*\S|\S)/"*" x length($1)/e
    } else {
       splice(@a,$i,1);
       if($i){$i--}
    }
    print @a
 }

```
> 1 votes

# Answer
# PHP, ~~286~~ ~~282~~ ~~274~~ ~~234~~ 229 bytes

```
<?for($a=$argv,array_shift($a);!strstr($a[+$i++],"{"););while($a[0][0]!=T){$x=&$a[$i-=$i>0];$x=str_pad(substr($x,0,strspn($x," ")),strlen($x),"*");eval($p='echo join("\n",$a),"\n\n";usleep(5e5);');array_splice($a,$i,1);eval($p);}

```

takes input as list of strings from command line arguments (no newline character!)

save to file, run with `php <filename> ' |' ' |#|' ' {#}' ' |# #|' '|# # #|' '|# # #|' '|# # #|' 'TTTTTTT'`

**breakdown**

```
<?
for($a=$argv,array_shift($a);   // import input
    !strstr($a[+$i++],"{"););   // find explosives
while($a[0][0]!=T)              // loop while ground not reached:
{
    $x=&$a[$i-=$i>0];               // move up if possible, reference floor
    $x=str_pad(
        substr($x,0,strspn($x," ")  // keep leading spaces
    ),strlen($x),"*");              // replace rest with asterisks
                                    // print and wait
    eval($p='echo join("\n",$a),"\n\n";usleep(5e5);');
    array_splice($a,$i,1);          // remove current floor
    eval($p);                       // print and wait
}

```
> 1 votes

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


title: Validate a PNG file

text:
# Question
Title: Validate a PNG file
Write a program that can validate a PNG file. Your program should follow the PNG spec and must validate the PNG signature and the 4 critical chunks: `IHDR`, `IDAT`, `PLTE` and `IEND`. Your program must not validate the contents of ancillary chunks, except for their CRC checksums.

Your program must validate the presence of the `PLTE` chunk (that is, `This chunk shall appear for colour type 3, and may appear for colour types 2 and 6; it shall not appear for colour types 0 and 4. There shall not be more than one PLTE chunk.` ref)

Your program must validate chunk order.

Your program must validate CRC checksums.

Your program must validate the compressed data.

You may use runtime code generation+execution (e.g. compress the program itself, or algorithmically write the program itself a la kolmogorov complexity). If any binary blobs are used, their source code will be considered when calculating size.

External library source code size counts towards program size. This is to discourage image-parsing external libraries while allowing e.g. a CRC32 library. Libraries defined in the language specification (aka "standard libraries") don't count as external.

No regex.

You must specify how to input the file. Your program must output to stdout "true" or "false" to answer the question "is the file a valid PNG?".

Failing test files:

```
This file is false.

```

(Yes, that's a plaintext file. Newline-terminated.)

Passing test files:

# Answer
> 4 votes
# Java - 1220 chars

```
import java.io.*;import java.util.zip.*;interface Q{static int i(byte[]b,int i){return java.nio.ByteBuffer.wrap(b).getInt(i);}static boolean v(int x,int...a){return java.util.stream.IntStream.of(a).anyMatch(y->x==y);}static void main(String[]a){byte[]b={-119,80,78,71,13,10,26,10},c={0,0,0,0},d=b.clone();OutputStream I=new InflaterOutputStream(new ByteArrayOutputStream());int l,k,i,t,r=k=i=l=0,H=1229472850,D=1229209940,P=1347179589,E=1229278788,L=8192;DataInputStream in=new DataInputStream(System.in);boolean v;CRC32 C=new CRC32();try{for(v=(in.read(b)>7&&java.util.Arrays.equals(b,d));v=v&&(l=in.readInt())>=0&&in.read(c)>3;){C.update(c);for(byte B:c)v&=(B|32)<123&&(B|32)>96;for(r=0;v&&(t=in.read(b=new byte[l-r>L?L:l-r]))>0;r+=t){C.update(b);if(i(c,0)==D)if(v=v(i,2,3))I.write(b);if(i(c,0)==H&&r==0)if(v=i==0&&t==13){v=i(b,0)>0&&i(b,4)>0&&b[10]==0&&b[11]==0&&v(b[12],0,1)&&((k=b[9])==0&&v(b[8],1,2,4,8,16))||(v(k,2,4,6)&&v(b[8],8,16))||(k==3&&v(b[8],1,2,4,8));i=(v&&k==3)?1:v?k&2:3;}}v&=(k=in.readInt())==(int)C.getValue();C.reset();if(v&(t=i(c,0))==P){v=v(i,1,2)&&l<=768&&l%3==0;i=3;}if(v&t==E){v=l==0;break;}if((t&L)!=0||((t&L<<16)==0&&!v(t,P,H,E,D)))v=0>1;}}catch(IOException e){v=0>1;}System.out.println(v);}}

```

Input is from stdin.

---
Tags: code-golf, decision-problem
---


title: The Most Durable Pokemon Types

text:
# Question
Title: The Most Durable Pokemon Types
# Background

This question is similar to this one. I have provided all of the information needed below. If you are familiar with the other challenge then note that we are ranking all defenses instead of seeing the effectiveness of a single attack. This is important because it means that the tables are inverses of each other and the goal of this challenge is to be without user input.

In Pokemon there are 18 types:

```
Normal    Fighting  Flying  Poison  Ground  Rock
Bug       Ghost     Steel   Fire    Water   Grass
Electric  Psychic   Ice     Dragon  Dark    Fairy

```

Pokemon have either one or two **unique** types that define them (a "type combination"). For example, a Bulbasaur has the type combination Grass/Poison (it has two types, Grass and Poison) and a Charmander has the type combination Fire (having just one type). The order of types does not matter (i.e. Grass/Poison is the same as Poison/Grass).

These types all have strengths and weaknesses:

* A type can be weak to another type. Fire is weak against Water. This results in Fire having a 2× multiplier against Water.
* A type can be resistant to another type. Water is resistant to Water. This results in Water having a 0.5× multiplier against Water.
* A type can be immune to another type. Flying is immune to Ground. This results in Flying having a 0× multiplier against Ground.

Anything else receives a standard 1× multiplier. Normal against Normal would result in a 1× multiplier is an example of this. These strengths and weaknesses can be compounded or negated as well. For example, Fire is weak to Water but a Fire/Water dual type would have a 1× multiplier against Water since the weakness from Fire would negate the resistance from Water. For a full table and a further explanation, see below.

# Objective

The goal here is to output a list of all types combinations, sorted in the order of their defensive ability, and listing their numbers of (resistances+immunities), weaknesses, and the ratio between those. Specifically, the sort order is as follows: type combinations with the best *ratio* of (resistances+immunities) to weaknesses are listed first, and if there is a tie, type combinations with the *most resistances and immunities* will win the tiebreak. You can produce this list via any means (an obvious method is to do a type effectiveness calculation against each type combination, but you are allowed to store precalculated or partially precalculated output in your program if doing so would make it shorter.)

# Type effectiveness table

For a human readable table, see the Pokemon database. **Note: the columns of this list are what we are considering.** But just in case, here is the table I'm thinking of in a compressed computer-friendly matrix of effectiveness. I've multiplied every value by 2 so we don't have to deal with pesky decimals:

```
           Attacking type
            (same order)
   Nor   222222422222202222
   Fir   214211224221422211
D  Wat   211441222222222212
e  Ele   222122224122222212
f  Gra   241114241424222222
e  Ice   242221422222422242
n  Fig   222222222441122124
d  Poi   222212114241222221
i  Gro   224044212222122222
n  Fly   222414120221422222
g  Psy   222222122214242422
   Bug   242212121422422222
T  Roc   114242414122222242
y  Gho   022222012221242422
p  Dra   211114222222224224
e  Dar   222222422204212124
   Ste   142211404111121211
   Fai   222222142221220142

```

# Example

If this problem had requested only output for single-type type combinations, then a valid output would look like this:

```
Steel -> 11/3 = 3.66
Electric -> 3/1 = 3
Poison -> 5/2 = 2.5
Fire -> 6/3 = 2
Water -> 4/2 = 2
Ghost -> 4/2 = 2
Fairy -> 4/2 = 2
Fly -> 4/3 = 1.333
Dragon -> 4/3 = 1.333
Fighting -> 3/3 = 1
Normal -> 1/1 = 1
Ground -> 3/3 = 1
Psychic -> 2/2 = 1
Bug -> 3/3 = 1
Dark -> 3/3 = 1
Grass -> 4/5 = 0.8
Rock -> 4/5 = 0.8
Ice -> 1/4 = 0.25

```

However, your program will also need to list all of the dual-type combinations in the output, so its output will be considerably longer.

Best of luck! Shortest code in bytes wins.

# Answer
> 2 votes
## Python 2, 784 bytes

```
i=['Normal','222222422222202222'],['Fire','214211224221422211'],['Water','211441222222222212'],['Electric','222122224122222212'],['Grass','241114241424222222'],['Ice','242221422222422242'],['Fighting','222222222441122124'],['Poison','222212114241222221'],['Ground','224044212222122222'],['Flying','222414120221422222'],['Psychic','222222122214242422'],['Bug','242212121422422222'],['Rock','114242414122222242'],['Ghost','022222012221242422'],['Dragon','211114222222224224'],['Dark','222222422204212124'],['Steel','142211404111121211'],['Fairy','222222142221220142']
L=[]
for x,X in i:
 for y,Y in i[i.index([x,X]):]:
  S=W=0.
  for a,b in zip(X,Y):A=int(a)*int(b);W+=A>4;S+=A<4
  L+=[([x+'/'+y,x][x==y]+' -> %d/%d'%(S,W),S/W)]
for l in sorted(L, key=lambda l:-l[1]):print'%s = %.2f'%l

```

Outputs:

```
Bug/Steel -> 9/1 = 9.00
Steel/Fairy -> 11/2 = 5.50
Normal/Ghost -> 5/1 = 5.00
Water/Ground -> 5/1 = 5.00
Grass/Steel -> 10/2 = 5.00
Poison/Dark -> 5/1 = 5.00
Poison/Steel -> 10/2 = 5.00
Flying/Steel -> 10/2 = 5.00
Dragon/Steel -> 10/2 = 5.00
Normal/Steel -> 12/3 = 4.00
Electric/Poison -> 8/2 = 4.00
Electric/Steel -> 12/3 = 4.00
Ghost/Dark -> 4/1 = 4.00
Water/Steel -> 11/3 = 3.67
Dark/Steel -> 11/3 = 3.67
Steel -> 11/3 = 3.67
Fire/Steel -> 10/3 = 3.33
Fire/Ground -> 6/2 = 3.00
Water/Flying -> 6/2 = 3.00
Electric -> 3/1 = 3.00
Electric/Flying -> 6/2 = 3.00
Electric/Fairy -> 6/2 = 3.00
Ice/Steel -> 9/3 = 3.00
Fighting/Steel -> 9/3 = 3.00
Rock/Steel -> 9/3 = 3.00
Ghost/Steel -> 12/4 = 3.00
Fire/Electric -> 8/3 = 2.67
Water/Poison -> 8/3 = 2.67
Normal/Poison -> 5/2 = 2.50
Water/Electric -> 5/2 = 2.50
Poison -> 5/2 = 2.50
Ground/Flying -> 5/2 = 2.50
Ground/Steel -> 10/4 = 2.50
Psychic/Steel -> 10/4 = 2.50
Fire/Flying -> 7/3 = 2.33
Water/Fairy -> 7/3 = 2.33
Electric/Ghost -> 7/3 = 2.33
Normal/Electric -> 4/2 = 2.00
Normal/Fairy -> 4/2 = 2.00
Fire -> 6/3 = 2.00
Fire/Poison -> 8/4 = 2.00
Fire/Bug -> 6/3 = 2.00
Fire/Fairy -> 8/4 = 2.00
Water -> 4/2 = 2.00
Water/Ghost -> 8/4 = 2.00
Electric/Bug -> 4/2 = 2.00
Fighting/Poison -> 6/3 = 2.00
Poison/Fairy -> 6/3 = 2.00
Psychic/Ghost -> 4/2 = 2.00
Ghost -> 4/2 = 2.00
Ghost/Fairy -> 4/2 = 2.00
Dragon/Fairy -> 8/4 = 2.00
Fairy -> 4/2 = 2.00
Fire/Ghost -> 9/5 = 1.80
Normal/Fire -> 7/4 = 1.75
Fire/Rock -> 7/4 = 1.75
Fire/Dark -> 7/4 = 1.75
Poison/Dragon -> 7/4 = 1.75
Normal/Water -> 5/3 = 1.67
Fire/Water -> 5/3 = 1.67
Fire/Dragon -> 5/3 = 1.67
Water/Bug -> 5/3 = 1.67
Electric/Fighting -> 5/3 = 1.67
Ghost/Dragon -> 8/5 = 1.60
Fire/Fighting -> 6/4 = 1.50
Water/Dragon -> 3/2 = 1.50
Electric/Dragon -> 6/4 = 1.50
Electric/Dark -> 6/4 = 1.50
Poison/Ground -> 6/4 = 1.50
Poison/Flying -> 6/4 = 1.50
Poison/Rock -> 6/4 = 1.50
Poison/Ghost -> 6/4 = 1.50
Ground/Fairy -> 6/4 = 1.50
Flying/Dragon -> 6/4 = 1.50
Rock/Fairy -> 6/4 = 1.50
Fire/Psychic -> 7/5 = 1.40
Water/Fighting -> 7/5 = 1.40
Water/Dark -> 7/5 = 1.40
Grass/Fairy -> 7/5 = 1.40
Fighting/Dragon -> 7/5 = 1.40
Dragon/Dark -> 7/5 = 1.40
Normal/Flying -> 4/3 = 1.33
Fire/Grass -> 4/3 = 1.33
Fighting/Dark -> 4/3 = 1.33
Poison/Psychic -> 4/3 = 1.33
Ground/Dragon -> 4/3 = 1.33
Flying -> 4/3 = 1.33
Dragon -> 4/3 = 1.33
Dark/Fairy -> 4/3 = 1.33
Normal/Dragon -> 5/4 = 1.25
Water/Rock -> 5/4 = 1.25
Electric/Ground -> 5/4 = 1.25
Electric/Psychic -> 5/4 = 1.25
Electric/Rock -> 5/4 = 1.25
Grass/Poison -> 5/4 = 1.25
Fighting/Bug -> 5/4 = 1.25
Fighting/Ghost -> 5/4 = 1.25
Poison/Bug -> 5/4 = 1.25
Flying/Dark -> 5/4 = 1.25
Water/Psychic -> 6/5 = 1.20
Grass/Ghost -> 6/5 = 1.20
Ground/Ghost -> 6/5 = 1.20
Flying/Rock -> 6/5 = 1.20
Flying/Ghost -> 6/5 = 1.20
Flying/Fairy -> 6/5 = 1.20
Bug/Ghost -> 6/5 = 1.20
Bug/Fairy -> 6/5 = 1.20
Normal -> 1/1 = 1.00
Normal/Fighting -> 4/4 = 1.00
Normal/Ground -> 4/4 = 1.00
Normal/Psychic -> 2/2 = 1.00
Normal/Bug -> 3/3 = 1.00
Normal/Rock -> 5/5 = 1.00
Normal/Dark -> 3/3 = 1.00
Fire/Ice -> 4/4 = 1.00
Water/Grass -> 3/3 = 1.00
Electric/Grass -> 4/4 = 1.00
Grass/Fighting -> 6/6 = 1.00
Grass/Dark -> 7/7 = 1.00
Ice/Poison -> 5/5 = 1.00
Ice/Ghost -> 5/5 = 1.00
Ice/Fairy -> 4/4 = 1.00
Fighting -> 3/3 = 1.00
Fighting/Flying -> 5/5 = 1.00
Fighting/Fairy -> 5/5 = 1.00
Ground -> 3/3 = 1.00
Ground/Bug -> 4/4 = 1.00
Ground/Rock -> 6/6 = 1.00
Ground/Dark -> 6/6 = 1.00
Psychic/Dragon -> 6/6 = 1.00
Psychic/Fairy -> 3/3 = 1.00
Bug -> 3/3 = 1.00
Bug/Dragon -> 5/5 = 1.00
Bug/Dark -> 5/5 = 1.00
Rock/Ghost -> 6/6 = 1.00
Rock/Dark -> 7/7 = 1.00
Dark -> 3/3 = 1.00
Grass/Psychic -> 6/7 = 0.86
Fighting/Rock -> 6/7 = 0.86
Normal/Grass -> 5/6 = 0.83
Grass/Bug -> 5/6 = 0.83
Fighting/Ground -> 5/6 = 0.83
Ground/Psychic -> 5/6 = 0.83
Rock/Dragon -> 5/6 = 0.83
Grass -> 4/5 = 0.80
Grass/Flying -> 4/5 = 0.80
Flying/Psychic -> 4/5 = 0.80
Flying/Bug -> 4/5 = 0.80
Rock -> 4/5 = 0.80
Electric/Ice -> 3/4 = 0.75
Grass/Ground -> 3/4 = 0.75
Ice/Flying -> 3/4 = 0.75
Ice/Bug -> 3/4 = 0.75
Psychic/Rock -> 5/7 = 0.71
Grass/Dragon -> 4/6 = 0.67
Ice/Rock -> 4/6 = 0.67
Ice/Dark -> 4/6 = 0.67
Fighting/Psychic -> 2/3 = 0.67
Psychic -> 2/3 = 0.67
Psychic/Bug -> 4/6 = 0.67
Bug/Rock -> 2/3 = 0.67
Ice/Dragon -> 3/5 = 0.60
Grass/Ice -> 4/7 = 0.57
Normal/Ice -> 2/4 = 0.50
Water/Ice -> 2/4 = 0.50
Grass/Rock -> 2/4 = 0.50
Ice/Fighting -> 3/6 = 0.50
Psychic/Dark -> 1/2 = 0.50
Ice/Ground -> 2/5 = 0.40
Ice/Psychic -> 2/6 = 0.33
Ice -> 1/4 = 0.25

```

---
Tags: code-golf, compression
---


title: Line ending conversion program

text:
# Question
Title: Line ending conversion program
Write a program or function that alters the file at a user-specified filename via replacing all instances of UNIX line endings with Windows line endings and vice versa.

Clarifications:

* For the purposes of this problem, a UNIX line ending consists of the octet `0A` in hexadecimal, except when it is immediately preceded by the octet `0D`. A Windows line ending consists of the two octets `0D 0A`.
* As usual, your program only has to run on one (pre-existing) interpreter on one (pre-existing) operating system; this is particularly important for this question, where I imagine many submissions will succeed on UNIX but fail on Windows, or vice versa, due to line ending conversions built into the language.
* To alter a file, you can either edit the file "in-place", or read the file, then save the contents of the file back over the original. However, the program must alter a file on disk; just taking a string as an argument and returning a string specifying the result is not acceptable for this challenge, because the challenge is partially about testing the ability to handle files.
* The program's user must have some method of specifying the filename to change without needing to alter the program itself (i.e. you can't use hardcoded filenames). For example, you could read the name of the file to modify from a command-line argument, or from standard input. If you're submitting a function rather than a full program, making it take a filename as argument would be acceptable.
* The input to the program must be specified as a *filename* specifically; you can't take input other than strings (assuming that you're using an operating system in which filenames are strings; in most, they are), and you can't place restrictions on what filenames you accept (you must accept all filenames that the operating system would accept, and that refer to a file that the user running the program has permission to read and write). For example, you can't write a function that takes a UNIX file descriptor as an argument and requires the file to already be open, and you can't write an editor macro that assumes the file has already been opened in the current buffer.
* If the file is missing a trailing newline before you alter it, it should continue to be missing a trailing newline after you alter it. Likewise, if the file does have a trailing newline, you should preserve that (leaving the file with the other sort of trailing newline).
* If the input file has mixed line ending conventions, you should nonetheless translate each of the line endings to the opposite sort of line ending (so the resulting line will still have mixed line ending conventions, but each individual line will have been converted).
* The program is intended for use converting text files, and as such, you don't have to be able to handle *nonprintable* control codes in the input (although you can if you wish). The nonprintable control codes are the octets from `00` to `1F` (hexadecimal) inclusive except for `09`, `0A`, `0B`, `0C`, `0D`. It's also acceptable for your program to fail on input that cannot be decoded as UTF-8 (however, there is no requirement to place a UTF-8 interpretation on the input; programs which handle all the high-bit-set octets are also acceptable).
* As an exception from the specification, it's acceptable for the program to do anything upon seeing the octet sequence `0D 0D 0A` in the input (because it's impossible to comply with the spec when this sequence appears in the input: you'd have to generate `0D` followed by an `0A` which is not immediately preceded by `0D`, which is a contradiction).

The shortest program wins, under usual rules (i.e. fewest bytes in the program you submit). Good luck!

## Test cases

Here are some hex dumps of files you can use to test your program. All these test cases are *reversible*; swapping the input and output gives another valid test case. Note that your program should work for cases other than the given test-cases; these are just some examples to help testing:

---

**Input**

```
30 31 32 0A 33 34 35 0A 36 37 38 0A

```

**Output**

```
30 31 32 0D 0A 33 34 35 0D 0A 36 37 38 0D 0A

```

---

**Input**

```
30 31 0A 0D 0A 32 0A 0A 0A 33 34

```

**Output**

```
30 31 0D 0A 0A 32 0D 0A 0D 0A 0D 0A 33 34

```

---

**Input** and **Output** both a zero-byte file.

# Answer
> 4 votes
# Sed (GNU), ~~27~~, ~~37~~, 24 bytes (21 byte + *"-zi"* flags)

(21 byte for code + 3 for "-zi" flags)

EDIT: I've just spotted an issue with an extra carriage return being appended to files with no trailing newline, when going from Unix to DOS.

This is now fixed, and I've also re-profiled my answer to pure *Sed* instead of *Bash*, and added some tests.

**Golfed**

```
s|\n|\r\n|g;s|\r\r||g

```

**Usage**

```
sed -zi -f newline.sed myfile.txt

```

**Tests**

> An old pond!
> A frog jumps in —
> the sound of water.
>
> (Matsuo Basho)

**Test Case #1, Unix newlines + trailing newline**

```
>xxd haiky.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e0a                           ater.

>sed -zi -f newline.sed haiku.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210d 0a41  An old pond !..A
0000010: 2066 726f 6720 6a75 6d70 7320 696e 20e2   frog jumps in .
0000020: 8094 0d0a 7468 6520 736f 756e 6420 6f66  ....the sound of
0000030: 2077 6174 6572 2e0d 0a                    water...

>sed -zi -f newline.sed haiku.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e0a                           ater..

```

**Test Case #2, Unix newlines, no trailing newline**

```
>xxd haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e                             ater.

>sed -zi -f newline.sed haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210d 0a41  An old pond !..A
0000010: 2066 726f 6720 6a75 6d70 7320 696e 20e2   frog jumps in .
0000020: 8094 0d0a 7468 6520 736f 756e 6420 6f66  ....the sound of
0000030: 2077 6174 6572 2e

>sed -zi -f newline.sed haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120  An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280  frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077  ..the sound of w
0000030: 6174 6572 2e                             ater.

```

# Answer
> 1 votes
# MATL, 28 bytes

```
&Z$[13X]OZt5E6MZtO10ZtG3$FZ#

```

This works in current release (19.5.1), which is predates the challenge.

I have only tested it on Windows, but it should work on Linux too.

Because of file input/ouput this can't be tested online directly. But here is an online version that accepts and produces hex-dump strings with the format shown in the challenge.

### Explanation

```
&Z$      % Implicitly input filename, and read as chars
[13X]    % Push array [13 10]
O        % Push 0
Zt       % Replace [13 10] by 0
5E       % Push 10
6M       % Push [13 10] again
Zt       % Replace 10 by [13 10]
O        % Push 0
10       % Push 10
Zt       % Replace 0 by 10
G        % Push filename again
3$FZ#    % Overwrite the file with the modified char array

```

# Answer
> 0 votes
# C, ~~240~~ ~~219~~ ~~211~~ 227 bytes

Saving a little by `#define...fputc` and a lot by converting to a program. -8 bytes for converting some logic. +16 bytes for in-place file replacement using the temporary file `T`

Takes filenames via command line parameters.

```
#import<stdio.h>
#define P(c) fputc(c,o)
d;int main(int c,char**v){FILE*i=fopen(v[1],"r"),*o=fopen("T","w");while((c=fgetc(i))!=-1){if(c==10)P(13),P(c);else if(c==13){if((d=fgetc(i))!=10)P(c);P(d);}else P(c);}rename("T",v[1]);}

```

Ungolfed:

```
#import<stdio.h>
#define P(c) fputc(c,o)
d;
int main(int c,char**v){
  FILE*i=fopen(v[1],"r"),*o=fopen("T","w");
  while((c=fgetc(i))!=-1){
    if(c==10)
      fputc(13,o),fputc(c,o);
    else if(c==13)
      if((d=fgetc(i))!=10)
        fputc(c,o);
      fputc(d,o);
    else fputc(c,o);
  }
  rename("T",v[1]);
}

```

Usage:

```
./a.out test_in.txt

```

---
Tags: code-golf, conversion, file-system, whitespace
---


title: RPN calculator without pointers

text:
# Question
Title: RPN calculator without pointers
Me and some other students were at a bar discussing programming languages, in particular the C programming language. At some point a first year student said he didn't need no damn pointers. Another student said that he couldn't use arrays either since "they're basically pointers".

This led to a programming challenge:
Implement a reverse polish notation calculator in C without using arrays and pointers.

## Description

You must implement a RPN calculator that

* operates on integers,
* supports addition (+),
* supports multiplication (\*).

Your implementation

* must not use pointers or arrays
* you may use structs
* the input is read from stdin
* your lexer may use pointers and arrays (but it shouldn't be needed)
* when EOF is read then print the top of the stack
* the behavior can be as undefined as you want for malformed input
* should be in a language sufficiently c-like that the "no-pointers and no-arrays" restriction has a sensible interpretation (please elaborate if you think people may not get it)

The lexer could have a signature a la thisNote: this is not taken from my own code. Please tell me if there's an error or it looks unreasonable

```
typedef enum {
  val,
  op,
  eof
} TYPE;

typedef enum {
  add,
  mul
} OPERATION;

typedef struct {
  TYPE type;
  union {
    int val;
    OPERATION op;
  } dat;
} token;

token next();

```

A solution using a stack with `push()` and `pop()` could look something like this:

```
token t;
while ((t = next()).type != eof) {
  switch (t.type) {
    case val:
      push(t.dat.val);
    case op:
      switch (t.dat.op) {
        case add:
          int v1 = pop();
          int v2 = pop();
          push(v1+v2);
        case mult:
          int v1 = pop();
          int v2 = pop();
          push(v1*v2);
      }
    case eof:
      printf("Result: %d\n", pop());
  }
}

```

Other languages than C are also accepted, but the constraints should be comparable. It is hard to state the constraints in a way that fits all languages, but something like »all used data structures must have fixed size and fixed "depth"«. If there's any doubt please ask in the comments.

 I have a solution that I can post. After cleaning up the code a bit. I wrote it the morning after while hungover.

# Answer
> 4 votes
This is pretty ugly, but I think it works. I've avoided using `null` to make it as obvious as possible that the references could be passed on the stack. I may rewrite this in the morning to have an extra token type of `NULL`.

```
import java.io.IOException;

public class RPN
{
    public static void main(String[] args) throws IOException {
        Token result = depth0();
        if (result.type != Token.EOF) throw new IllegalStateException("Bad input");
        System.out.println(result.value);
    }

    private static Token depth0() throws IOException {
        Token tok = Lexer.lex();
        if (tok.type != Token.NUMBER) throw new IllegalStateException("Bad input");
        return depth1(tok);
    }

    private static Token depth1(Token s1) throws IOException {
        while (true) {
            Token s2 = Lexer.lex();
            switch (s2.type) {
                case Token.EOF:
                    return new Token(Token.EOF, s1.value);
                case Token.NUMBER:
                    s1 = depth2(s1, s2);
                    if (s1.type == Token.EOF) return s1;
                    break;
                default:
                    throw new IllegalStateException("Bad input");
            }
        }
    }

    private static Token depth2(Token s1, Token s2) throws IOException {
        while (true) {
            Token s3 = Lexer.lex();
            switch (s3.type) {
                case Token.EOF:
                    return new Token(Token.EOF, s2.value);
                case Token.OPERATOR:
                    return new Token(Token.NUMBER, s3.value == Token.OP_PLUS ? s1.value + s2.value : s1.value * s2.value);
                case Token.NUMBER:
                    s2 = depth2(s2, s3);
                    if (s2.type == Token.EOF) return s2;
                    break;
                default:
                    throw new IllegalArgumentException("Bug in lexer");
            }
        }
    }

    static class Lexer {
        private static boolean hasPushback = false;
        private static int pushback;

        private static int read() throws IOException {
            if (hasPushback) {
                hasPushback = false;
                return pushback;
            }

            // Assume input is in ASCII
            return System.in.read();
        }

        private static void pushback(int ch) {
            if (hasPushback) throw new IllegalStateException();
            hasPushback = true;
            pushback = ch;
        }

        public static Token lex() throws IOException {
            while (true) {
                int ch = read();
                switch (ch) {
                    case -1:
                        return new Token(Token.EOF, Token.EOF);
                    case '-':
                        return new Token(Token.NUMBER, -lexInteger(0));
                    case '0': case '1': case '2':
                    case '3': case '4': case '5':
                    case '6': case '7': case '8':
                    case '9':
                        return new Token(Token.NUMBER, lexInteger(ch - '0'));
                    case '+':
                        return new Token(Token.OPERATOR, Token.OP_PLUS);
                    case '*':
                        return new Token(Token.OPERATOR, Token.OP_TIMES);
                    default:
                        // Whitespace or comment
                        break;
                }
            }
        }

        private static int lexInteger(int value) throws IOException {
            while (true) {
                int ch = read();
                if (ch < '0' || ch > '9') {
                    pushback(ch);
                    return value;
                }

                value = value * 10 + (ch - '0');
            }
        }
    }

    static class Token {
        public static final int NUMBER = 0;
        public static final int OPERATOR = 1;
        public static final int EOF = -1;

        public static final int OP_PLUS = 0;
        public static final int OP_TIMES = 1;

        public final int type;
        public final int value;

        public Token(int type, int value) {
            this.type = type;
            this.value = value;
        }
    }
}

```

Sample usage:

```
$ javac RPN.java && java RPN <<<"1 2 3 4 5 ****2+"
122

```

# Answer
> 7 votes
This is a stand-alone C version, it doesnt require any external lexer. It works recursivly, like ratchet freaks solution.

All characters that are not `+`, `*`, `-` or numbers are treated as spaces. A `-` is treated as a space if it is not directly followed by a number.

```
#include <stdio.h>

int rpn(int n1, int n2) {
        int c, sign = 1, skip = 0;
        if(n1 < 0) sign = -1;
        do {
                c = getchar();
                if(c == '+') return n1+n2;
                if(c == '*') return n1*n2;
                if(c >= 48 && c <= 57) {
                        if(!skip) n1 = n1 * 10 + sign * (c - 48);
                        else n1 = rpn(sign * (c - 48), n1);
                } else {
                        skip = 1;
                        sign = 1;
                }
                if(c == '-') sign = -1;
        } while(c != EOF);
        return n1;
}

void main() {
        printf("%d\n", rpn(0, 0));
}

```

# Answer
> 3 votes
use recursion:

```
enum TYPE {
  val,
  op,
  eof
};

enum OPERATION {
  add,
  mul
};

struct token{
  TYPE type;
  union {
    int val;
    OPERATIOIN op;
  }
}

token parse(int val1,int val2){
    token t;
    //next() is the lexer
    while((t=next()).type!=TYPE.EOF){
        if(t.type==TYPE.op){//calculate the value
            return token(TYPE.val,t.op==add?val1+val2:val1*val2);
        }else if(t.type==TYPE.val){
            //recurse and pass the top 2 values on the stack
            t= parse(val2,t.val);
            if(t.type==TYPE.eof)return t;
            else val2=t.val;
        }else{
             return token(eof,val2);
        }
    }
}

```

I returned token so I can stop the recursion cleanly

# Answer
> 2 votes
2 uses of pointers are collected at the top, and **are permitted by the rules** as these are a necessary part of I/O at the level of file descriptors. Uses C99 compound literals and POSIX low-level file operations, reading and writing one byte at a time. There is also one implicit `FILE *` returned by `tmpfile()` which is immediately converted by `fileno()` to an integer.

This code implements the RPN calculator as a Semi-Thue system that works like a *queue*. ("Thue" is pronounced /too-ay/, like "2 A".) It uses iteration and a tempfile to evaluate the formula left-to-right, examining up to 3 tokens, possibly reducing, and writing into a new temp file for the next iteration.

It waits for enter before each pass. Terminate with an interrupt signal (`ctrl-C`). A simple extension would allow it to detect when a string is no longer reducing from one pass to the next, and terminate.

```
#define Read(f,x) read(f,&x,1)
#define Write(f,x) write(f,&x,1),write(1,&x,1)

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

typedef union {
    enum tag {number, oper, eof} tag;
    struct {
        enum tag tag;
        int val;
    } num;
    struct {
        enum tag tag;
        char val;
    } op;
} token;

token input(int in){
    char b;
    int a;
    char o;
    a=0;
    o=0;
    do {
        if (!Read(in,b)) {
            return (token){.tag=eof};
        }
        if (b=='\n') {
            return (token){.tag=eof};
        }
        if (b>='0'&&b<='9') {
            a*=10;
            a+=b-'0';
        } else if (b=='+'||b=='*') {
            o=b;
        }
    } while(b!=32);

    if (o)
        return (token){.op.tag=oper, .op.val=o};
    else
        return (token){.num.tag=number, .num.val=a};
}

output(int out, token t){
    char b;
    int c;
    switch(t.tag){
    case number:
        c=t.num.val>9?(int)floor(log10((double)t.num.val)):0;
        //b = c + '0'; Write(out,b);
        for( ; c>=0; c--) {
            b = '0' + (t.num.val/(int)pow(10.0, c)) % 10;
            Write(out,b);
        }
        break;
    case oper:
        b = t.op.val;
        Write(out,b);
        break;
    case eof:
        b = '\n';
        Write(out,b);
        return;
    }
    b = 32;
    Write(out,b);
}

int rpn(int in, int out) {
    token x,y,z;
    char b;
read_x:
    //b='X';write(1,&b,1);
    x = input(in);
    //b='A'+x.tag;write(1,&b,1);
    switch (x.tag){
    case eof:
        output(out, x);
        return EOF;
    case oper:
        output(out, x);
        goto read_x;
    }
read_y:
    //b='Y';write(1,&b,1);
    y = input(in);
    //b='A'+y.tag;write(1,&b,1);
    switch (y.tag){
    case eof:
        output(out, x);
        output(out, y);
        return EOF;
    case oper:
        output(out, x);
        output(out, y);
        goto read_x;
    }
read_z:
    //b='Z';write(1,&b,1);
    z = input(in);
    //b='A'+z.tag;write(1,&b,1);
    switch(z.tag){
    case eof:
        output(out, x);
        output(out, y);
        output(out, z);
        return EOF;
    case number:
        output(out, x);
        x.num.val = y.num.val;
        y.num.val = z.num.val;
        goto read_z;
    case oper:
        switch(z.op.val){
        case '+':
            x.num.val = x.num.val + y.num.val;
            break;
        case '*':
            x.num.val = x.num.val * y.num.val;
            break;
        }
        output(out, x);
        goto read_x;
    }
    return 0;
}

main(){
    int i=0,o;
    char b;
    token t;
    do {
        o = fileno(tmpfile());
        rpn(i,o);
        i = o;
        lseek(i, 0, SEEK_SET);
    } while(Read(0,b));
}

```

In action:

```
./2A
1 2 3 4 5 6 7 8 9 10 + + + + + + + + +
1 2 3 4 5 6 7 8 19 + + + + + + + +

1 2 3 4 5 6 7 27 + + + + + + +

1 2 3 4 5 6 34 + + + + + +

1 2 3 4 5 40 + + + + +

1 2 3 4 45 + + + +

1 2 3 49 + + +

1 2 52 + +

1 54 +

55

55

55

```

# Answer
> 0 votes
# RProgN, 2 Bytes

```
do

```

Evaluates as RProgN. Any valid RPN is valid Syntax is RProgN by design, And RProgN is stack based. However, this prints the entire stack after running, not just the top of the stack. This can be resolved with:

```
do p w{ }

```

Which prints the top of the stack, then empties the stack.

Try it online

---
Tags: math, popularity-contest, restricted-source
---