# Question
Title: Define a function f such that f(f(n)) = -n for all non-zero integers n
> This challenge was inspired by a programming blog I frequent. Please see the original post here: A Programming Puzzle

---

# Challenge

Define a function \\$f:\mathbb{Q}\to\mathbb{Q}\\$ such that \\$f(f(n)) = -n\\$ for all non-zero integers \\$n\\$, and where \\$\mathbb{Q}\\$ is the set of rational numbers.

# Details

In whatever language you prefer, please define **one** function or program \\$f\\$ that accepts as parameter **one** number \\$n\\$ and returns or outputs **one** number \\$f(n)\\$.

Input may be provided through whichever mechanism is most natural for your language: function argument, read from STDIN, command-line argument, stack position, voice input, gang signs, etc.

Output should be a return value from a function/program or printed to STDOUT.

I would like to restrict answers to functions that do not take advantage of program state or global memory/data that is visible from outside of the function \\$f\\$. For example, keeping a counter outside of \\$f\\$ that counts how many times \\$f\\$ was called and just doing a negation based on this count isn't very challenging or interesting for anyone. The decisions \\$f\\$ makes should rely only on data within \\$f\\$'s lexical scope.

However, this restriction is probably inappropriate for some stack-oriented languages or other types of languages that do not distinguish these types of data or scopes. Please use your best judgement to keep with the spirit of this challenge.

---

# Scoring

Standard code golf rules apply - your score is the number of **bytes** in your source code.

The minimal answer requires the domain and codomain of \\$f\\$ to be a subset of the rationals \\$\mathbb{Q}\\$. If you restrict your domain and codomain of \\$f\\$ to the integers \\$\mathbb{Z}\\$, then your score is the ceiling of 90% of the number of **bytes** in your source code.

# Tiebreak

In the event of a tie, the following will be used in order:

1. Fewest number of printable non-whitespace **symbols** in your source code
2. Earliest date and time of answer submission

---

You are not required to support arbitrarily sized numbers. Please interpret the sets \\$\mathbb{Z}\\$ and \\$\mathbb{Q}\\$ as datatypes in your chosen language (typically integer and floating point, respectively).

If your solution relies entirely on the underlying structure or bit pattern of a data type, please describe its limitations and how it is being used.

# Answer
> 12 votes
## J, 9 points (10 chars)

Based on stackoverflow answer:

```
   (*-[*_1&^)

```

First idea (13 chars):

```
   ((-*)-2&|*+:)

   ((-*)-2&|*+:) _10 _9 _8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8 9 10
_9 10 _7 8 _5 6 _3 4 _1 2 0 _2 1 _4 3 _6 5 _8 7 _10 9

   ((-*)-2&|*+:) _9 10 _7 8 _5 6 _3 4 _1 2 0 _2 1 _4 3 _6 5 _8 7 _10 9
10 9 8 7 6 5 4 3 2 1 0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _10

```

# Answer
> 15 votes
## Python: ~~61 34 30 29~~ 27 points

f: Q -\> Q

in math:

```
       | 0.5-x   if x is in Q \ Z
f(x) = |
       | x+0.5   if x is in Z

```

in Python:

```
f=lambda x:.5+[x,-x][x%1>0]

```

tested with

```
filter(lambda n: n[0] != -n[1], map(lambda n:(n,f(f(n))),range(0,50)))

```

logic behind this:

When you take an integer `n` and put it into `f` you will get `x+0.5`. This is not an integer any more, so the next application will be `0.5-(x+0.5)` which is `-x`.

## Credits

Thanks to

* Bakuriu for striping it down from 61 characters to 34 characters.
* Volatility for further reducing code size to 30 characters.
* copy for reducing code size to 29 characters (and fixing a potential floating point problem).
* aditsu for mentioning an inconsistency that came with the changes above.

## Notes

First I thought this would be ok

```
f = lambda n: 1j*n

```

but its f:N-\>C and that is not allowed :-/

# Answer
> 11 votes
## C, 41 points (41 or 45 chars)

Works using both 32- and 64-bit.

`f : Z -> Z` (except `INT_MAX`):

```
f(n){return (abs(n)%2*2-1)*n+n?(-n<n)*2-1:0;}

```

---

If we don't have to include `0` we can shave off some chars (41 chars):

`f : Z -> Z` (except `0` & `INT_MAX`):

```
f(n){return (abs(n)%2*2-1)*n+(-n<n)*2-1;}

```

---

This function works by dividing all integers into 4 groups based on their sign and parity.

So we have the 4 different combinations:

```
+ even, + odd, - even, - odd

```

As we need to switch the sign of the number, but not the parity after two passes, we get two different possible sequences:

```
  + even -> - odd -> - even -> + odd -\
^-------------------------------------/

  + even -> + odd -> - even -> - odd -\
^-------------------------------------/

```

In this example I have chosen the first one.

First we need to map all even positive integers to odd negative integers. We do this by changing the sign and incrementing the number (you could also choose to decrement the number instead):

```
f1(n) = -n + 1

```

We then need to map all odd negative integers to even negative integers. We need to make sure that `f2(f1(n)) = -n`:

```
f2(f1(n)) = -n
f2(-n + 1) = -n
f2(-n) = -n - 1
f2(n) = n - 1

```

Using the same methods we find `f3` and `f4`:

```
f3(n) = -n - 1
f4(n) =  n + 1

```

To combine these functions into one single function, we observe that every time `n` is even we switch the sign of `n` and every time `n` is positive we increment by one and otherwise we decrement by one:

```
f1(n) = -n + 1 (+ even)
f2(n) =  n - 1 (- odd)
f2(n) = -n - 1 (- even)
f4(n) =  n + 1 (+ odd)

```

This can thus be rewritten as:

```
f(n) = odd(n) * n + sign(n)

```

where `odd(n)` returns `1` for odd numbers and `-1` for even numbers.

There are 4 solutions total:

```
f(n) = odd(n) * n + sign(n)  (edge cases: f(f(0))  -> -2, f(f(INT_MAX))   -> -8)
f(n) = even(n) * n - sign(n) (edge cases: f(f(0))  -> -2, f(f(INT_MIN+1)) -> -6)
f(n) = odd(n) * n - sign(n)  (edge cases: f(f(1))  -> -3, f(f(INT_MIN))   -> -5)
f(n) = even(n) * n + sign(n) (edge cases: f(f(-1)) -> -1, f(f(INT_MIN))   -> -5)

```

`INT_MIN` might always be considered an edge case in all 4 functions as `-INT_MIN == INT_MIN` =\> `f(f(INT_MIN)) = INT_MIN`.

# Answer
> 9 votes
Here's my go at it.

```
long f(int i){return i;}
int f(long i){return -i;}

```

Live example:

```
int main()
{
  for(int i=-10; i<10; i=i+3)
    std::cout << f(f(i)) << "\n";
}

```

The input types cn be arbitrarily tailored to suit your needs. This version works for integer literals that are smaller in magnitude than 2^32-1.

# Answer
> 6 votes
# JavaScript, 18

```
f=n=>n%1?.5-n:n+.5

```

Using the new fat arrow notation (Firefox 22).

Other version (18):

```
f=n=>n%1?-.5/n:.5/n

```

Previous version (20):

```
f=n=>n-~~n?.5-n:n+.5

```

Example:

```
> [-3,-2,-1,1,2,3].map(f).map(f)
[3, 2, 1, -1, -2, -3]

```

# Answer
> 4 votes
# Mathematica 18

```
f=#+1/2-4#(#-⌊#⌋)&

```

Here `⌊...⌋` is the floor function. It uses only rational numbers (not lists, complex numbers, etc)

```
f[10]
f[f[10]]

```

> 21/2
>
> -10

```
f[-5]
f[f[-5]]

```

> -9/2
>
> 5

# Answer
> 3 votes
x86 assembly language (FASM). The argument and the result are in eax register.

It works properly for -2^30 \< N \< +2^30-1

16 bytes executable code.

```
        use32

f_n:
        lea     edx, [2*eax]
        xor     edx, eax
        btc     eax, 30
        shl     edx, 1
        jnc     .end
        neg     eax
.end:
        retn

```

# Answer
> 3 votes
# Common Lisp: 35 bytes

```
(defun f(x)(/(if(> 1 x)-1/2 1/2)x))

```

# Scheme (and Racket): 36 bytes

```
(define(f x)(/(if(> 1 x)-1/2 1/2)x))

```

Ungolfed with comments and explanation:

```
(define (f x)
  (/             ;; divide
     (if (> 1 x) ;; if x is below 1
         -1/2    ;; then -1/2 (the fraction)
         1/2)    ;; else 1/2 (the fraction)
      x))        ;; gets divided with x

```

For any number `x` in `[1,->]` the `if` will turn into the fraction `1/2` which is a real exact number in both languages.

The divide part will then become `(/ 1/2 x)` so the fraction will become `1/(x*2)` which always is below `1`. For `1` it will be `1/2`, for `2` it's `1/4`, etc.

For any number below 1 the `if` will turn in to the fraction `-1/2`, which makes the function do `(/ -1/2 x)` which is `-1/(2*x)` but since we can expect the value to be result of the previous run we can substitute x for 1/(x\*2) making a double application `-1/((1/(x*2))*2) = -x`

E.g. since `1` turns into `1/2` the second application is `(/ -1/2 1/2) ==> -1`

# Answer
> 3 votes
# C, 60 (⌈66 * .9⌉)

```
int f(int x){if(!x&1||!~x)return ~x;if(x<0)return x-1;return x+1;}

```

Here is an uncondensed version:

```
int f(int x){
    if(!x&1 || !~x) return ~x;
    if(x<0) return x-1;
    return x+1;
}

```

This method works using only integers, so it gets the 90% score bonus. I was originally writing it in java, but realized that this program in particular could benefit from C-style logical operators.

As there is no integer corresponding to `-INT_MIN`, `f(f(INT_MIN))` returns `INT_MIN` instead.

The underlying mapping is algebraically rather simple. Executing the statement `x=f(x)` replaces x with:

* `x+1`, if `x` is positive and odd
* `-x+1`, if `x` is positive and even
* `x-1`, if `x` is negative and odd
* `-x-1`, if `x` is negative and even

The result of each case will fall under the next case the next time the function is applied to x.

As you can see, composing a case with the case following it yields `-x`.

The code is a result of some clever simplification of the function to take advantage of the bit structure of two's compliment integers.

# Answer
> 3 votes
# \>\<\>, 21 + 3 = 24 bytes, 22 points

```
:0)$:0($:1$2%2*-*+-n;

```

Use the official Python interpreter, and use the `-v` command line option to enter input, at a cost of 3 bytes.

I have a feeling that this could be better--I'll keep looking at it and try to golf it down.

Given input `n`, the program outputs

```
(n>0) - ((n<0) + n * (1 - 2*(n%2)))

```

where `(n>0)` and `(n<0)` are booleans. This is equivalent to Gelatin's Python answer

```
(n>0) - (n<0) - n * (-1)**n

```

but `><>` doesn't have a built-in exponentiation operator so we use `(1 - 2*(n%2))` in place of `(-1)**n`.

### What follows is mathematical theory -- read if (and only if) you are interested:

Given any function `f: Z -> Z` such that `f(f(n)) = -n` for all `n` in `Z`, we see immediately that `f(f(f(f(n)))) = n`, or in other words, `f^4` is the identity function. In particular, `f` is invertible, and its inverse function is `f^3`. Thus `f` is a permutation of `Z`, and since `f^4 = Id`, it follows that every orbit (or cycle) of `f` has size either `1`, `2`, or `4`.

Next, we see that `f(0) = 0`. Proof: `f(0) = f(-0) = f(f(f(0))) = -f(0)`, so `f(0) = 0`, as desired. Conversely, suppose `x` is in a cycle of length `1` or `2`, so `f(f(x)) = x`. Then `-x = x` so `x = 0`.

Thus `f` is made up entirely of 4-cycles, except for the fixed point (1-cycle) at `0`.

Further, every 4-cycle must have the form `(x, y, -x, -y)`, and by rotating the cycle around we may assume that `x` and `y` are both positive. Conversely, every such product of 4-cycles partitioning the nonzero integers determines a choice of `f`.

Thus each choice of `f` corresponds uniquely to a directed graph whose vertices are the positive integers, such that every vertex is incident to exactly one arrow, either entering or exiting. More precisely, in the underlying undirected graph, every vertex has degree exactly `1`. (Each 4-cycle `(x y -x -y)` with `x` and `y` positive corresponds to the arrow `x --> y`.)

The function in this answer (and several other answers here) corresponds to the graph where `1 --> 2`, `3 --> 4`, and in general `2k-1 --> 2k`.

Such graphs are in bijection with infinite sequences of ordered pairs `(a_n, p_n)`, where each `a_n` is a positive integer and each `p_n` is either `0` or `1`: given a sequence `(a_1, p_1), (a_2, p_2), (a_3, p_3), ...`, we first pair `1` with `1 + a_1`, and then we form either the arrow `1 --> 1 + a_1` or the arrow `1 + a_1 --> 1` depending on whether `p_1` is `0` or `1`. Essentially, the arrow is either a `<` sign or a `>` sign, depending on the parity of `p_1`.

Next, take the smallest unpaired positive integer `k`, and count up from `k`, exactly `a_2` steps, SKIPPING any number that is already paired with something. Pair `k` with the result, and set the direction of the arrow depending on `p_2` as above. Then repeat with `(a_3, p_3)`, etc.

Each arrow will eventually be determined this way, so the process is well defined. The function in this answer corresponds to the sequence `(1,0), (1,0), (1,0), ...`, since at step `n` the smallest unpaired integer is `2n-1` and no integers larger than `2n-1` have been paired with anything, so we get `2n-1 --> 2n` for each `n` (arrows are oriented this way because each `p_n` equals `0`).

The cardinality of this set is `(N*2)^N = N^N`, which by the last paragraph of this answer equals `2^N`, the cardinality of the real numbers.

# Answer
> 2 votes
To fix the earlier J answer (I don't have enough reputation to comment on the original):

```
(*+[*1-~2*2|])

```

It just replaces the `_1&^` with `1-~2*2|]`, which gives the opposite sign. So I changed the `-` to a `+` (which only matters on input of `1` and `_1`).

Here are the tests:

```
   (*+[*1-~2*2|])6 3 _9 _8 1r2 _4.6 0 1 _1
7 _2 8 _9 1 7.28 0 2 _2
   (*+[*1-~2*2|])7 _2 8 _9 1 7.28 0 2 _2
_6 _3 9 8 0 _10.3568 0 _1 1

   NB. f^:2 = f@:f
   (*+[*1-~2*2|])^:(2)6 3 _9 _8 1r2 _4.6 0 1 _1
_6 _3 9 8 2 _5.0832 0 _1 1

```

As you can see, the domain and range are of all real numbers, but it only works for integers (including 0).

Explanation:

```
(   *     + [ *  1-~    2*     2|]    )
 signum n + n * pred (twice (n mod 2))

```

# Answer
> 2 votes
## GolfScript `ceiling(26*.9)=24`

Golfscript only handles integers, so apply the `Z` bonus for a total of 24 points:

```
.{..0>2*(\)2%!2*(@*+}{ }if

```

The special case of 0 accounts for 8 characters. Ignoring 0, we can have a 17 point answer:

```
..0>2*(\)2%!2*(@*+

```

This code does the following to an integer `x` on top of the stack:

* If `x` is 0, leave `0` on the stack and apply no more rules.
* If `x` is even, negate `x`.
* If `x` is positive, add `1`.
* If `x` is negative, subtract `1`.

This logically connects sets of 4 numbers in a cycle, where `f` traverses elements of the cycle, and opposite corners of the cycle are negatives of each other. Every integer is part of exactly 1 such cycle, except 0 which is special cased. For example, for `{-8, -7, 7, 8}`:

* `7 f -> 8`
* `8 f -> -7`
* `-7 f -> -8`
* `-8 f -> 7`

The only relevant test cases I could think of were a negative odd, negative even, positive odd, positive even, `0`, and then I threw in `-1` and `1` since their proximity to `0` may have caused problems:

```
[-10 -5 -1 0 1 5 10]
{.{..0>2*(\)2%!2*(@*+}{ }if}:f;
{f f}%
-> [10,5,1,0,-1,-5,-10]

```

I'm sure the actual GolfScript can be improved somewhat. It doesn't feel like it should take up 26 characters! Would love to hear some suggestions.

# Answer
> 2 votes
## Java, just for fun

Here's an implementation that does an actual bijection between ℤ and ℤ², which is an odd function at the same time (g(-x) == -g(x)). It treats the corresponding ℤ² element as a complex number and multiplies it by "i", then converts back to ℤ.

f(x)=g⁻¹(ig(x))
f(f(x))=g⁻¹(-g(x))=-x

The function runs in O(1).

```
public class Ffn {
    public static int f(int n) {
        if (n == 0) {
            return 0;
        }
        // adjust sign
        int s = n > 0 ? 1 : -1;
        int m = n * s;
        // calculate square "radius"
        int r = (int) (Math.sqrt(2 * m - 1) + 1) / 2;
        int q = r * 2;
        // starting point
        int x = r, y = r;
        int k = q * (r - 1) + 1;

        if (m - k < q) {
            // go left
            x -= m - k;
        }
        else {
            // go left
            x -= q;
            // go down
            y -= m - k - q;
        }

        // multiply by i
        int x2 = -y * s, y2 = x * s;
        // adjust sign
        s = y2 < x2 || y2 == x2 && x2 < 0 ? -1 : 1;
        x2 *= s;
        y2 *= s;

        if (y2 == r) {
            // go left
            k += r - x2;
        }
        else {
            // go left and down
            k += q + r - y2;
        }
        return k * s;
    }

    public static void main(final String... args) {
        for (int i = 0; i < 1000000; ++i) {
            if (f(f(i)) != -i || f(f(-i)) != i) {
                System.out.println(i);
            }
        }
    }
}

```

P.S. Happy New Year!

# Answer
> 2 votes
# Python 3 - 38

Similar to @moose's answer, but, `f(n) == n`. Works for all integer values.

```
f=lambda x:x*(isinstance(x,int)*2.0-1)

```

# Answer
> 2 votes
## Perl, 33 (non-whitespace)

```
sub f{($=)=@_;$=-$_[0]?-$=:"$=.1"}

```

**Edit:**

* `$=.".1"` shortened to `"$=.1"` (thanks ardnew).

**Math:**

**Ungolfed:**

```
# script.pl
sub f {
  ($=) = @_;   # short for $= = int($_[0]);
               # "int" is implicit in assignments to $=;
               # ($=) can be prepended by "local" to get
               # the function free of side effects.

  $= - $_[0] ? # short for $= != $_[0], check if input is integer
    -$=        # input is not an integer
  : $= . ".1"  # input is integer
}

# Testing
chomp;
$_ = sprintf "f(f($_)) = f(%s) = %s\n", f($_), f(f($_));

```

**Examples:**

```
perl -p script.pl
7
f(f(7)) = f(7.1) = -7
2
f(f(2)) = f(2.1) = -2
0
f(f(0)) = f(0.1) = 0
-1
f(f(-1)) = f(-1.1) = 1
-10
f(f(-10)) = f(-10.1) = 10
-1.23
f(f(-1.23)) = f(1) = 1.1
3.4
f(f(3.4)) = f(-3) = -3.1
1.0
f(f(1.0)) = f(1.1) = -1

```

# Answer
> 2 votes
# Julia, 26

```
julia> f(n::Int)=n//1
f (generic function with 1 method)
julia> f(n)=int(-n)
f (generic function with 2 methods)
julia> f(f(4))
-4

```

Not super competitive, but very Julian since it relies on multiple dispatch. It just makes n a Rational if its an Int, or an int with a minus sign if it is anything else. One might object that this is 2 functions, but Julia considers this to be one function with two methods, and it is equivalent to defining one function with an if statment on the type of `n`.

# Answer
> 2 votes
# Candy, ~~20~~ 18 bytes

Uses the 3 -\> 4 -\> -3 -\> -4 -\> 3 trick.

```
~A2%{|m}1A0>{+|-}.

```

To invoke it use the -i switch on the interpreter

Example of double-invokation:

```
$ candy -i 7 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> 8
$ candy -i 8 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> -7
$ candy -i -7 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> -8
$ candy -i -8 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> 7

```

Long form:

```
peekA
pushA
digit2
mod          # even/odd
if
else
  negate     # negate even numbers
endif
digit1
pushA
digit0
greater      # positive/negative
if
  add        # add two numbers from stack (original stack value, and delta)
else
  sub        # diff two numbers from stack (original stack value, and delta)
endif
retSub

```

# Answer
> 2 votes
## Dyalog APL, 9 points

```
×-⍨⊢×¯1*⊢

```

The source is 9 bytes long and qualifies for the bonus (which doesn't help at all). It also uses the formula from the top SO answer.

# Answer
> 1 votes
Updated with function supplied by Synthetica (obviously the one who should get credit for this now)

Language: Python

Number of characters: 41 including whitespace

```
f=lambda x:-float(x) if str(x)==x else`x`

```

# Answer
> 1 votes
## Python: 32 bytes (29 points)

f: Z -\> Z

```
f=lambda n:(n>0)-(n<0)-n*(-1)**n

```

Using Ben Reich's method.

# Answer
> 1 votes
## GTB, 22

```
@S;N,"--$x?N)→N~N#~-N&

```

# Answer
> 1 votes
# Java, 113 bytes

The approach is pretty simple. It ended up more bytes than I anticipated, but can perhaps be golfed down a bit.

```
public class F{public static int f(int x){if(x<0)x+=-2147483647-++x;x+=1073741824;return x<0?-2147483647-++x:x;}

```

It basically creates 4 different "areas" of x, utilizing the fact that Java happily lets variables wrap around. I had to do some tricky conversion for negative numbers which is the main reason this ended up bigger than anticipated.

Works for all x besides -2147483648.

# Answer
> 1 votes
Same sequence of numbers (3, 4, -3, -4, 3 ...) as the golfscript answer, but implemented in perl (42 chars after whitespace is stripped)

```
sub f{($_[0]%2?1:-1)*$_[0]+($_[0]<0?-1:1)}

```

More legibly:

```
sub f { ($_[0] % 2 ? $_[0] : -$_[0] ) + ( $_[0] < 0 ? -1 : 1 ) }

```

Or even more legibly:

```
sub f {
  my $n = shift;
  my $sign = $n >= 0 ? 1 : -1;
  # note that in perl $n % 2 is the same as int($n) % 2
  if( $n % 2 ) {
    # odd: add one to magnitude
    return $n + $sign
  } else {
    # even: subtract one from magnitude then invert
    return -($n - $sign)
  }
}

```

Output:

```
ski@anito:~/mysrc/.../acme$ echo 3 | perl -e 'sub f{($_[0]%2?1:-1)*$_[0] + ($_[0]<0?-1:1)}; my $x = <>; for(0..10) { print "$_: $x\n"; $x = f($x); }'
0: 3
1: 4
2: -3
3: -4
4: 3
5: 4
6: -3
7: -4
8: 3
9: 4
10: -3

```

# Answer
> 1 votes
# Sed, 25 bytes.

```
|sed s/0+/0-/|sed s/^/0+/

```

**Usage:**

```
$ echo 1.23 |sed s/0+/0-/|sed s/^/0+/
0+1.23
$ echo 0+1.23 |sed s/0+/0-/|sed s/^/0+/
0+0-1.23

```

# Answer
> 1 votes
# Matlab, 26 characters

```
f=@(n) (n<0)-(n<0)-n*(-1)^n

```

# Answer
> 1 votes
# C++ - ~~63~~ 55.8

This is how the code looks:

```
int f(int n){return (n&45056?n^45056:n|45056)*(n&45056?-1:1);}

```

It doesn't work on integers whose fourth byte is equal to 0xB as it uses that value to keep track of passes. Otherwise works on any member of Z, including zero.

# Answer
> 1 votes
# Prolog, 36 bytes

**Code:**

```
X*Y:-X//1=:=X,Y is 0.5+X;Y is 0.5-X.

```

**Explained:**

```
Dyadic predicate which converts integers to floats and floats back to negated integers.

```

**Example:**

```
10*X.
X = 10.5

10*Y,Y*X.
X = -10,
Y = 10.5

```

# Answer
> 1 votes
# Javascript ES6, ~~27~~ 26 bytes

```
a=>a%1?-Math.floor(a):a+.2

```

# Answer
> 1 votes
# Mouse-2002, ~~21~~ ~~19~~ 12 bytes

```
$A1%[1%_|1%]

```

Defines a function `A`; call it like `#A,#A,?;;` (which will wait for the user to enter any number). Alternatively, call it like `#A,#A,n;;` where `n` is any number.

# Answer
> 1 votes
# Julia, 21

```
f(x)=(1-2(1>x>-1))/2x

```

Then

```
julia> f(f(12//1))
-12//1

```

p//q is julia's literal notation of rational numbers.

# Answer
> 1 votes
# Forth, 37 bytes

```
: f 9 @ if negate 0 else 1 then 9 ! ;

```

Works at least in durexforth (it should at least, I couldn't type the whole line in because VICE was being stupid with my keybaord layout so I couldn't type the `:`). To run it in gforth you need to do `variable 9` before, since it doesn't allow writing to arbitrary memory locations.

(Forth sadly doesn't work with floating point numbers.)

# Answer
> 0 votes
**C, 80 bytes**

```
#include <math.h>
double z(double x){return x==0.0?x:fabs(x)>0.5?0.5/x:-0.5/x;}

```

for to test

```
#include <stdio.h>
#define P printf
#define R return
main()
{double i, j;
 for(i=-20;i<20;i+=1)
       P("z(z(%f))=%f\n", i, z(z(i)) );
 for(i=-2;i<-1;i+=0.1)
       P("z(z(%f))=%f\n", i, z(z(i)) );
 for(i= 2;i<3;i+=0.1)
       P("z(z(%f))=%f\n", i, z(z(i)) );
 P("z(z(%f))=%f\n", 0.1245447, z(z(0.1245447)) );
 R 0;
}

```

results where you can see that this is for every number in double except 0 and 2 other

```
/*
z(z(-20.000000))=20.000000
z(z(-19.000000))=19.000000
z(z(-18.000000))=18.000000
z(z(-17.000000))=17.000000
z(z(-16.000000))=16.000000
z(z(-15.000000))=15.000000
z(z(-14.000000))=14.000000
z(z(-13.000000))=13.000000
z(z(-12.000000))=12.000000
z(z(-11.000000))=11.000000
z(z(-10.000000))=10.000000
z(z(-9.000000))=9.000000
z(z(-8.000000))=8.000000
z(z(-7.000000))=7.000000
z(z(-6.000000))=6.000000
z(z(-5.000000))=5.000000
z(z(-4.000000))=4.000000
z(z(-3.000000))=3.000000
z(z(-2.000000))=2.000000
z(z(-1.000000))=1.000000
z(z(0.000000))=0.000000
z(z(1.000000))=-1.000000
z(z(2.000000))=-2.000000
z(z(3.000000))=-3.000000
z(z(4.000000))=-4.000000
z(z(5.000000))=-5.000000
z(z(6.000000))=-6.000000
z(z(7.000000))=-7.000000
z(z(8.000000))=-8.000000
z(z(9.000000))=-9.000000
z(z(10.000000))=-10.000000
z(z(11.000000))=-11.000000
z(z(12.000000))=-12.000000
z(z(13.000000))=-13.000000
z(z(14.000000))=-14.000000
z(z(15.000000))=-15.000000
z(z(16.000000))=-16.000000
z(z(17.000000))=-17.000000
z(z(18.000000))=-18.000000
z(z(19.000000))=-19.000000
z(z(-2.000000))=2.000000
z(z(-1.900000))=1.900000
z(z(-1.800000))=1.800000
z(z(-1.700000))=1.700000
z(z(-1.600000))=1.600000
z(z(-1.500000))=1.500000
z(z(-1.400000))=1.400000
z(z(-1.300000))=1.300000
z(z(-1.200000))=1.200000
z(z(-1.100000))=1.100000
z(z(2.000000))=-2.000000
z(z(2.100000))=-2.100000
z(z(2.200000))=-2.200000
z(z(2.300000))=-2.300000
z(z(2.400000))=-2.400000
z(z(2.500000))=-2.500000
z(z(2.600000))=-2.600000
z(z(2.700000))=-2.700000
z(z(2.800000))=-2.800000
z(z(2.900000))=-2.900000
z(z(0.124545))=-0.124545
*/

```

---
Tags: code-golf, math, number, open-ended-function
---


# Question
Title: f(g(x)) decreases while g(f(x)) increases
For this challenge you need to implement two functions, **f** and **g**, on the integers, such that **f ∘ g** is a strictly decreasing function while **g ∘ f** is a strictly increasing function. In other words, if you take any two integers **a \< b**, then **f(g(a)) \> f(g(b))** and **g(f(a)) \< g(f(b))**. There are no restrictions on **f** and **g** individually, except that they must each map one integer to another integer.

Please include a short description of **f** and **g** and an argument for why they have the required property.

<sup>**Credit:** This challenge was inspired by a problem in the 2011 Romanian Master of Mathematics competition (which asks the same thing but on the real numbers, instead of integers). If you really want spoilers, you now know what to search for.</sup>

## Rules

* The word "function" in this challenge should be taken in the mathematical sense of mapping one integer to another: you may either write two programs or two functions and use any of the standard methods of receiving input and providing output, as usual. You may use string representations of integers instead of actual integer variables, but the types of input and output should be identical, so that the functions can be composed without manually converting types in between. Remember that conceptually, **f** and **g** still need to be functions on ℤ, so you can't cheat by using two different string representations of the same number or anything like that.
* Remember that functions may be unnamed, as long as their name isn't needed by itself or another function you define. If you do name one or both of the functions, you may assume that they exist in the same program, so that they may refer to each other in their implementation (e.g `def f(x): return -g(x)` in Python).
* The usual integer overflow rules apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution.
* You may use any programming language, but note that these loopholes are forbidden by default.
* This is , so your score is the sum of the *number of bytes* of both functions and the shortest valid answer wins.

# Answer
> 20 votes
# Python, 68 characters

```
f=lambda x:(1-x%2*2)*(2*x*x+(x<0))
g=lambda x:(1-x%2*2)*(2*x*x+(x>0))

```

f maps negative numbers to odd numbers and positive numbers to even numbers, and even numbers to positive numbers and odd numbers to negative numbers, with the output magnitude increasing strictly with the input magnitude.

g does the same, except it maps negative numbers to even numbers and positive numbers to odd numbers.

f ∘ g maps negative → even → positive and positive → odd → negative.
g ∘ f maps negative → odd → negative and positive → even → positive.

Therefore f and g have the desired properties.

# Answer
> 16 votes
## CJam (17 bytes)

Function f (named `F` because CJam only allows upper-case names):

```
{W1$2b,#*}:F

```

Function g (anonymous):

```
{F2*}

```

Online demo

This saves a byte by relying on a implementation detail of CJam which is arguably a bug: when doing base conversions it uses absolute value. `2b,` therefore gives the number of bits in the absolute value of its argument, so f negates precisely those numbers whose absolute value has an odd number of bits. g applies f and then doubles (changing the parity of the number of bits).

So applying f and then g leaves sign unchanged and doubles, mapping `x` to `2x`. Applying g and then f changes the sign exactly once and doubles, mapping `x` to `-2x`.

# Answer
> 16 votes
# Python, 40 bytes

```
f=lambda x:x*(-1)**x
g=lambda x:3*f(x)+1

```

Try it online! Some outputs are floats that equal integers because `(-1)**(-3)` gives a float for instance.

Based off ideas from Peter Taylor. The function `f` negates odd numbers and leaves even ones unchanged. The function `g` does the same, then applies the monotonic parity-switching map `x -> 3*x + 1`.

Since `f(f(x)) = x`, we have `g(f(x)) = 3*f(f(x))+1 = 3*x+1` increasing.

For `f(g(x)) = f(3*f(x)+1)`, the idea is that exactly one of the inner and outer `f` flips sign, making it decreasing.

* For even `x`, `f(x) = x`, but `f(3*x+1) = -3*x-1` because `3*x+1` is odd.
* For odd `x`, `f(x) = -x`, and `f(-3*x+1) = -3*x+1` because `-3*x+1` is even.

We now only need the even and odd inputs interleave in a decreasing way, which holds because `-3*x±1` is decreasing regardless of how the signs are chosen. This is why the `3*` is needed.

A Haskell port is 25 bytes:

```
f x=x*(-1)**x
g x=1+3*f x

```

Try it online!

# Answer
> 2 votes
# Pyth, 34 Bytes

This is just a direct translation of my Python answer.

```
*-1*2%Q2+*2*QQ<Q0
*-1*2%Q2+*2*QQ>Q0

```

---
Tags: code-golf, math, open-ended-function
---


title: deRpiFy tHe sTriNg!

text:
# Question
Title: deRpiFy tHe sTriNg!
> yOu wiLl bE giVen A sTriNg wHich cOnsiSts oF pRintAble asCii cHarActErs.
>
> yOu iTeraTe tHrougH thE sTrIng tHen chAnge rAndOM(uNifoRm, 50% cHanCe uPPercAse) lEtteRs to uPPercAse aNd eVerytHing elSe tO lOwercAse.
>
> tHat'S iT.

(sorry for the punctuation, it was for the concept of the question)

Readable version:

> You will be given a string which consists of printable ASCII characters.
>
> You iterate through the string and change random(uniform, 50% chance uppercase) letters to uppercase, and everything else to lowercase.
>
> that's it.

# exaMplEs

```
iNpuT => pOssiBle oUtPUt
Programming puzzles and Code Golf => pRogRaMMiNg pUzzlEs aNd coDe goLf
dErpity deRp derP => deRpiTy dErp DerP
CAAAPSLOOOCK => cAAapslOoocK
_#$^&^&* => _#$^&^&*

```

# Answer
> 10 votes
# C – 65 bytes

Pretty good for a mainstream language!

```
main(c){while((c=getchar())>0)putchar(isalpha(c)?c^rand()&32:c);}

```

Uses XOR to randomly flip the bit at `0x20` for each alphabetic character. Program assumes ASCII character set and that `EOF < 0`.

Sample run on its own source!

```
$ main < main.c
MaIN(c){WhILe((C=GETChAr())>0)pUtCHaR(iSALpha(C)?C^rANd()&32:C);}

```

Very derpy.

# Answer
> 7 votes
## JavaScript, 87 bytes

```
function(s){return s.replace(/./g,c=>Math.random()<.5?c.toLowerCase():c.toUpperCase())}

```

68 bytes in ES6:

```
f=
s=>s.replace(/./g,c=>c[`to${Math.random()<.5?`Low`:`Upp`}erCase`]())
```

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

# Answer
> 5 votes
# MATL, ~~13~~ 12 bytes

```
"@ktXkhlZr&h

```

Try it at **MATL Online**

**Explanation**

```
        % Implicitly grab input as a string
"       % For each character...
  k     % Convert to lowercase
  tXk   % Make a copy and convert to uppercase
  h     % Horizontally concatenate these two characters
  lZr   % Randomly select one of them
  &h    % Horizontal concatenate the entire stack
        % Implicit end of for loop and implicit display

```

# Answer
> 5 votes
# Jelly, 6 bytes

```
,ŒsXµ€

```

**Try it online!**

### How?

Lower casing all chars of the input and then uppercasing each with 50% probability is the same as choosing one of the original char and the swapped-case char with equal probability...

```
,ŒsXµ€ - Main link: string s
    µ  - monadic chain separation
     € - for each char c in s
,      -     pair c with
 Œs    -     swapped case of c
   X   -     choose a random item from the list (of the two chars)
       - implicit print

```

# Answer
> 5 votes
# PowerShell, ~~64~~ 60 bytes

```
-join([char[]]"$args".ToLower()|%{"$_".ToUpper(),$_|random})

```

Try it online! (make sure that "disable output cache" is checked if you want random results)

Exact translation of the challenge. Takes the input string, `ToLower()`s it, converts it to a `char` array, loops through each character `|%{...}`, and randomly selects between either the existing character or the uppercase variant. Then `-join`s them all back together into a single string. This works because `ToUpper` and `ToLower` only affect alphabetical characters, leaving punctuation and the like unchanged.

*(Dennis fixed the alias list on TIO so that `Random` isn't trying Linux `random` but correctly aliases to `Get-Random` as a PowerShell command, as it should. Thanks, Dennis!)*

# Answer
> 4 votes
# PHP, 53 Bytes

```
for(;a&$c=$argn[$i++];)echo(lu[rand()&1].cfirst)($c);

```

# Answer
> 4 votes
# Japt, 10 bytes

```
®m"uv"gMq2

```

Try it online!

### Explanation

So this is kind of a cheesy hack, but it works. In JavaScript you can do something like

```
x[`to${Math.random()<.5?"Upp":"Low"}erCase`]()

```

to randomly convert `x` to upper- or lowercase. In Japt, the equivalent functions are `u` for `toUpperCase` and `v` for `toLowerCase`. But in Japt there is no direct way to get a calculated property value (`x[expression]` in JavaScript).

One of my favorite features of Japt is that if you have a function which is composed of a single method call (e.g. `mX{Xq}`, or `.m(X=>X.q())` in JS), you can leave out everything except the name of the method, e.g. `mq`. The compiler then turns this into a string which gets passed to the original method call (`.m("q")`), and the method turns this back into a function. So there's no difference between `mq` and `m"q"`; both produce the same output.

Now, where I was going with this: while we can't directly call a random method on a string, we *can* call `m` on that string with a random method name. So, for the explanation:

```
®m"uv"gMq2
®           // Replace each char in the input by this function:
 m          //   Replace each char in this char by this function:
      g     //     the char at index
       Mq2  //       random integer in [0,2)
  "uv"      //     in "uv".
            //   This randomly calls either .u() or .v() on the char.
            // Implicit: output result of last expression

```

# Answer
> 2 votes
# Perl 5, 26 bytes

25 bytes + `-p` flag.

```
s/./rand 2&1?uc$&:lc$&/ge

```

Try it online!

# Answer
> 2 votes
# Perl 6,  ~~32~~  29 bytes

```
{[~] .comb.map:{(.lc,.uc).pick}}

```

Try it

```
{S:g/./{($/.uc,$/.lc).pick}/}

```

Try it

# Answer
> 2 votes
# MATL, ~~12~~ 11 bytes

*1 byte removed using Jonathan Allan's idea of directly changing case.*

```
"@rEk?Yo]&h

```

Try at **MATL online!**

### Explanation

```
"         % Implicit input. For each
  @       %   Push current char
  r       %   Random number uniformly distributed on (0,1)
  Ek      %   Duplicate, floor: gives 0 or 1 with the same probability
  ?       %   If nonzero
    Yo    %     Change case. Leaves non-letters unaffected
  ]       %   End
  &h      %   Horizontally concatenate evverything so far
          % Implicit end and display

```

# Answer
> 2 votes
# Python 2, ~~77~~ 74 bytes

```
lambda s:"".join(map(choice,zip(s.upper(),s.lower())))
from random import*

```

Try it online!

# Answer
> 2 votes
# Japt, ~~12~~ 10 bytes

```
£M¬?Xv :Xu

```

### Explanation:

```
£M¬?Xv :Xu
£             // Iterate through the input. X becomes the iterative item
 M¬           // Return a random number, 0 or 1
    ?         // If 1:
     Xv       //   X becomes lowercase
        :     // Else:
         Xu   //   X becomes uppercase

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
vyDš‚.RJ

```

Try it online!

**Explanation**

```
v          # for each char y in input
 yDš‚      # pair lower-case y with upper-case y
     .R    # pick one at random
       J   # join to string

```

# Answer
> 1 votes
# JavaScript, 77 bytes

```
x=>x.toLowerCase().split``.map(y=>Math.random()*2|0?y:y.toUpperCase()).join``

```

Try it online!

# Answer
> 1 votes
# CJam, 14 bytes

```
qel{2mr{eu}&}%

```

Try it online!

**Explanation**

```
q               e# Read the input
 el             e# Make it lowercase
   {            e# For each character in it
    2mr         e#  Randomly choose 0 or 1
       {eu}&    e#  If 1, make the character uppercase
            }%  e# (end of block)

```

# Answer
> 1 votes
# Pyth, 5 bytes

```
srLO2

```

Test suite

```
srLO2
srLO2Q    Variable introduction
  L  Q    Map over the input
 r        Set the case of each character to
   O2     Random number from [0, 1]. 0 means lowercase, 1 means uppercase.
s         Concatenate

```

# Answer
> 1 votes
# Befunge, 136 bytes

```
>~:0`!#@_:"@"`!#v_:"Z"`!#v_:"`"`!#v_:"z"`!#v_,
^,<    <        <                 <
 >?<                     <             -*84<
  >84*+^

```

Try it online!

There is a lot of whitespace that I think is possible to get rid of. Befunge doesn't have a way of figuring out what's a letter and what isn't, so this is what I'm doing on the first row.

# Answer
> 0 votes
# Swift - way too many bytes (~~176~~ 167)

`uppercased()`,`lowercased()`,`arc4random_uniform()` really kill the score, besides for me having to add a function since Swift has no standard input method!

```
import Foundation
func g(x:String){var result="";for i in x.characters{let e=String(i);result+=(arc4random_uniform(2)>0 ?e.uppercased():e.lowercased())};print(result)}

```

Function with usage: `print(g(x: "Your String Here"))`

# Answer
> 0 votes
# Bash, 64 bytes

first try

```
a=$(shuf -e -n 13 {A..Z}|tr -d "\n");b=${a,,};tr $b $a <<<${1,,}

```

Try it online!

shuffles capital letters, takes first 13, removes newlines and saved to $a. $b holds $a to lowercase. input is set to lowercase by ${1,,} and passed as a heredoc to tr which replaces each ocurrence of $b by $a

This is somewhat non compeating because the same letter is always capitalized.

# Answer
> 0 votes
# JavaScript + HTML, 115 bytes

```
<input oninput="this.value=this.value.toLowerCase().split('').map(v=>Math.random()<.5?v.toUpperCase():v).join('')">
```

# Answer
> 0 votes
**Bash, 162 Bytes**

```
a=$1
b=1
c="echo $a|head -c$b|tail -c1"
while(($b<=${#a}))
do
r=$[RANDOM%2]
if [ $r = 1 ]
then d=$(eval $c);echo -n ${d^}
else echo -n $(eval $c)
fi
b=$[b+1]
done

```

Pretty self explanatory. Takes input from command line arg, writes to stdout.

Run like `derpifier.sh "Derp this"`

Man, once I start applying the tips the code shrinks fast.

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


title: Minesweeper At Work

text:
# Question
Title: Minesweeper At Work
Everyone knows the old minesweeper game that shipped with Windows XP. It's a simple grid with a 9x9 matrix of cells containing either a number (indicating how many mines are adjacent to it) or a mine.

The challenge is to generate a random 9x9 grid with 10 bombs given any integer seed (up to whatever your machine/language's largest int is) with brownie points if you implement the PRNG yourself

example output: cells contain either numerals 0-8 or * for mines

```
*101*1000
110111000
123210000
1***10000
123210011
00000002*
00000114*
000112*3*
0001*2121

```

Shortest code in bytes wins.. standard rules etc, etc..

# Answer
> 3 votes
# Dyalog APL, 40 bytes

`⎕rl←1⋄(1,¨a)⍕¨{⍉3+/0,⍵,0}⍣2⊢a←9 9⍴9≥?⍨81`

(assumes `⎕io←0`)

the `1` in `⎕rl←1` is the seed

from right to left:

`?⍨81` is the same as `81?81` \- a random permutation

`9≥` results in a bitmask containing ten 1s at random positions, the rest are 0s

`a←9 9⍴` reshape to a 9-by-9 square and call it "a"

`{ }⍣2` do the following twice:

`⍉3+/0,⍵,0` sliding window sum of 3 columns (assume 0s outside), then transpose

`(1,¨a)⍕¨` is format (convert to string) each. The left argument to  specifies the total number of characters and fractional characters in the result. If  can't format according to that spec it outputs a `*` \- a lucky coincidence for this problem. `a` will be 1 where the mines are - trying to fit a whole and fractional part into a single char is impossible, so those will appear as `*`s.

# Answer
> 5 votes
# MATLAB, ~~94~~ 93 bytes

```
rng(input(''));x(9,9)=~1;x(randperm(81,10))=1;y=[conv2(+x,ones(3),'s')+48 ''];y(x)=42;disp(y)

```

Example run (the first line after the code is the input typed by the user):

```
>> rng(input(''));x(9,9)=~1;x(randperm(81,10))=1;y=[conv2(+x,ones(3),'s')+48 ''];y(x)=42;disp(y)
99
*10001*2*
220001232
*201111*1
*312*1111
12*211000
011211000
0001*1000
000112110
000001*10

```

### Explanation

```
rng(input(''));

```

takes an integer and uses it as seed. (This works in modern MATLAB versions. Old versions may need a different syntax.)

```
x(9,9)=~1;

```

assigns logical `0`, or `false` (obtained by logically negating `1`) to the entry `(9,9)` of a matrix `x`. The rest of the entries are automatically initiallized to logical `0` too.

```
x(randperm(81,10))=1;

```

assigns `1` (autoomatically cast to logical `1`, or `true`) to `10` of the `81` entries of `x`, chosen randomly without replacement. These entries are the ones that contain bombs.

```
conv2(+x,ones(3),'s')

```

is an abbreviation of `conv2(+x,ones(3),'same')`. It convolves the matrix `x` (which needs to be cast to `double`, using `+`) with a 3×3 neighbourhood containing `1`. This counts how many bombs are adjacent to each entry. For entries that contain a bomb it includes that bomb, but the value there will be overwritten later.

```
y=[...+48 ''];

```

adds 48 to the value, to convert from number to ASCII code. Concatenating with the empty matrix casts these ASCII codes to chars.

```
y(x)=42;

```

assigns 42 (ASCII code for `'*'`) to the positions of the bombs. These positions are given by `x`, which is here used as a logical index.

```
disp(y)

```

displays the result.

# Answer
> 4 votes
## Javascript (ES6), 204 or 198 bytes

### Custom PRNG (204 bytes)

```
s=>(p=-1,S=n=>(x=p%9-(n+=p)%9)*x-64&&b[n]=='*',T=n=>S(n)+S(-n),b=[...'*00000000'.repeat(9)]).sort(_=>(s=(22695477*s+1)>>>0)&1||-1).map(c=>(p++,c=='0'?T(1)+T(8)+T(9)+T(10):c)).join``.match(/.{9}/g).join`
`

```

This code is using a linear congruential generator with multiplier `22695477` and increment `1` (this is the Borland C/C++ implementation).

Due to the poor efficiency of the PRNG during its warmup phase, I had to place one bomb per row (instead of 10 at the beginning or 10 at the end of the unshuffled array). So, there are only 9 bombs. I may try to fix that later.

Also, there must be a simpler/shorter way of processing the 'out of board' check `(x=p%9-(n+=p)%9)*x-64` but I just can't figure it out right now.

### Using Math.random() (198 bytes)

```
s=>(p=-1,S=n=>(x=p%9-(n+=p)%9)*x-64&&b[n]=='*',T=n=>S(n)+S(-n),b=[...'**********'+'0'.repeat(71)]).sort(_=>Math.random()-.5).map(c=>(p++,c=='0'?T(1)+T(8)+T(9)+T(10):c)).join``.match(/.{9}/g).join`
`

```

This one includes 10 mines as requested.

### Demo

```
let f =
_=>(p=-1,S=n=>(x=p%9-(n+=p)%9)*x-64&&b[n]=='*',T=n=>S(n)+S(-n),b=[...'**********'+'0'.repeat(71)]).sort(_=>Math.random()-.5).map(c=>(p++,c=='0'?T(1)+T(8)+T(9)+T(10):c)).join``.match(/.{9}/g).join`
`
console.log(f())
```

# Answer
> 4 votes
# R, 187 Bytes

```
set.seed();x=1:121;y=x[!(x%%11 %in% 0:1|(x-1)%/%11 %in% c(0,10))];z=sample(y,10);x=x*0;for(t in z){p=t+c(-10:-12,-1,1,10:12);x[p]=x[p]+1};x[z]=9;m=data.frame(matrix(x[y],9));m[m==9]='*';m

```

Try it on Ideone

Explanation:

`set.seed()` take a cst seed.

`x` is the index for a 11\*11 matrix

`y` is the index of the 9\*9 matrix in the 11\*11 matrix

`z` is the index of the bomb

`x=x*0` initialise the matrix value

The loop add 1 to x in case of adjacent bomb.

# Answer
> 3 votes
# Python 2, ~~269~~ ~~266~~ 264 bytes

```
from random import*
seed(input())
z=1,0,-1
n=range(9)
m=[[0]*9 for _ in n]
for x,y in sample([[x,y]for x in n for y in n],10):
 m[x][y]=-9
 for a in z:
  for b in z:
    if 0<=x+a<9>0<=y+b<9:m[x+a][y+b]+=1 # it gets displayed as 4 spaces, but the beginning of this line is a single tab
print("\n".join("".join([`c`,'*'][c<0]for c in l)for l in m))

```

Try it on ideone.com

Saved 2 bytes thanks to Aaron.

Most likely still golfable.

### Explanation

`random` is imported for using `seed` to seed the PRNG and `sample` to select ten bomb locations randomly. `m` is a 9 x 9 matrix saving the board. For each of the bomb locations, the corresponding entry in `m` gets set to `-9` and all neighbouring entries get incremented. This way `m` ends up containing the count of adjacent bombs for non-bomb cells and a negative number for bomb cells. The final `print` prints the whole board by iterating through all lines `l` in `m` and all cells `c` in `l`.

# Answer
> 2 votes
## JavaScript ES6, 244 bytes

```
f=(a=[...Array(11)].map(_=>Array(11).fill(0)),n=10,r=_=>Math.random()*9|0,x=r(),y=r())=>a[x+1][y+1]>8||[0,1,2].map(i=>[0,1,2].map(j=>a[x+i][y+j]++),a[x+1][y+1]=9)&&--n?f(a,n):a.slice(1,-1).map(a=>a.slice(1,-1).map(n=>n<9?n:`*`).join``).join`
`
;o.textContent=f()
```

```
<pre id=o>
```

# Answer
> 1 votes
# Ruby, ~~181~~ ~~194~~ 183+1 = 184 bytes

Forgot to actually set the seed, whoops. Uses the `-n` flag.

Try it online!

```
srand$_.to_i
a=[0]*81
[*0..80].sample(10).map{|i|w=i%9;h=i/9;a[i]=-99
(r=-1..1).map{|x|x+=w
x<0||x>8?0:r.map{|y|y+=h
y<0||y>8?0:a[9*y+x]+=1}}}
puts a.map{|c|c<0??*:c}.join.scan /.{9}/

```

# Answer
> 0 votes
# Python 2, 172 bytes

```
from random import*
seed(input())
r=range
b=set(sample(r(81),10))
for j in r(9):print''.join([[`len({x-10,x-9,x-8,x-1,x+1,x+8,x+9,x+10}&b)`,'*'][x in b]for x in r(j,81,9)])

```

Try it online!

---
Tags: code-golf, random, minesweeper
---


# Question
Title: Make me a loaf of bread before I'm fired!
# Backstory

Not really real, *sshh!*

It all started one day when a coworker brought in a *homemade* loaf of bread for my boss's birthday.

My boss *really* liked this loaf of bread, and he wanted another. Unfortunately, my coworker has quit, so my boss needs *me* to give him another loaf.

The problem is, I have *no idea* how to make bread. So I told my boss that i'm not a chef and to look harder for someone who is.

He said, "Sure...but you lose your job if you can't make me a loaf."

Then I had an idea.

I would make him an  loaf with my coding skilz! He said yes, under 1 condition: "You must make it in under 351 bytes." Unfortunately for me, my best code golfing got me to 375 bytes. Uh oh.

Then my boss added 2 things: "You must give me that loaf in a week (4/13), and if you do so you get an increased salary. The lower the amount of bytes you use, the better salary. But remember, if you go over 349 you lose your job."

So I need your help in your language of choice to help me keep my job!

# Rules

I was about to do a `curl ... | sh` on a TinyURL, but my boss told me that I can't use a list of loopholes. I probably could skirt the rules, but my job is at stake, so it's not a good idea.

# What counts as a loaf

Your program or function must take 3 positive integers as input. If your language has a list or array, you can take a list or array of those numbers. You can also take them as arguments to a function or program, or a space-separated string of numbers to STDIN, a command-line or function argument, etc.

**The first number is the width of your loaf**

**The second number is the height of your loaf.**

**The third number is the depth of your loaf.**

Here's a loaf with a width of `3`, a height of `2`, and a depth of `1`:

```
 /---\
/---\|
|   ||
|___|/

```

Looks wierd? Here's a 3x2x2:

```
  /---\
 /    |
/---\ |
|   | /
|___|/

```

How about a 3x3x3:

```
   /---\
  /    |
 /     |
/---\  |
|   |  /
|   | /
|___|/

```

A 4x1x2:

```
  /----\
 /     |
/----\ /
|____|/

```

I hope you understand! See my JS (ES6) answer below for an example.

Also see complete test cases

# Notes:

* Don't worry about valid input. All sizes will be positive integers.
* You must accept any positive integers that your language can support.
* If the numbers are so high your languages crashes from StackOverflow, maximum string length overflow, etc. that's OK.

# Shortest answer in bytes wins!

# Answer
> 7 votes
# Charcoal, ~~35~~ ~~33~~ 30 bytes

*Saved 2 bytes thanks to @ASCII-only*

*Saved 3 bytes thanks to @Neil by rearranging the order in which the lines where drawn*

```
ＮωＮηＮδ↓η↗→×_ω↑η←\←ω↗δ→/ω↓\↓η↙δ

```

Try it online!

This is my first try at Charcoal. I heard it was good at , so I tried it out.

### Explanation (outdated)

```
ＮωＮηＮδ                  # Take the width, height and depth as input
↗¹                        # Write 1 /
↗δ                        # Write depth times /
¶ω                        # Move the cursor down and write - width times
\                         # Write \
↙↓η                       # Move the cursor one down and one left, and then write | height times
↙δ                        # Write / depth times

```

Now the back part of the loaf is complete. Now comes the front face.

```
↑↑η                       # Go up and write | height times
←\                        # Write a \ and move 1 to the left
←ω                        # Write - width times
↓↓η                       # Go down and write | height times
↗Ｐ×_ω                    # Go northeast and write _ width times

```

# Answer
> 3 votes
# JS (ES6), 375 bytes

```
s=(s,t)=>s.repeat(t);(d,c,e)=>{z=" ",y=`
`,x="\\",w="/",v="|",u="-";a=s(z,e--);a=a+w+s(u,d);a+=x+y;for(b=0;b<e;b++)a+=s(z,e-b),b<c?(a+=w,a+=s(z,d+b+1),a+=v):(a+=w,a+=s(z,d+c+1),a+=w),a+=y;a=a+w+s(u,d);a+=x;f=0;b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w);b++;f++;a+=y;for(g=0;g<c;g++)a+=v,a+=s((g==c-1?"_":z),d),a+=v,b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w),b++,f++,a+=y;return a}

```

Ungolfed:

```
var proc = function(width, height, depth){
    var str = "";

    //Back of loaf (depth)
    str += " ".repeat(depth);//initial padding before start of back of loaf
    str += "/";//top left corner of back of loaf
    str += "-".repeat(width);//top edge of back of loaf
    str += "\\";//top left corner of back of loaf
    str += "\n";//end line

    //Depth lines
    for(var i = 0; i < depth - 1; i++){
        console.log(i)
        str += " ".repeat(depth - i - 1);//space padding before start of left middle edge
        if(i < height){
            //str += " ".repeat(depth - i - 2);
            str += "/";//left middle edge
            str += " ".repeat(width + i + 1);//middle of loaf
            str += "|";//end that edge
            str += "\n";//end line
        }else{
            str += "/";//left middle edge
            str += " ".repeat(width + height + 1);//between two /s
            str += "/";//right middle edge
            str += "\n";//end line
        }
    }

    //front top edge of loaf
    str += "/";//top left corner
    str += "-".repeat(width);//top edge
    str += "\\";//top right corner

    var i3 = 0;

    if(i < height){
        str += " ".repeat(depth - 1);//space for the incoming far right edge
        str += "|";//far right edge
        i++;
        i3++;
    }else{
        str += " ".repeat(height - i3);//space for the incoming far right edge
        str += "/";//far right edge
        i++;
        i3++;
    }

    str += "\n";//newline

    for(var i2 = 0; i2 < height; i2++){
        str += "|";//left edge
        str += (i2 === height - 1 ? "_" : " ").repeat(width);//if we are at the bottom, use underscores to mark that, otherwise spaces.
        str += "|";
        if(i < height){
            str += " ".repeat(depth - 1);//space for the incoming far right edge
            str += "|";//far right edge
            i++;
            i3++;
        }else{
            str += " ".repeat(height - i3);//space for the incoming far right edge
            str += "/";//far right edge
            i++;
            i3++;
        }
        str += "\n";//newline
    }

    return str;
};

```

```
s=(s,t)=>s.repeat(t);
var bakeBread = (d,c,e)=>{z=" ",y=`
`,x="\\",w="/",v="|",u="-";a=s(z,e--);a=a+w+s(u,d);a+=x+y;for(b=0;b<e;b++)a+=s(z,e-b),b<c?(a+=w,a+=s(z,d+b+1),a+=v):(a+=w,a+=s(z,d+c+1),a+=w),a+=y;a=a+w+s(u,d);a+=x;f=0;b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w);b++;f++;a+=y;for(g=0;g<c;g++)a+=v,a+=s((g==c-1?"_":z),d),a+=v,b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w),b++,f++,a+=y;return a}
```

```
<input type = "number" id = "a1">
<br/>
<input type = "number" id = "a2">
<br/>
<input type = "number" id = "a3">
<br/>
<button onclick = "document.getElementById('textarea').innerText = bakeBread(+(document.getElementById('a1').value), +(document.getElementById('a2').value), +(document.getElementById('a3').value))">Bake Bread!</button>
<br/>
<textarea id = "textarea"></textarea>
```

# Answer
> 3 votes
# C, ~~270~~ ~~290~~ ~~320~~ 328 bytes

```
#define P printf(
p(n,s)char*s;{P s,--n&&p(n,s));}i,j,k;f(w,h,d){P "%*c",d+1,47);p(w,"-");P "\\\n");for(i=d,j=h,k=0;--i;)P "%*c%*c\n",i+1,47,w+d+1-i-k+!!k,j-->0?124:(++k>0)*47);P "/");p(w,"-");P "\\%*c\n",d-k,j-->0?124:47);for(k&&k++;++i<h;)P "|%*c%*c\n",w+1,124,d-k>!k?d+1-k-!k:0,j-->0?124:(++k>0)*47);P "|");p(w,"_");P "|/");}

```

Finally (after ~~two~~ three incorrect versions) it works correctly with large sizes also.

Try it online!

# Answer
> 1 votes
# Python 2, ~~234~~ ~~216~~ 210 bytes

```
w,h,d=input()
f,g='|','/';z,s=g+'-'*w+'\\',' '
print'\n'.join([s*d+z]+[s*(d-c)+g+s*(w+c)+(f,g)[c>h]for c in range(1,d)]+[z+s*(d-1)+(f,g)[d>h]]+[f+s*w+f+s*(h-e-1)+(f,s+g)[d>=h]for e in range(1,h)]+[f+'_'*w+f+g])

```

Try it online!

~~Sure it can be golfed a lot more but it's a start.~~ 210 will do for me for now.

# Answer
> 1 votes
# PHP, 420 bytes

```
<?php $a=$_GET["a"];$b=$_GET["b"];$c=$_GET["c"];$w="<br>";$s=" ";$u="&#95";$p="|";$k="/";$t=str_repeat;$l='';$r=$t($s,$c).$k.$t("-",$a)."\\".$w;for($i=0;$i<$c+$b-1;$i++){$i<=$b-1?($i<$c-1?$l=$t($s,$a+$i+1).$p:$l=$t($s,$c-1).$p):($i<$c-1?$l=$t($s,$a+$b+1).$k:$l=$t($s,$c+$b-$i-1).$k);$i<$c-1?$r.=$t($s,$c-$i-1).$k.$l.$w:($i==$c-1?$r.=$k.$t("-",$a)."\\".$l.$w:$r.=$p.$t($s,$a).$p.$l.$w);};echo$r.=$p.$t($u,$a).$p.$k?>

```

Sounds like someone's fired - maybe try convincing your boss that it's much cooler on backend.

Input is attached to the URL string: `?a=[width]&b=[height]&c=[depth]`.

Ungolfed for transparency:

```
<?php
$a=$_GET["a"];$b=$_GET["b"];$c=$_GET["c"];
$w="<br>";$s=" ";$u="&#95"; $p="|";$k="/";$t=str_repeat;$f=$v=$m=$l='';
//first line
$r=$t($s,$c).$k.$t("-",$a)."\\".$w;

for($i=0;$i<$c+$b-1;$i++){

    //right side of the loaf
    $i <= $b-1
    ? ($i < $c-1 ? $l=$t($s,$a+$i+1).$p : $l=$t($s,$c-1).$p)
    : ($i < $c-1 ? $l=$t($s,$a+$b+1).$k : $l=$t($s,$c+$b-$i-1).$k) ;

    //left side, with the right side attached
    $i<$c-1
        ? $r.=$t($s,$c-$i-1).$k.$f.$l.$w
        : ($i==$c-1
            ? $r.=$k.$t("-",$a)."\\".$f.$l.$w
            : $r.=$p.$t($s,$a).$p.$f.$l.$w);

};
    //final line
    echo $r.=$p.$t($u,$a).$p.$k;

?>

```

# Answer
> 1 votes
## JavaScript (ES6), 204 bytes

```
(w,h,d)=>[...Array(h-~d)].map((_,y)=>[...Array(w-~d)].map((_,x)=>x+y==d|x+y==h+w-~d?`/`:x==w+d&y<=h&&y||!x|x==w&&y>d?`|`:y==h+d&x<w?`_`:!y|y==d?x+y==w+d?`\\`:x+y>d&x+y<w+d?`-`:` `:` `).join``,++w).join`\n`

```

Where `\n` represents the literal newline character.

Rather than fiddle around with repeating characters, this just creates a suitably sized array and computes which character appears in each cell.

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


title: Embedded Hexagons!

text:
# Question
Title: Embedded Hexagons!
Your task: given an integer `n`, generate an embedded hexagon pattern following the below rules, to the nth depth.

An embedded hexagon has the basic shape of this: (`n=0`)

```
 __
/  \
\__/

```

Embedded Hexagons `n=1` and `n=2`:

```
  ____
 /  \ \
/\__/  \
\      /
 \____/

    ________
   /  \ \   \
  /\__/  \   \
 /\      /    \
/  \____/      \
\              /
 \            /
  \          /
   \________/

```

The length of each side is 2 times the length of the same side in the previous depth times two. The top and bottom sides are 2 characters long when `n=0` and the rest start out as 1 character long. The non top-bottom side lengths should be `2^n` long (OEIS: A000079) and the top and bottom sides should follow the rule `2^(n+1)` (same OEIS).

The current hexagons are 0-indexed, you may chose to use 1-indexed if you want.

This is , so the shortest answer wins!

# Answer
> 9 votes
# Charcoal, ~~40~~ 29 bytes

*11 bytes saved thanks to @Neil by changing the while loop to a for-loop amongst other tricks*

```
ＦＮ«ＡＸ²ιβ×__β↓↘β←↙β↑←×__β↖β→↗β

```

Try it online!

### Explanation (outdated)

This program starts with generating the largest hexagon, and then does the smaller ones one-by-one in a while loop (1-indexed). For reference, `α` is the input number, `β` is the variable that contains `2^(α-1)` and `ι` is the iterating variable in the loop.

```
Ｎα                        # Take input and store in α
Ｗα«                       # While α do:
 ×_Ｘ²ι                    #  Write "_"*(2**ι); this forms the top edge of the hexagon
 ↓                         #  Go down
 ＡＸ²⁻ι¹β                 #  Assign 2**(ι-1) to β
 ↘β←                       #  Write \ β times in a SE direction (top right edge) and then go left
 ↙β↑                       #  Write / β times in a SW direction (bottom right edge) and then go up
 ←×_Ｘ²ι                   #  Write the bottom edge
 ↖β→↗β                    #  Just like before, write the top and bottom left edges
 Ａ⁻α¹α                    #  Decrement α
                          # Now the pointer is at the top left corner of the hexagon,
                          # from where the other smaller hexagons will soon be generated

```

# Answer
> 5 votes
# Haskell, ~~230~~ ~~217~~ 207 bytes

EDIT:

* -13 bytes: @xnor saw that my `#` could be just `max`.
* -10 bytes: And also that `zipWith` and `p` could be merged into a `?` operator, and that I'd (somehow!) reimplemented `replicate`.

`m` takes an `Integer` and returns a `String`.

```
m n=unlines.foldr1 o$((2^n)&).(2^)<$>[0..n]
l&t|a<-c[l,2*t]" _",b<-[c[l-i,1,2*t+2*i-2,1,l-i]" / \\ "|i<-[1..t]]=a:b++r(r<$>o[a]b)
c=(concat.).z replicate
o=max?' '?""
f?e=z f.(++repeat e)
r=reverse
z=zipWith

```

Try it online!

# How it works

* `m` is the main function. It uses `&` to generate the hexagons with proper padding, then folds them together with `o`.
* `l&t` generates a small hexagon of side length `t`, padded inside a large one of side length `l`, as a list of `String` lines.
    + `a` is the top line of the hexagon, with the underscores.
    + `b` is a list of the other lines in the upper half of the hexagon. The lines of `b` are centered in the padding, which is rectangular; this allows the next step to work.
    + The bottom half of the hexagon is `a` overlaid on top of `b` with `o`, then reversed (both order of lines and within each line).
* `c` takes two arguments, a list of lengths and a string, and generates a string that has as many copies of each character in the original as the corresponding length, e.g. `c[1,3,2]"abc" == "abbbcc"`. It is used in `&` to generate the lines.
* `o` takes two arguments representing pictures as lists of lines, and overlays the first, smaller one on top of the second one.
    + It is used both to combine hexagons and to add the bottom to each hexagon.
    + It essentially works by using `?` twice to pad the first picture with infinitely many spaces both downwards and rightwards, then zipping together corresponding characters with `max`, which selects the non-space character if there is one.
* `(f?e)l m` pads a list `l` by appending infinitely many 'e' elements, then zips the resulting list and the list `m` with the `f` function.

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

```
f=(n,s=` `.repeat(1<<n),p=(n?f(n-1):`

`).replace(/(.*)\n/g,s+`$1 `+s)+s,t=`_`.repeat(2<<n))=>(s+t+s+`
`+s.replace(/ /g,"$'/$'$'  $`$`$`$`\\$'\n")).replace(/ /g,(c,i)=>p[i+(1<<n>>1)])+s.replace(/ /g,"$`\\$`$`  $'$'$'$'/$`\n").replace(/ +\/( *)\n$/,t+`/$1
`)
```

```
<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>
```

Explanation: For hexagons after the first, the previous hexagon is first generated and padded on each side (this relies on the output being a rectangle). (For the first heading, some dummy padding is created.) The top and top sides of the hexagon are generated, and all the spaces merged with the previous hexagon. (There's some trickery in order to get the hexagons to line up; this would be easier if extra margins were allowed.) The bottom sides of the hexagon are generated analogously to the top sides, and the bottom of the hexagon is then filled in. Care has to be taken to return rectangular output, including a trailing newline, for the recursion to work.

# Answer
> 2 votes
# PHP, 337 Bytes

0 Indexing

```
$h=array_fill(0,1+2*$v=2**($c=$argn),str_pad("",4*$v));for(;1+$c;$c--)for($i=0;$i<$e=2**$c*2+1;$i++){$z=$e-$i<2;$y=$i&&$i<$e/2;$x=$i>=$e/2&$i<$e-1;$h[$i]=substr_replace($h[$i],$s=str_pad(!$y?$z|$x?"\\":"":"/",$e-1+$z-$y+$y*$i*2-$x+$x*2*($e-$i),$z|!$i?"_":" ").(!$y?$z|$x?"/":"":"\\"),$v-$z-$y*$i-$x*($e-$i),strlen($s));}echo join("\n",$h);

```

Try it online!

Expanded

```
$h=array_fill(0,1+2*$v=2**($c=$argn),str_pad("",4*$v)); # fill array with maximal width
for(;1+$c;$c--)  # greatest hexagon to lowest
for($i=0;$i<$e=2**$c*2+1;$i++){ # loop through the rows
    $z=$e-$i<2;$y=$i&&$i<$e/2;$x=$i>=$e/2&$i<$e-1; # booleans last first ad second half
    $h[$i]=substr_replace($h[$i], # replace substring
    $s=str_pad(
        $z?"\\":($y?"/":($x?"\\":"")),
        $e-1+$z-$y+$y*$i*2-$x+$x*2*($e-$i),
        $z|!$i?"_":" "
        ).(!$z?!$y?$x?"/":"":"\\":"/"), # with string for smaller hexagon
    $v-$z-$y*$i-$x*($e-$i), # at offset
    strlen($s));
}
echo join("\n",$h); # Output

```

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


# Question
Title: Is this number an exact power of -2: (Very) Hard Mode
This is a version of the recent challenge Is this number an integer power of -2? with a different set of criteria designed to highlight the interesting nature of the problem and make the challenge more difficult. I put some consideration into it here.

The challenge as wonderfully stated by Toby in the linked question, is:

> There are clever ways of determining whether an integer is an exact power of 2. That's no longer an interesting problem, so let's determine whether a given integer is an exact power of **-2**. For example:
>
> ```
> -2 => yes: (-2)¹
> -1 => no
> 0 => no
> 1 => yes: (-2)⁰
> 2 => no
> 3 => no
> 4 => yes: (-2)²
>
> ```

## Rules:

* An integer is 64 bits, signed, two's complement. This is the *only* data type you may work with.
* **You may only use the following operations. Each of these counts as one operation.**
    + `n << k`, `n >> k`: Left/right shift `n` by `k` bits. Sign bit is extended in right shift.
    + `n >>> k`: Right shift but do not extend sign bit. 0's are shifted in.
    + `a & b`, `a | b`, `a ^ b`: Bitwise AND, OR, XOR.
    + `a + b`, `a - b`, `a * b`: Add, subtract, multiply.
    + `~b`: Bitwise invert.
    + `-b`: Two's complement negation.
    + `a / b`, `a % b`: Divide (integer quotient, rounds towards 0), and modulo.
        - Modulo of negative numbers uses the rules specified in C99: `(a/b) * b + a%b` shall equal `a`. So `5 % -3` is `2`, and `-5 % 3` is `-2`:
        - `5 / 3` is `1`, `5 % 3` is `2`, as 1 * 3 + 2 = 5.
        - `-5 / 3` is `-1`, `-5 % 3` is `-2`, as -1 * 3 + -2 = -5.
        - `5 / -3` is `-1`, `5 % -3` is `2`, as -1 * -3 + 2 = 5.
        - `-5 / -3` is `1`, `-5 % -3` is `-2`, as 1 * -3 + -2 = -5.
        - Note that Python's `//` floor division operator does not satisfy the "round towards 0" property of division here, and Python's `%` operator does not meet the requirements, either.
    + Assignments do not count as an operation. As in C, assignments evaluate to the value of the left-hand side after the assignment: `a = (b = a + 5)` sets `b` to `a + 5`, then sets `a` to `b`, and counts as one operation.
    + Compound assignments may be used `a += b` means `a = a + b` and count as one operation.
* You may use integer constants, they do not count as anything.
* Parentheses to specify order of operations are acceptable.
* You may declare functions. Function declarations can be in any style that is convenient for you but note that 64 bit integers are the *only* valid data type. Function declarations do not count as operations, but a function *call* counts as one. Also, to be clear: Functions may contain multiple `return` statements and `return`s from any point are allowed. The `return` itself does not count as an operation.
* You may declare variables at no cost.
* You may use `while` loops, but you may not use `if` or `for`. Operators used in the `while` condition count towards your score. `while` loops execute as long as their condition evaluates to a *non-zero* value (a "truthy" 0 in languages that have this concept is not a valid outcome). Since early-return is allowed, you are allowed to use `break` as well
* Overflow/underflow is allowed and no value clamping will be done. It is treated as if the operation actually happened correctly and was then truncated to 64 bits.

## Scoring / Winning Criteria:

Your code must produce a value that is non-zero if the input is a power of -2, and zero otherwise.

This is . Your score is the total number of operations present in your code (as defined above), *not* the total number of operations that are executed at run-time. The following code:

```
function example (a, b) {
    return a + ~b;
}

function ispowerofnegtwo (input) {
    y = example(input, 9);
    y = example(y, 42);
    y = example(y, 98);
    return y;
}

```

Contains 5 operations: two in the function, and three function calls.

It doesn't matter how you present your result, use whatever is convenient in your language, be it ultimately storing the result in a variable, returning it from a function, or whatever.

The winner is the post that is demonstrably correct (supply a casual or formal proof if necessary) and has the lowest score as described above.

## Bonus *Very* Hard Mode Challenge!

For a chance at winning absolutely nothing except the potential ability to impress people at parties, submit an answer without using `while` loops! If enough of these are submitted I may even consider dividing the winning groups into two categories (with and without loops).

---

Note: If you'd like to provide a solution in a language that only supports 32-bit integers, you may do so, provided that you sufficiently justify that it will still be correct for 64-bit integers in an explanation.

Also: *Certain* language-specific features may be permitted at no-cost *if they do not evade the rules but are necessary to coerce your language into behaving according to the rules above*. For example (contrived), I will permit a free *not equals 0* comparison in `while` loops, when applied to the condition as a whole, as a workaround for a language that has "truthy" 0's. *Clear attempts to take advantage of these types of things are not allowed* -- e.g. the concept of "truthy" 0 or "undefined" values does not exist in the above ruleset, and so they may not be relied on.

# Answer
# C++, 15 operations

I have no idea why `while` loops are allowed as they destroy the whole challenge. Here is an answer without any:

```
int64_t is_negpow2(int64_t n) {
    int64_t neg = uint64_t(n) >> 63; // n >>> 63
    n = (n ^ -neg) + neg; // if (n < 0) n = -n;
    int64_t evenbits = n & int64_t(0xaaaaaaaaaaaaaaaaull >> neg);
    int64_t n1 = n - 1;
    int64_t pot = n & n1;
    int64_t r = pot | (n1 >> 63) | evenbits;
    return ~((r | -r) >> 63); // !r
}

```
> 36 votes

# Answer
# Python 2, 3 operations

```
def f(n):
 while n>>1:
  while n&1:return 0
  n=n/-2
 return n

```

Try it online!

The operations are `>>`, `&`, `/`.

The idea is to repeatedly divide by -2. Powers of -2 chain down to 1: `-8 -> 4 -> -2 -> 1`. If we hit a `1`, accept. If we hit an odd number before hitting `1`, reject. We also need to reject `0`, which forever goes to itself.

The `while n>>1:` loops until `n` is 0 or 1. When the loop breaks, `n` itself is returned, and `1` is a Truthy output and `0` a Falsey one. Inside the loop, we reject repeatedly apply `n -> n/-2` and reject any odd `n`.

Since the `/` is only ever used on even values, its rounding behavior never comes into play. So, it doesn't matter that Python rounds differently from the spec.
> 26 votes

# Answer
# Rust, ~~14~~ 12 operations (no loops)

Requires optimization (`-O`) or `-C overflow-checks=no` to enable the overflowing subtraction instead of panic.

```
fn is_power_of_negative_2(input: i64) -> i64 {
    let sign = input >> 63;
    // 1 op
    let abs_input = (input ^ sign) - sign;
    // 2 ops
    let bad_power_of_two = sign ^ -0x5555_5555_5555_5556; // == 0xaaaa_aaaa_aaaa_aaaa
    // 1 op
    let is_not_power_of_n2 = abs_input & ((abs_input - 1) | bad_power_of_two);
    // 3 ops
    let is_not_power_of_n2 = (is_not_power_of_n2 | -is_not_power_of_n2) >> 63;
    // 3 ops
    input & !is_not_power_of_n2
    // 2 ops
}

```

(To clarify: `!x` is bitwise-NOT here, not logical-NOT)

Test cases:

```
#[test]
fn test_is_power_of_negative_2() {
    let mut value = 1;
    for _ in 0 .. 64 {
        assert_ne!(0, is_power_of_negative_2(value), "wrong: {} should return nonzero", value);
        value *= -2;
    }
}

#[test]
fn test_not_power_of_negative_2() {
    for i in &[0, -1, 2, 3, -3, -4, 5, -5, 6, -6, 7, -7, 8, 1<<61, -1<<62, 2554790084739629493, -4676986601000636537] {
        assert_eq!(0, is_power_of_negative_2(*i), "wrong: {} should return zero", i);
    }
}

```

Try it online!

---

The idea is to check if |x| is a power of 2 (using `(y & (y - 1)) == 0` as usual). If x is a power of 2, then we further check (1) when `x >= 0`, it should also be an even power of 2, or (2) when `x < 0`, it should be an odd power of 2. We check this by `&`-ing the "`bad_power_of_two`" mask 0x…aaaa when `x >= 0` (produces 0 only when it is an even power), or 0x…5555 when `x < 0`.
> 11 votes

# Answer
# C, 5 operations

```
long long f(long long x){
    x=x ^ ((x & 0xaaaaaaaaaaaaaaaa) * 6);
    while(x){
        while(x&(x-1))
            return 0;
        return 1;
    }
    return 0;
}

```

# C, 10 operations, without loops

```
long long f(long long x){
    x = x ^ ((x & 0xaaaaaaaaaaaaaaaa) * 6);
    long long t = x & (x-1);
    return (((t-1) & ~t) >> 63) * x;
}

```

# C, 1 operation

```
long long f(long long x){
    long long a0=1, a1=-2, a2=4, a3=-8, a4=16, a5=-32, a6=64, a7=-128, a8=256, a9=-512, a10=1024, a11=-2048, a12=4096, a13=-8192, a14=16384, a15=-32768, a16=65536, a17=-131072, a18=262144, a19=-524288, a20=1048576, a21=-2097152, a22=4194304, a23=-8388608, a24=16777216, a25=-33554432, a26=67108864, a27=-134217728, a28=268435456, a29=-536870912, a30=1073741824, a31=-2147483648, a32=4294967296, a33=-8589934592, a34=17179869184, a35=-34359738368, a36=68719476736, a37=-137438953472, a38=274877906944, a39=-549755813888, a40=1099511627776, a41=-2199023255552, a42=4398046511104, a43=-8796093022208, a44=17592186044416, a45=-35184372088832, a46=70368744177664, a47=-140737488355328, a48=281474976710656, a49=-562949953421312, a50=1125899906842624, a51=-2251799813685248, a52=4503599627370496, a53=-9007199254740992, a54=18014398509481984, a55=-36028797018963968, a56=72057594037927936, a57=-144115188075855872, a58=288230376151711744, a59=-576460752303423488, a60=1152921504606846976, a61=-2305843009213693952, a62=4611686018427387904, a63=-9223372036854775807-1, a64=0;
    while(a0){
        long long t = x ^ a0;
        long long f = 1;
        while(t){
            f = 0;
            t = 0;
        }
        while(f)
            return 1;
        a0=a1; a1=a2; a2=a3; a3=a4; a4=a5; a5=a6; a6=a7; a7=a8; a8=a9; a9=a10; a10=a11; a11=a12; a12=a13; a13=a14; a14=a15; a15=a16; a16=a17; a17=a18; a18=a19; a19=a20; a20=a21; a21=a22; a22=a23; a23=a24; a24=a25; a25=a26; a26=a27; a27=a28; a28=a29; a29=a30; a30=a31; a31=a32; a32=a33; a33=a34; a34=a35; a35=a36; a36=a37; a37=a38; a38=a39; a39=a40; a40=a41; a41=a42; a42=a43; a43=a44; a44=a45; a45=a46; a46=a47; a47=a48; a48=a49; a49=a50; a50=a51; a51=a52; a52=a53; a53=a54; a54=a55; a55=a56; a56=a57; a57=a58; a58=a59; a59=a60; a60=a61; a61=a62; a62=a63; a63=a64;
    }
    return 0;
}

```
> 8 votes

# Answer
# Haskell, 2 3 operations

```
import Data.Bits (.&.)

f 0 = False
f 1 = True
f n | n .&. 1 == 0 = f (n `div` -2)
f n | otherwise    = False

```

Defines a recursive function `f(n)`. Operations used are function call (`f`), division (`div`), and bitwise and (`.&.`).

Contains no loops because of the fact that Haskell has no loop statements :-)
> 6 votes

# Answer
# Python 3, ~~10 or 11~~ 9 operations

```
def g(x):
 while x:
  while 1 - (1 + ~int(x - -2 * int(float(x) / -2))) & 1: x /= -2
  break
 while int(1-x):
     return 0
 return 5  # or any other value

```

Returns `5` for powers of `-2`, `0` otherwise
> 5 votes

# Answer
# C, 31 operations

**Live Demo**

My idea is simple, if it's a power of two, then if its log is even then it has to be positive, otherwise its log has to be odd.

```
int isPositive(int x) // 6
{
    return ((~x & (~x + 1)) >> 31) & 1;
}

int isPowerOfTwo(int x) // 5
{
    return isPositive(x) & ~(x & (x-1));
}

int log2(int x) // 3
{
    int i = (-1);

    while(isPositive(x))
    {
        i  += 1;
        x >>= 1;
    }

    return i;
}

int isPowerOfNegativeTwo(int x) // 17
{
    return (  isPositive(x) &  isPowerOfTwo(x) & ~(log2(x) % 2) )
         | ( ~isPositive(x) & isPowerOfTwo(-x) & (log2(-x) % 2) );
}

```
> 4 votes

# Answer
# Assembly, 1 operation

```
.data

    .space 1         , 1 # (-2)^31
    .space 1610612735, 0
    .space 1         , 1 # (-2)^29
    .space 402653183 , 0
    .space 1         , 1 # (-2)^27
    .space 100663295 , 0
    .space 1         , 1 # (-2)^25
    .space 25165823  , 0
    .space 1         , 1 # (-2)^23
    .space 6291455   , 0
    .space 1         , 1 # (-2)^21
    .space 1572863   , 0
    .space 1         , 1 # (-2)^19
    .space 393215    , 0
    .space 1         , 1 # (-2)^17
    .space 98303     , 0
    .space 1         , 1 # (-2)^15
    .space 24575     , 0
    .space 1         , 1 # (-2)^13
    .space 6143      , 0
    .space 1         , 1 # (-2)^11
    .space 1535      , 0
    .space 1         , 1 # (-2)^9
    .space 383       , 0
    .space 1         , 1 # (-2)^7
    .space 95        , 0
    .space 1         , 1 # (-2)^5 = -32
    .space 23        , 0
    .space 1         , 1 # (-2)^3 = -8
    .space 5         , 0
    .space 1         , 1 # (-2)^1 = -2
    .space 1         , 0
dataZero:
    .space 1         , 0
    .space 1         , 1 # (-2)^0 = 1
    .space 2         , 0
    .space 1         , 1 # (-2)^2 = 4
    .space 11        , 0
    .space 1         , 1 # (-2)^4 = 16
    .space 47        , 0
    .space 1         , 1 # (-2)^6 = 64
    .space 191       , 0
    .space 1         , 1 # (-2)^8
    .space 767       , 0
    .space 1         , 1 # (-2)^10
    .space 3071      , 0
    .space 1         , 1 # (-2)^12
    .space 12287     , 0
    .space 1         , 1 # (-2)^14
    .space 49151     , 0
    .space 1         , 1 # (-2)^16
    .space 196607    , 0
    .space 1         , 1 # (-2)^18
    .space 786431    , 0
    .space 1         , 1 # (-2)^20
    .space 3145727   , 0
    .space 1         , 1 # (-2)^22
    .space 12582911  , 0
    .space 1         , 1 # (-2)^24
    .space 50331647  , 0
    .space 1         , 1 # (-2)^26
    .space 201326591 , 0
    .space 1         , 1 # (-2)^28
    .space 805306367 , 0
    .space 1         , 1 # (-2)^30
    .space 3221225471, 0
    .space 1         , 1 # (-2)^32

.globl isPowNeg2
isPowNeg2:
    movl dataZero(%edi), %eax
    ret

```

Uses a huge lookup table to find whether the number is a power of 2. You can expand this to 64 bits, but finding a computer to store that much data is left as an exercise to the reader :-P
> 4 votes

# Answer
# PHP, 3 operations

ternary and `if` are disallowed; so let´s abuse `while`:

```
function f($n)
{
    while ($n>>1)               # 1. ">>1"
    {
        while ($n&1)            # 2. "&1"
            return 0;
        return f($n/-2|0);      # 3. "/-2" ("|0" to turn it into integer division)
    }
    return $n;
}

```
1. `$n>>1`: if number is 0 or 1, return number
2. `$n&1`: if number is odd, return 0
3. else test `$n/-2` (+cast to int)
> 1 votes

# Answer
# C, 7 operations

```
int64_t is_power_of_neg2(int64_t n)
{
    int64_t x = n&-n;
    while (x^n) {
        while (x^-n)
            return 0;
        return x & 0xaaaaaaaaaaaaaaaa;
    }
    return x & 0x5555555555555555;
}

```

or:

# C, 13 operations without loops-as-conditionals

```
int64_t is_power_of_neg2(int64_t n)
{
    int64_t s = ~(n>>63);
    int64_t a = ((n/2)^s)-s;
    int64_t x = n&-(uint64_t)n; // Cast to define - on INT64_MIN.
    return ~(a/x >> 63) & x & (0xaaaaaaaaaaaaaaaa^s);
}

```

Explanation:

* `n&-n` yields the lowest set bit of `n`.
* `a` is the negated absolute value of `n/2`, necessarily negative because `/2` precludes overflow of negation.
* `a/x` is zero only if `a` is an exact power of two; otherwise at least one other bit is set, and it's higher than `x`, the lowest bit, yielding a negative result.
* `~(a/x >> 63)` then yields a bitmask that's all-ones if `n` or `-n` is a power of two, otherwise all-zeros.
* `^s` is applied to the mask to check the sign of `n` to see if it's a power of `-2`.
> 1 votes

# Answer
# JavaScript ES6, 7 operations

```
x=>{
  while(x&1^1&x/x){
    x/=-2;x=x|0
  }
  while(x&0xfffffffe)x-=x
  return x
}

```

Try it online!

## Explanation

```
while(x&1^1&x/x)

```

While x!=0 and x%2==0 **4 ops**
x/x is equal to 1 so long as x is not 0 (0/0 gives NaN which is evaluated as false)
& bitwise and
x&1^1 is equal to 1 if x is even (x and 1) xor 1

```
x/=-2;x=x|0

```

This is the form of division defined by the question **1 op**

```
while(x&0xfffffffe)

```

While x!=1 and x!=0 **1 op**
The condition needed to exit when x==0 or x==1 as those two are the return values and entering an infinite loop would not be productive. This could theoretically be extended for greater values by increasing the hexadecimal number. Currently works for up to ±2^32-1

```
x-=x

```

Set x to 0 **1 op**
While I could have used return 0 for 0 ops, I felt that any while loop which is broken by another statement feels too much like cheating.

```
return x

```

returns x (1 if power of -2, 0 otherwise)
> 0 votes

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


title: Count up by Syllables

text:
# Question
Title: Count up by Syllables
# Backstory

I've always found it quite annoying how some numbers in English don't have the same number of syllables even though they have the same number of digits. Example: `seven` has 2 syllables whereas all of the other digits have one (other than `zero`).

So, when I'm counting in time to something (like a drill cadence in cadets or in the military), it doesn't sound as nice because you have a random extra syllable.

But I appear to have found a solution to this!

Instead of counting the regular way, we omit the number `eight`. That way, the second syllable of `seven` carries into where `eight` would have been. So, we get the following:

```
1     2     3     4     5     6     7     8     9     10
one   two   three four  five  six   se   -  ven nine  ten

```

But, it's hard to count this way for higher numbers, so I need your help to make a program to help me figure out which numbers to count!

# Challenge Details

### Input

Input will be given as a single positive integer. For the purposes of this challenge, you may assume that all numbers are less than or equal to `999 999 999 999 999` (`1 quadrillion - 1`) This is because "quadrillion" has a different number of syllables than "million", "billion", and "trillion", and I needed to specify an upper bound somewhere. Since as @HelkaHomba pointed out most languages have a cap at `2^32` which is somewhere around 4 billion, you can use your language's integer bound as the limit (this must be at least 1 million to be considered valid).

### Output

Output will be given as a list of integers (to be specified below). The exact formatting will not be specified, but as long as it is easy to see what the list is and it does not contain arbitrary numbers everywhere, it is pretty flexible.

### What's in the list

Pretty much, starting from `i = 1`, append `i` to the list. Then, take the number of syllables in `i` (let this be `s`) and omit the next `s - 1` numbers. Keep doing this until `i > n` where `n` is the input.

For the purposes of this challenge, assume that the word `and` is never present (so `101` is `one hundred one`).

# Test Cases

```
Input -> Output
10 -> 1 2 3 4 5 6 7 9 10
7 -> 1 2 3 4 5 6 7
8 -> 1 2 3 4 5 6 7
25 -> 1 2 3 4 5 6 7 9 10 11 14 16 18 20 22 25

```

Additionally, since I need to be able to carry this around on a cue card when counting things in time, your program needs to be as short as possible (in bytes)!

# Answer
# Mathematica, 117 bytes

```
For[t=1,t<=#,t+=Length[Join@@(#~WordData~"Hyphenation"&/@StringSplit[Echo@t~IntegerName~"Words",{"‐",", "," "}])]]&

```

Pure function taking a nonnegative integer as input; it echoes the appropriate integers to the standard output one at a time.

There might well be a shorter implementation in Mathematica, but this is the lazy one :) `t~IntegerName~"Words"` gives the English name of the integer `t`; then `StringSplit[...,{"‐",", "," "}]` divides this name into a list of individual words. (Mathematically annoyingly uses the 3-byte character  (U+2010) for the hyphen in names of integers.) `#~WordData~"Hyphenation"&/@` splits each of those words into a list of its syllables, and `Length[Join@@(...)]` counts these syllables.

Thus the function, after initializing `t=1`, loops as long as `t` doesn't exceed the input; each time, it prints `t` and then augments it by the number of syllables in the English name of `t`. In principle, this algorithm works up to 1036–1, at which point the hyphenation dictionary doesn't have an entry for "undecillion".
> 1 votes

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


title: Do a BackFlip for ais523!

text:
# Question
Title: Do a BackFlip for ais523!
This challenge is a prize for ais523 for winning the "Rookie of the Year" category in "Best of PPCG 2016". Congratulations!

---

BackFlip is an esoteric programming language made by user ais523, who has created well over 30 other interesting esolangs.

BackFlip is a 2D language like Befunge or \>\<\> where the instruction pointer traverses a grid of text (the program), moving up, down, left, and right, changing direction depending on the character it's on. Critically, the grid in a BackFlip program changes as it is being traversed, a bit like Langton's Ant.

For this challenge you may assume that a BackFlip program is always a rectangular grid of text (all lines the same length), 1×1 in size at minimum, only containing the characters `./\<>^V`. (`.` is used for visibility rather than space.) Semantically the BackFlip we'll use here is identical to the original spec.

The instruction pointer (IP) in BackFlip always starts just left of the top-left corner of the program, heading right. There are three types of commands it can encounter:

1. `.` is a no-op. The IP continues on in the direction it was going. The no-op stays a no-op.
2. `/` and `\` are mirrors. They reflect the IP in the direction indicated by their angle, then **they change into the other type of mirror**.

* For example, if the IP heads left into a `\`, it starts moving upward instead of left and the `\` becomes a `/`.
3. `<`, `>`, `^`, and `V` are arrows. They redirect the IP to the direction they point in, then **they change into an arrow that points in the direction the IP came from (opposite the direction the IP was moving)**.

* For example, if the IP heads downward into `>`, it starts moving right instead of downwards and the `>` becomes a `^` because that is the direction the IP came from.

A BackFlip program terminates when the IP moves out of bounds, i.e. goes off the grid. It turns out *all* BackFlip programs eventually end because infinite loops are impossible. (You may assume this is true.)

Your goal in this challenge is to write a program or function that takes in a BackFlip program and outputs the number of moves the instruction pointer takes before the program terminates. That is, **how many steps does the IP take in the course of running a program?** This includes the initial step onto the grid and the final step off of it.

For example, the instruction pointer takes 5 steps in the trivial grid `....`:

```
 ....  <- empty 4×1 grid
012345 <- step number of the IP

```

So the output to `....` is `5`.

In the more complex 4×2 grid

```
\...
\.><

```

the IP exits the grid on its 9th step, so the output is `9`:

```
step  grid  IP position (@)
0     \...  @....
      \.><   ....

1     \...   @...
      \.><   ....

2     /...   ....
      \.><   @...

3     /...   ....
      /.><   .@..

4     /...   ....
      /.><   ..@.

5     /...   ....
      /.<<   ...@

6     /...   ....
      /.<<   ..@.

7     /...   ....
      /.><   .@..

8     /...   ....
      /.><   @...

9     /...   ....
      \.><   ....
             @

```

**The shortest code in bytes wins.**

You may take input as an array of lines or matrix of characters instead of a multiline string if desired, but you must use the characters `./\<>^V` (not integer opcodes). You may use space instead of `.` if preferred. It's fine if characters like `\` need to be escaped in input. Output is always an integer more than one.

# Test Cases

```
....
5

\...
\.><
9

.
2

..
3

.
.
2

\
2

^
2

.^.
3

<.
2

\\
\/
7

>V
^<
6

>\
>/
6

\><
2

\><
\><
7

\><
\><
\><
12

\.V.
\.\<
5

\.V.
\./<
9

V./\
V./\
>./<
..\/
14

\V..
.^..
\/><
.V..
.^..
20

\.V.V.
\./.\<
.>\<..
..^.^.
31

\.V.V.V.
\./>/.\<
.>\>\<..
..^.^.^.
69

\.V.V.V.V.
\./>/>/.\<
.>\>\>\<..
..^.^.^.^.
145

\.V.V.V.V.V.V.V.V.V.V.
\./>/>/>/>/>/>/>/>/.\<
.>\>\>\>\>\>\>\>\>\<..
..^.^.^.^.^.^.^.^.^.^.
9721

```

# Answer
## JavaScript (ES6), 158 bytes

```
f=(a,x=0,y=0,d=3)=>a[x]&&(c=a[x][y])?(a[x][y]=c=='.'?c:c=='/'?(d^=3,'\\'):c=='\\'?(d^=1,'/'):'v>^<'[d][d='^<v>'.search(c),0],f(a,d<3?x+d-1:x,d?y+d-2:y,d)+1):1

```

Developed independently from @tsh's answer although strikingly similar.

The mapping of directions `^<v>` to integers 0-3 is governed by the fact that `.search('^')` returns 0 since `^` is a regexp metacharacter.
> 4 votes

# Answer
# Haskell, ~~333~~ 325 bytes

EDIT:

* -8 bytes: Made `f` pointfree and merged into `b`.

`b` takes a list of `String`s and returns an `Integer`.

```
data C a=C{c::a->(a,C a)}
b g=[0,0]#([0,1],map(maybe(C$m 1)C.(`lookup`zip"./^>V<"[n,m(-1),a[-1,0],a[0,1],a[1,0],a[0,-1]]))<$>g)
[y,x]#(d,g)|g&y||g!!0&x=1|n@([f,e],_)<-(($d).c)?x?y$g=1+[y+f,x+e]#n
l&i=i<0||i>=length l
(f?i)l|(p,a:r)<-splitAt i l=(p++).(:r)<$>f a
n d=(d,C n)
a v d=(v,C$a$(0-)<$>d)
m s[d,e]=([s*e,s*d],C$m(-s))

```

Try it online!

# How it works

* `C a` is a data type used because Haskell won't allow a type to be recursive without declaring it explicitly. `C` is also a wrapping constructor and `c` is its corresponding unwrapping function. It is only used with `a=[Int]`.
    + The type `C [Int]` represents a cell command, as a function that takes a direction (`[Int]`) argument, and returns a pair of a new direction, and a new `C [Int]` value.
* `b` is the main function. It converts each character into a `C` value, then it calls `#`.
    + `g` is the grid as a list of strings.
    + Since `\`  needs to be escaped and so is the longest character to mention, its result is instead used as the default value for the list lookup.
* `#` runs the main simulation, checking bounds with `&` and generating new grids with `?`. `[y,x]` is the current position, `d` the current direction, and `g` the current grid. `[f,e]` is the next direction, and `n` is a pair of it and the next grid.
* `l&i` checks if the index `i` is out of bounds for the list `l`. (It returns `True` for out of bounds, since that avoids a dummy guard condition in `#`.)
* When `f(l!!i)==(d,x)`, `(f?i)l==(d,m)` where `m` is the list `l` with the `i`th element replaced with `x`.
    + Technically `(?i)` is a more general lens, focusing on the i'th element of a list, in this case used with the `(,) [Int]` functor instance.
* `n` is the function representing a dot.
* `a v` is a function representing an arrow in direction `v`.
* `m s` is a function representing a mirror; `s==1` for `\\` and `s==-1` for `/`.
> 3 votes

# Answer
# Python 3, 286 bytes

\[f() takes input in the form of `{(0,0):'/',(0,1):'.'}` so I have also written a function g() for converting an array of lines to that form\]

```
def f(r):
 x=y=0;d='>';s=1
 while 1:
  try:c=r[y,x];m='>^<V'.find(d)
  except:break
  if(c=="\\"):d='V<^>'[m];r[y,x]="/"
  elif(c=="/"):d='^>V<'[m];r[y,x]="\\"
  elif(c!="."):r[y,x]='<V>^'[m];d=c
  x+=1if(d=='>')else-1if(d=='<')else 0;y+=1if(d=='V')else-1if(d=='^')else 0;s+=1
 return s

```

Try it online!
> 1 votes

# Answer
# JavaScript, 172 bytes

```
f=(a,d=3,x=0,y=0,n=1)=>(p=a[y]||[],q=p[x])?(p[x]=~(t='^<V>'.indexOf(q))?'^<V>'[d^2]:q=='/'?(t=3-d,'\\'):q=='\\'?(t=d^1,'/'):(t=d,q),f(a,t,x+(t&1&&t-2),y+(~t&1&&t-1),n+1)):n

```

But i cannot test last testcase since i got stack overflow on my machine. (should work if there is a machine with larger ram)

We use a number for direction:

* 0: ^
* 1: \<
* 2: V
* 3: \>

Let `d` be the direction number...

* if we meet a '/', we need d = 3 - d;
* if we meet a '\\' we need d = d ^ 1;
* if we meet a '^\<V\>' we need d = '^\<V\>'.indexOf(note)

Let `(x, y)` be current position, the next position is: `x+(t&1&&t-2)`, `y+(~t&1&&t-1)`

**Note:**

The function takes one paramter with the following format:

```
[ [ '\\', '.', 'V', '.', 'V', '.', 'V', '.', 'V', '.' ],
  [ '\\', '.', '/', '>', '/', '>', '/', '.', '\\', '<' ],
  [ '.', '>', '\\', '>', '\\', '>', '\\', '<', '.', '.' ],
  [ '.', '.', '^', '.', '^', '.', '^', '.', '^', '.' ] ]

```

**Test it here**

```
f=(a,d=3,x=0,y=0,n=1)=>(p=a[y]||[],q=p[x])?(p[x]=~(t='^<V>'.indexOf(q))?'^<V>'[d^2]:q=='/'?(t=3-d,'\\'):q=='\\'?(t=d^1,'/'):(t=d,q),f(a,t,x+(t&1&&t-2),y+(~t&1&&t-1),n+1)):n

    ;k=x=>x.split('\n').map(t=>t.split(''));
```

```
<textarea id=v>\.V.V.V.V.
\./>/>/.\<
.>\>\>\<..
..^.^.^.^.</textarea><br/><button onclick="r.textContent=f(k(v.value))">Solve</button>
<p>Result: <output id=r></output></p>
```
> 1 votes

# Answer
# C, ~~232~~ 221 bytes

```
d,n,t,m[4]={1,-1};char*w="><^V/\\.",*P;main(o,v)char**v;{for(P=v[1],m[2]=-(m[3]=strchr(P,10)-P+1);P>=v[1]&&P<strchr(v[1],0)&&*P^10;++n)*P=w[((o=d,t=strchr(w,*P)-w)<4)?d=t,o^1:(t<6)?d^=t-2,9-t:6],P+=m[d];printf("%d",n+1);}

```

Takes input in first argument, prints result. Requires that input contains at least 1 newline (so if there's only 1 row, it must end with a newline)

Example usage:

```
./backflip '....
';

```

Breakdown:

```
d,                                          // Direction
n,                                          // Step counter
t,
m[4]={1,-1};                                // Movement offsets
char*w="><^V/\\.",                          // Command lookup
*P;                                         // Cursor location
main(o,v)char**v;{
    for(P=v[1],                             // Begin at 0,0
        m[2]=-(m[3]=strchr(P,10)-P+1);      // Find width of grid
        P>=v[1]&&P<strchr(v[1],0)&&*P^10;   // While inside grid:
        ++n)                                //  Increment step
        *P=w[                               //  Update the current cell
            ((o=d,t=strchr(w,*P)-w)         //  (store current direction & command)
              <4)?d=t,o^1:                  //   If <>^V, write backflip & set dir
            (t<6)?d^=t-2,9-t:               //   If / or \, write flip & bounce
            6],                             //   If ., write unchanged & continue
        P+=m[d];                            //  Move
    printf("%d",n+1);                       // Print result
}

```
> 1 votes

---
Tags: code-golf, grid, integer, interpreter
---