title: Minus, Plus, Times, Exponentiation?

text:
# Question
Title: Minus, Plus, Times, Exponentiation?
This is a CMC (chat mini challenge) that I posted in our chatroom, The Ninteenth Byte, a bit ago.

### The Challenge

Given a positive integer `x`, depending on the last 2 bits of `x`, do the following:

```
x & 3 == 0: 0
x & 3 == 1: x + x
x & 3 == 2: x * x
x & 3 == 3: x ^ x (exponentiation)

```

### Input/Output

```
Single Integer -> Single Integer

```

A trailing newline is permitted in the output. No other whitespace is permitted.

### Testcases

```
input       output
    1            2
    2            4
    3           27
    4            0
    5           10
    6           36
    7       823543
    8            0
    9           18
   10          100
   11 285311670611
   12            0

```

This is a challenge, so the shortest code wins!

# Answer
> 13 votes
# Jelly, 8 bytes

```
ị“+×*_”v

```

Try it online!

## How it works

Firstly, notice that `x&3` is equivalent to `x%4`, where `%` is modulo. Then, since Jelly uses modular indexing (`a[n] == a[n+len(a)]`), so we don't even need to deal with that.

Then:

* If `x%4==0`, return `x_x` (subtraction) (for consistency);
* If `x%4==1`, return `x+x`;
* If `x%4==2`, return `x×x`(multiplication);
* If `x%4==3`, return `x*x`(exponentiation)

Note that Jelly uses 1-indexing, so the subtraction `"_"` is moved to the end.

```
ị“+×*_”v  example input: 10
ị“+×*_”   index 10 of the string “+×*_”, which gives "×"
       v  evaluate the above as a Jelly expression,
          with 10 as the argument, meaning "10×" is the
          expression evaluated. The dyad "×" takes the
          second argument from the only argument, effectively
          performing the function to itself.

```

# Answer
> 13 votes
# Python, 30 bytes

```
lambda x:[0,x+x,x*x,x**x][x%4]

```

Try it online!

# Answer
> 9 votes
# CJam, 12 bytes

```
ri__"-+*#"=~

```

Try it online!

### Explanation

```
ri            e# Read an int from input (call it x).
  __          e# Duplicate x twice.
    "-+*#"    e# Push this string.
          =   e# Get the character from the string at index x (mod 4).
           ~  e# Eval that char, using the two copies of x from before.

```

Runs one of the following operations depending on `x`'s value mod 4 (mod 4 is equivalent to AND 3).

```
0:  -  Subtraction
1:  +  Addition
2:  *  Multiplication
3:  #  Exponentiation

```

# Answer
> 6 votes
## Mathematica 25 Bytes

```
0[2#,#*#,#^#][[#~Mod~4]]&

```

Saved 4 Bytes thanks to @MartinEnder

# Answer
> 4 votes
# Pyth, 8 bytes

```
.v@"0y*^

```

Interpreter

# Answer
> 4 votes
# Ruby, 26 bytes

```
->x{x*[0,2,x,x**~-x][x%4]}

```

Try it online!

# Answer
> 3 votes
# PHP, 37 Bytes

```
<?=[0,2*$x=$argn,$x*$x,$x**$x][$x&3];

```

Online Version

# PHP, 47 Bytes

```
<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);

```

Online Version

BC Math functions

# Answer
> 3 votes
## Haskell, ~~28~~ 27 bytes

```
f x=cycle[0,x+x,x*x,x^x]!!x

```

Try it online!

Edit: Thanks to @Ørjan Johansen for 1 byte.

# Answer
> 2 votes
# JavaScript, 24 bytes

```
a=>[0,a+a,a*a,a**a][a%4]

```

Try it online!

# Answer
> 2 votes
# Java 7, 75 bytes

```
long c(int n){int x=n%4;return x<1?0:x<2?n+n:x<3?n*n:(long)Math.pow(n,n);}

```

Even though it is valid according to the rules, `long` is 64-bits, so it fails for the exponentiation test cases of `19^19` and above. To fix that we can use a `BigDecimal` approach:

**~~148~~ 146 bytes**

```
import java.math.*;BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}

```

**Explanation (of BigDecimal approach):**

```
import java.math.*;                // Import required for BigDecimal
BigDecimal c(int n){               // Method with integer parameter and BigDecimal return-type
  int x=n%4;                       //  Input modulo-4
  BigDecimal m=new BigDecimal(n);  //  Convert input integer to BigDecimal
  return x<1?                      //  If the input mod-4 is 0:
    m.subtract(m)                  //   Return input - input (shorter than BigDecimal.ZERO)
   :x<2?                           //  Else if the input mod-4 is 1:
    m.add(m)                       //   Return input + input
   :x<3?                           //  Else if the input mod-4 is 2:
    m.multiply(m)                  //   Return input * input
   :                               //  Else:
    m.pow(n);                      //   Return input ^ input
}                                  // End of method

```

**Test code:**

Try it here.

```
import java.math.*;
class M{
  static BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}

  public static void main(String[] a){
    for (int i = 1; i <= 25; i++) {
      System.out.print(c(i) + "; ");
    }
  }
}

```

**Output:**

```
2; 4; 27; 0; 10; 36; 823543; 0; 18; 100; 285311670611; 0; 26; 196; 437893890380859375; 0; 34; 324; 1978419655660313589123979; 0; 42; 484; 20880467999847912034355032910567; 0; 50;

```

# Answer
> 2 votes
# C, 63 or 62 bytes

```
#include<math.h>
f(x){return(int[]){0,x+x,x*x,pow(x,x)}[x&3];}

```

-1 byte if macros are allowed, assuming `x` is not an expression like `3+5` (since that'd mess up the precedence):

```
#include<math.h>
#define f(x)(int[]){0,x+x,x*x,pow(x,x)}[x&3]

```

# Answer
> 2 votes
# C#, 39 bytes

```
x=>new[]{0,2,x,Math.Pow(x,x-1)}[x&3]*x;

```

### Explanation

Observe that:

(x-x, x+x, x\*x, x^x) == (0, 2, x, x^(x-1)) * x

The solution creates an array, indexes into it and then multiplies the result by `x`:

```
x => new[] { 0, 2, x, Math.Pow(x,x-1) }[x&3] * x;

```

### Alternative versions:

```
x=>new[]{0,x+x,x*x,Math.Pow(x,x)}[x%4];

```

(39B, all multiplication done in the array, `x%4` replaces `x&3`)

```
x=>x%4<2?x%2*2*x:Math.Pow(x,x%4<3?2:x);

```

(39B, same as @MetaColon's answer but `x%2*2*x` replacing `x*x%4<1?0:2`)

# Answer
> 2 votes
## x86 Assembler, Intel syntax, 192 bytes

```
.data
f dw @q,@w,@e,@r
.code
mov ecx, eax
and ecx, 3
mov edx,dword ptr f[ecx*4]
call [edx]
ret
q:
xor eax,eax
ret
w:
add eax,eax
ret
e:
mul eax,eax
ret
r:
mov ecx,eax
t:
mul eax,eax
loop t
ret

```

Example pretends for fastest working speed. Is is a program or program part, which uses fastcall convention. It assumes input variable `x` in register `eax`, and returns result also in `eax`. Basic idea is stay away from using conditional jumps, as in some examples here. Also, it is not to evaluate everything (as in C example with arrays) but to use array of pointers to functons and make faster unconditional jumps (jmp/call) as an optimized "C language switch()-case.." analog. This technique could be also useful in kinds of finita automata - like processor emulators, executors and so on.

Upd: for x64 use "r" in register names, instead of "e" (e.g. `rax` instead of `eax`, `rcx` instead of `ecx`). Size will not be changed, and it will use 64-bit unsigned words.

# Answer
> 1 votes
# Actually, 12 bytes

```
;;3&"-+*ⁿ"Eƒ

```

Try it online!

Explanation:

```
;;3&"-+*ⁿ"Eƒ
;;            two copies of input (so 3 total)
  3&          bitwise AND with 3
    "-+*ⁿ"E   index into this string
           ƒ  call the respective function

```

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
Ð"-+*m"è.V

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 1 votes
# , 14 bytes

```
4&|{0,+:,*:,^~

```

Try it online!

# Answer
> 1 votes
# Oasis, 25 bytes

```
mn4%3Q*nkn4%2Q*nxn4%1Q*++

```

Try it online!

## How it works

Notice that `x&3` is equivalent to `x%4`, where `%` is modulo.

```
mn4%3Q*nkn4%2Q*nxn4%1Q*++  input is n
mn4%3Q*                    (n**n)*((n%4)==3)
       nkn4%2Q*            (n**2)*((n%4)==2)
               nxn4%1Q*    (n*2)*((n%4)==1)
                       +   add the above two
                        +  add the above two

```

Oasis is a stack-based language where every character is a command.

# Answer
> 1 votes
# C#, 42 Bytes

```
x=>x%4<2?x*x%4<1?0:2:Math.Pow(x,x%4<3?2:x)

```

Actually it's normal C#, but as you can't run it as a whole program and you have to type it into the interactive, I guess you may call it *C# interactive*.

**Explanation**:

```
x => (x % 4) < 2     //If the bits are smaller than 2 (1 or 0)
? x *           //multiply x with
    (x % 4) < 1 //if the bits are 0
    ? 0         //0 (results in 0)
    : 2         //or else with 2 (results in 2*x or x+x)
: Math.Pow(x,   //otherwise power x by
    (x % 4) < 3 //if the bits are 2
    ? 2         //2 (results in x^2 or x*x)
    : x);       //or else x (results in x^x)

```

I can't tell wether it's the shortest variant, any suggestions are appreciated.

# Answer
> 1 votes
# Cubix, 29 bytes

```
.;.O+@.UOI:4%!^s;((?u.^P;<^*;

```

Try it online!

Explanation will be added soon...

# Answer
> 1 votes
# PHP, 36 bytes

```
<?=[0,2,$x=$argn,$x**~-$x][$x&3]*$x;

```

# Answer
> 1 votes
# dc, 27

I've never had the occasion to use arrays in dc before:

```
[+]1:r[*]2:r[^]3:r?dd4%;rxp

```

Try it online.

# Answer
> 1 votes
## C, 115 bytes

```
#include<math.h>
#define D(K,L)K(x){return L;}
D(q,0)D(w,x+x)D(e,x*x)D(r,pow(x,x))(*g[])()={q,w,e,r};D(f,g[x%4](x))

```

Example is a function `int f(int x)`

It pretends for fastest working speed as it keeps CPU away from using conditional jumps. And this is only correct speed-optimisation way for this task. Also, it tries not to evaluate everything, as in array C example `return(int[]){0,x+x,x*x,pow(x,x)}[x%4];` But but to wisely use array of pointers to functons, in order to make much faster unconditional jumps (jmp/call) with much faster address arithmetics, as an optimized version of "switch()-case..". This technique could be also useful in several kinds of finita automata - like processor emulators, executors, command stream parsers, and so on - where speed matters and code like `switch(x%4) case(0):... case(1):...` is unsuitable because it produces multiple cmp/jnz instructions; and these are costly operations for CPU

Simpliest and shortest test program (in default conditions) for the case will be as follows:

```
D(main,f(x))

```

It will add just 12 bytes of payload and will total our size to 127 bytes;

But you should better tell the linker to use `f` function as an entry point, instead of `main`. That is the way, if we aim to get fastest possible working binary for this task from shortest code ;-) This happens because C library adds extra init/shutdown code before calling your main() function.

Code compiles on MSVS Community 2015 without any tricks and issues and produces correct results. I haven't tested it with gcc, but i'm sure it will work fine as well.

# Answer
> 1 votes
# Groovy, 26 bytes

```
{x->[0,x+x,x*x,x**x][x%4]}

```

Try it online!

# Answer
> 1 votes
# R, ~~47~~ 42 bytes

```
x=scan();c(`-`,`+`,`*`,`^`)[[x%%4+1]](x,x)

```

Applies the function `-`, `+`, `*`, or `^` based on the modulus of `x` to `x` and `x`.

`-` is the only (somewhat) smart thing, since `x-x` is always 0.

# R, 33 bytes

```
pryr::f(c(0,2*x,x^2,x^x)[x%%4+1])

```

Same method as other people use. Though it is shorter, I don't like it nearly as much.

# Answer
> 0 votes
# Pyth, 12 bytes

```
.vjd,+@"-+*^

```

Try it online!

## How it works

Firstly, notice that `x&3` is equivalent to `x%4`, where `%` is modulo. Then, since Pyth uses modular indexing (`a[n] == a[n+len(a)]`), so we don't even need to deal with that.

Then:

* If `x%4==0`, return `x-x` (for consistency);
* If `x%4==1`, return `x+x`;
* If `x%4==2`, return `x*x`;
* If `x%4==3`, return `x^x`.

---

```
.vjd,+@"-+*^  example input: 10
      @"-+*^  "-+*^"[10], which is "*"
     +        "*10"
    ,         ["*10","10"]
  jd          "*10 10"
.v            evaluate as Pyth expression
              (Pyth uses Polish notation)

```

More about Polish notation: Wikipedia (too bad if you are in Turkey).

# Answer
> 0 votes
# Japt, 13 bytes

```
Ov"^+*p"gU +U

```

Try it online!

This uses the same method as the other eval answers, except the program `-U` just negates `U`, so we use `^` (bitwise XOR) instead.

# Answer
> 0 votes
## Vim, 50 bytes

```
y$o^R"A-+*^^V^[0^R"lx0"_Dp^[0D@"kJ0"ad$:r!echo ^R"^R0|bc^<Enter>

```

Here, `^V` represents a `Ctrl+V`, `^R` represents `Ctrl-R` and `^[` represents the `esc` key

Works by first building up the expression and then letting `bc` evaluate it. Expects the input on the first line in an otherwise empty buffer.

Explanation:

```
y$o^R"                                                          Copies the input into register " and pastes it on the second line
      A-+*^^V^[0^R"lx0"_Dp                                      Enters that text after the input on the second line
                          ^[0D@"                                Executes the second line as a Vim command.
                                                                For example, if the input is 12, the second line would be 12A-+*^^[012lx0"_Dp, which means:
                                                                  12A-+*^^[           Insert the text -+*^ 12 times
                                                                           012lx0"_Dp Go 12 chars to the right and remove everything except for that.
                                                                If effect, this basically just selects the appropriate operation.
                                kJ0"ad$                         Put the operator after the number, cut it into register a
                                       :r!                      Execute the following shell command and put the result into the buffer:
                                          echo ^R"^R0|bc<Enter> The shell command "echo [contents of register a][contents of registers 0]|bc. As said above, register a contains the input and the operator, and register 0 contains the input. The <enter> then executes this command.

```

# Answer
> 0 votes
# Pyth, 9 bytes

```
@[0yQ*QQ^

```

Test suite

Nothing fancy going on here, just calculate the four values, and select one with modular indexing.

```
@[0yQ*QQ^
@[0yQ*QQ^QQ)Q    Implicit variable introduction
@           Q    Modularly index into the following list
 [0        )     0
   yQ            Q*2
     *QQ         Q*Q
        ^QQ      Q^Q

```

# Answer
> 0 votes
## Batch, 135 bytes

```
@set/an=%1*2^&6
@goto %n%
:6
@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@goto 0
:4
@set n=%1
:2
@set/an*=%1
:0
@echo %n%

```

I was hoping to create the exponentiation by building up and evaluating a string of the form `[0+...+0, 2+...+2, x+...+x, x*...*x]` depending on the last two bits of `x` but unfortunately the code to select the operation took too long to express because I couldn't use `*` as a `for` parameter, but I was at least able to use some fall-though trickery to golf away some bytes.

# Answer
> 0 votes
# Retina, 87 bytes

```
.+
$*1;$&$*
;((1111)*)(1?)$
;$3$3
1(?=1.*;((1111)*111)$)
$1;
+`\G1(?=.*;(1*))|;1*$
$1
1

```

Try it online! (Link includes test suite.)

Explanation: The first two lines convert the input into unary and duplicate it (so we now have `x;x`). The next two lines look for an `x&3` of either `0` or `1` and change `x;x` into `x;0` or `x;2` appropriately. The next two lines look for `x&3==3` and change `x;x` into `x;x;x;...;x;1;x` (`x` `x`s). This means that we have either `x;0`, `x;2`, `x;x`, or `x;...;x` and it remains to multiply everything together and convert back to decimal. (The multiplication code is based on that in the Retina wiki but amended to handle multiplication by zero.)

# Answer
> 0 votes
## vba, 101

```
Function x(f)
Select Case f Mod 4
Case 0:x=0
Case 1:x=f+f
Case 2:x=f*f
Case 3:x=f ^f
End Select
End Function

```

# Answer
> 0 votes
# Dyvil, 24 Bytes

```
x=>[0,x+x,x*x,x**x][x&3]

```

**Usage**:

```
let f: int->int = x=>[0,x+x,x*x,x**x][x&3]
print f(10) // => 100

```

**Explanation**:

The code creates a lambda expression that takes and returns a 32-bit integer. The body stores the result of all calculations in an array and retrieves the result from the index given by the last 2 bits of `x`.

# Answer
> 0 votes
# Swift, ~~105~~ ~~68~~ 67 bytes

Here is the body of the function:

```
i in let a=i%4;return [0,i+i,i*i,Int(pow(Double(i),Double(i)))][a]

```

Here is the full implementation:

```
import Foundation;var e:(Int)->Int={i in let a=i%4;return [0,i+i,i*i,Int(pow(Double(i),Double(i)))][a]}

```

Try it here

# Answer
> 0 votes
# TI-BASIC, ~~27~~, 23 bytes

```
:Prompt X          //Get input as X, 3 bytes
:{2X,X²,X^X,0      //Implicitly store the list {2X,X²,X^X,0} to Ans, 16 bytes
:Ans(remainder(X,4 //Compute X&3 (as X%4), get that element of the list, and implicitly print 8 bytes

```

TI-BASIC doesn't have bitwise operators, so I used the modulus operator (`remainder(`) instead.

# Answer
> 0 votes
# oK, 20 bytes

```
{*/(."-+*#"4!x).x,x}

```

Try it online!

# Answer
> 0 votes
# C (gcc), 59 bytes

```
#include<math.h>
h(x){return x&2?pow(x,x&1?x:2):(x&1)*2*x;}

```

Test and results. It overflows at 11.

```
main()
{int i;
 for(i=0;i<20;++i)
       printf("%u %u\n", i, h(i));
}

0 0
1 2
2 4
3 27
4 0
5 10
6 36
7 823543
8 0
9 18
10 100
11 1843829075
12 0
13 26
14 196
15 1500973039
16 0
17 34
18 324
19 0

```

Ideone

Try it online!

# Answer
> 0 votes
# Pure Bash, 35

```
a=(- + * **)
echo $[$1${a[$1%4]}$1]

```

Try it online.

# Answer
> 0 votes
# Axiom, ~~59~~ 33 bytes

```
h(x)==[0,x+x,x*x,x^x].(1+x rem 4)

```

traslate in Axiom the answer of Mego... this is the old 59 bytes

```
h(x)==(x quo 2 rem 2=1=>(x rem 2=0=>x^2;x^x);(x rem 2)*2*x)

```

results

```
(24) -> for i in 0..30 repeat output [i,h(i)]
   [0,0]
   [1,2]
   [2,4]
   [3,27]
   [4,0]
   [5,10]
   [6,36]
   [7,823543]
   [8,0]
   [9,18]
   [10,100]
   [11,285311670611]
   [12,0]
   [13,26]
   [14,196]
   [15,437893890380859375]
   [16,0]
   [17,34]
   [18,324]
   [19,1978419655660313589123979]
   [20,0]
   [21,42]
   [22,484]
   [23,20880467999847912034355032910567]
   [24,0]
   [25,50]
   [26,676]
   [27,443426488243037769948249630619149892803]
   [28,0]

```

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


# Question
Title: The strange attraction of the logistic map
The purpose of the challenge is to approximately plot the attractor of the logistic map as a function of its parameter *r* (also called bifurcation diagram), or a subregion of it. The appearance of the graph can be seen in the following image from Wikipedia:

## Background

The **logistic map** is a mathematical function that takes an input *xk* and maps it to an output *xk+1* defined as

*xk+1* = *r* *xk* (1−*xk*)

where *r* is the **parameter** of the map, assumed to lie in the interval \[0, 4\].

Given *r* in \[0,4\], and an initial value *x*0 in the interval \[0,1\], it is interesting to **repeatedly apply** the function for a large number *N* of iterations, producing a final value *xN*. Note that *xN* will necessarily lie in \[0,1\] too.

As an example, consider *r* = 3.2, *N* = 1000. The initial value *x*0 = 0.01 gives *x*1000 = 0.5130. For *x*0 = 0.02 the result is *x*0 = 0.7995. For *any* other initial values *x*0 the final values *x*1000 are extremely close to either 0.5130 or 0.7995. This is seen in the graph as the height of the two lines at horizontal position *r* = 3.2.

This does *not* mean that for *r* = 3.2 each sequence converges to one of those two values. In fact, for the two initial values considered above, the sequences are (note the oscillating behaviour):

*x*0 = 0.01, ..., *x*1000 = 0.5130, *x*1001 = 0.7995, *x*1002 = 0.5130, ...
*x*0 = 0.02, ..., *x*1000 = 0.7995, *x*1001 = 0.5130, *x*1002 = 0.7995, ...

What *is* true is that for sufficiently large *N*, and for almost all initial values *x*0, the term *xN* will be close to one of the elements of the set {0.5130, 0.7995}. This set is called the **attractor** for this specific *r*.

For other values of the parameter *r* the size of the atractor set, or its elements, will change. The graph plots the elements in the attractor for each *r*.

The attractor for a specific *r* can be **estimated** by

1. testing a wide range of initial values *x*0;
2. letting the system evolve for a large number *N* of iterations; and
3. taking note of the final values *xN* that are obtained.

## The challenge

### Inputs

* ***N***: number of iterations.
* ***r*1**, ***r*2** and ***s***. These define the set *R* of values of *r*, namely *R* = {*r*1, *r*1 \+ *s*, *r*1 \+ 2 *s*, ..., *r*2}.

### Procedure

The set *X* of initial values *x*0 is fixed: *X* = {0.01, 0.02, ..., 0,99}. Optionally, 0 and 1 may also be included in *X*.

For each *r* in *R* and each *x*0 in *X*, iterate the logistic map *N* times to produce *xN*. Record the obtained tuples (*r*, *xN*).

### Output

Plot each tuple (*r*, *xN*) as a point in the plane with *r* as horizontal axis and *xN* as vertical axis. Output should be graphic (not ASCII art).

## Additional rules

* The indicated procedure defines the required result, but is not enforced. Any other procedure that procudes the same set of (*r*, *xN*) tuples can be used.
* Input is flexible as usual.
* Floating point errors won't be held against the answerer.
* Graphic output is required, in any of the accepted formats. In particular, output may be displayed on screen, or a graphics file may be produced, or an array of RGB values may be output. If outputting a file or an array, please post an example of what it looks like when displayed.
* Graphics may be vector or raster. For raster graphics, the size of the image should be at least 400×400 pixels.
* Each point should be shown as a single pixel, or as a mark with size of the order of one pixel (otherwise the graph quickly gets cluttered).
* Axis range should be \[0,4\] for *r* (horizontal axis) and \[0,1\] for *xN* (vertical axis); or it may be smaller as long as it includes all obtained points.
* Axis scales are arbitrary. In particular, the scale need not be the same for both axes.
* Grid lines, axis labels, colors and similar elements are acceptable, but not required.
* Shortest code in bytes wins.

## Test cases

Click on each image for a high-resolution version.

`N = 1000; r1 = 2.4; r2 = 4; s = 0.001;`

`N = 2000; r1 = 3.4; r2 = 3.8; s = 0.0002;`

`N = 10000; r1 = 3.56; r2 = 3.59; s = 0.00002;`

## Acknowledgment

Thanks to @FryAmTheEggman and @AndrasDeak for their helpful comments while the challenge was in the sandbox.

# Answer
> 13 votes
# MATL, ~~32~~ ~~30~~ ~~28~~ 27 bytes

*4 bytes saved thanks to @Luis*

```
3$:0:.01:1!i:"tU-y*]'.'3$XG

```

The input format is `r1`, `s`, `r2`, and `N`

Try it at **MATL Online**

**Explanation**

```
        % Implicitly grab the first three inputs
3$:     % Take these three inputs and create the array [r1, r1+s, ...]
0:.01:1 % [0, 0.01, 0.02, ... 1]
!       % Transpose this array
i       % Implicitly grab the input, N
:"      % For each iteration
  tU    % Duplicate and square the X matrix
  -     % Subtract from the X matrix (X - X^2) == x * (1 - x)
  y     % Make a copy of R array
  *     % Multiply the R array by the (X - X^2) matrix to yield the new X matrix
]       % End of for loop
'.'    % Push the string literal '.' to the stack (specifies that we want
        % dots as markers)
3$XG    % Call the 3-input version of PLOT to create the dot plot

```

# Answer
> 8 votes
# Mathematica, 65 bytes

```
Graphics@Table[Point@{r,Nest[r#(1-#)&,x,#]},{x,0,1,.01},{r,##2}]&

```

Pure function taking the arguments N, r1, r2, s in that order. `Nest[r#(1-#)&,x,N]` iterates the logistic function `r#(1-#)&` a total of `N` times starting at `x`; here the first argument to the function (`#`) is the `N` in question; `Point@{r,...}` produces a `Point` that `Graphics` will be happy to plot. `Table[...,{x,0,1,.01},{r,##2}]` creates a whole bunch of these points, with the `x` value running from `0` to `1` in increments of `.01`; the `##2` in `{r,##2}` denotes all of the original function arguments starting from the second one, and so `{r,##2}` expands to `{r,r1,r2,s}` which correctly sets the range and increment for `r`.

Sample output, on the second test case: the input

```
Graphics@Table[Point@{r,Nest[r#(1-#)&,x,#]},{x,0,1,.01},{r,##2}]&[2000,3.4,3.8,0.0002]

```

yields the graphics below.

# Answer
> 5 votes
# Mathematica, 65 bytes

I used some of Greg Martin's tricks and this is my version without using Graphics

```
ListPlot@Table[{r,NestList[#(1-#)r&,.5,#][[-i]]},{i,99},{r,##2}]&

```

**input**

> \[1000, 2.4, 4, 0.001\]

**output**

**input**

> \[2000, 3.4, 3.8, 0.0002\]

**output**

# Answer
> 2 votes
# TI-Basic, 85 bytes

```
Prompt P,Q,S,N
P→Xmin:Q→Xmax
0→Ymin:1→Ymax
For(W,.01,1,.01
For(R,P,Q,S
W→X
For(U,1,N
R*X*(1-X→X
End
Pt-On(R,X
End
End

```

A complete TI-Basic program which takes input in the order `r1,r2,s,N` and then shows the output in real time on the graph screen. Note that this tends to be *incredibly slow*.

Here is an incomplete sample output generated after about 2.5 hours for the input `3,4,0.01,100`:

# Answer
> 1 votes
# ProcessingJS, ~~125~~ ~~123~~ 120 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

```
var f(n,q,r,s){size(4e3,1e3);for(i=0;i<1;i+=.01)for(p=q;p<=r;p+=s){x=i;for(j=0;j<n;j++)x*=p-p*x;point(p*1e3,1e3-x*1e3)}}

```

Try it online! Call using `f(N, r_1, r_2, s);`

# Answer
> 1 votes
# GEL, 158 bytes

```
`(N,r,t,s)=(LinePlotWindow=[r,t,0,1];for i=r to t by s do(p=.;for w=0to 1by 0.01do(x=w;for a=0to N do(x=i*x*(1-x););p=[p;q=[i,x]];);LinePlotDrawPoints(p);););

```

It may not be the shortest, but it draws in real time, although it can be incredibly slow with huge inputs. Anyways, this is an anonymous function which takes input in the format `(N,r1,r2,s)` and outputs the plot in a new window. Note that this *must* be run with the GNOME version of Genius.

# Answer
> 1 votes
# R, ~~159~~ 147 bytes

```
pryr::f({plot(NA,xlim=c(a,b),ylim=0:1);q=function(r,n,x=1:99/100){for(i in 1:n)x=r*x*(1-x);x};for(i in seq(a,b,s))points(rep(i,99),q(i,n),cex=.1)})

```

Which productes the function

```
function (a, b, n, s)
{
    plot(NA, xlim = c(a, b), ylim = 0:1)
    q = function(r, n, x = 1:99/100) {
        for (i in 1:n) x = r * x * (1 - x)
        x
    }
    for (i in seq(a, b, s)) points(rep(i, 99), q(i, n), cex = 0.1)
}

```

`plot(NA,...)` creates an empty canvas that has the correct dimensions. `q` is the function that does the iterating. It takes a value of `r`, and then does `n` iterations for all starting points between `0.01` and `0.99`. It then returns the resulting vector.

The for-loop applies the function `q` to the sequence `a` to `b` with step `s`. Instead of returning the values, it adds them as points to the plot. If the attraction point is one value, all the points would just overlap and show as one point. `cex=.1` is a necessary addition to make the points as small as possible.

---
Tags: code-golf, math, number, graphical-output, fractal
---


title: What type are my suffixes?

text:
# Question
Title: What type are my suffixes?
## Intro

So I've been wasting my time again researching suffix sorting algorithms, evaluating new ideas by hand and in code. But I always struggle to remember the type of my suffixes! Can you tell me which type my suffixes are?

## Left-most what?

A lot of suffix sorting algorithms (SAIS, KA, my own daware) group suffixes into different types in order to sort them. There are two basic types: **S-type** and **L-type** suffixes. *S-type* suffixes are suffixes that are lexicographically less (**S**maller) than the following suffix and *L-type* if it is lexicographically greater (**L**arger). A *left-most S-type* (*LMS-type*) is just that: A *S-type* suffix that is preceeded by a *L-type* suffix.

The special thing about these *LMS-type* suffixes is that once we sorted them we can sorted all the other suffixes in linear time ! Isn't that awesome?

## The challenge

Given a string assume it is terminated by a special character that is less than any other character in that string (e.g. smaller than even the null byte). Output a type corrosponding char for each suffix.

You can freely choose which char to use for which type but I'd prefer `L, S and *` for `L-, S- and LMS-type` as long as they are all printable (`0x20 - 0x7E`).

## Example

Given the string `mmiissiissiippi` output (when using `L, S and *`):

```
 LL*SLL*SLL*SLLL

```

For example the first `L` is due to the fact that `mmiissiissiippi$` is lexicographically greater than `miissiissiippi$` (the `$` represents the added minimal character):

```
L - mmiissiissiippi$ > miissiissiippi$
L - miissiissiippi$  > iissiissiippi$
* - iissiissiippi$   < issiissiippi     and preceeded by L
S - issiissiippi$    < ssiissiippi$
L - ssiissiippi$     > siissiippi$
L - siissiippi$      > iissiippi$
* - iissiippi$       < issiippi$        and preceeded by L
S - issiippi$        < ssiippi$
L - ssiippi$         > siippi$
L - siippi$          > iippi$
* - iippi$           < ippi$            and preceeded by L
S - ippi$            < ppi$
L - ppi$             > pi$
L - pi$              > i$
L - i$               > $

```

Some more examples:

```
"hello world" -> "L*SSL*L*LLL"
"Hello World" -> "SSSSL*SSLLL"
"53Ab§%5qS"   -> "L*SSL*SLL"

```

## Goal

I'm not here to annoy Peter Cordes (I'm so gonna do this on stackoverflow sometime); I'm just very lazy so this is of course ! The shortest answer in bytes wins.

---

Edit: The order of the chars is given by their byte value. That means compare should be like C's `strcmp`.

Edit2: Like stated in the comments output should be a single character for each input character. While I assumed that would be understood as "return a string" it seems at least 1 answer returns a list of single characters. In order to not invalidate the existing answers I will allow you to return a list of single characters (or integers which when printed result in only 1 char).

---

### Tips for linear time:

1. It can be done in 2 parallel forward iterations or in a single backward iteration.
2. The state of each suffix depends only on the first 2 chars and the type of the second.
3. Scanning the input in reverse direction you can determine L or S like this: `$t=$c<=>$d?:$t` (PHP 7), where `$c` is the current char `$d` the previous and `$t` the previous type.
4. See my PHP answer. Tomorrow I will award the bounty.

# Answer
# Haskell, 64 53 48 42 bytes

```
(0!)
k!(x:y)|x:y>y=1:2!y|2>1=k:0!y
_![]=[]

```

Try it online!

Ungolfed, with `Char` instead of `Int`:

```
suffixes :: String -> String
suffixes = go 'S'
 where
   go :: Char -> String -> String
   go _ "" = ""
   go lorstar s | s > tail s = 'L' : go '*' (tail s)
                | otherwise  = lorstar : go 'S' (tail s)

```
> 7 votes

# Answer
# Jelly,  ~~25 23 21 20~~  19 bytes

```
Ṛ;\UỤỤIṠµI2n×ịØDṚ;0

```

A full program that prints the list of characters, using:

```
L: 0
S: 8
*: 9

```

(As a link it returns a list where all items are characters except the last one, which is a zero.)

**Try it online!** or see the test suite (with conversion to `LS*`).

### How?

```
Ṛ;\UỤỤIṠµI2n×ịØDṚ;0 - Link: list of characters, s  e.g. "cast"
Ṛ                   - reverse                           "tsac"
  \                 - cumulative reduce by:
 ;                  -   concatenation                   ["t","ts","tsa","tsac"]
   U                - upend (reverse each)              ["t","st","ast","cast"] (suffixes)
    Ụ               - sort indexes by value             [3,4,2,1] (lexicographical order)
     Ụ              - sort indexes by value             [4,3,1,2] (order of that)
      I             - incremental differences           [-1,-2,1] (change)
       Ṡ            - sign                              [-1,-1,1] (comparisons)
        µ           - monadic chain separation, call that x
         I          - incremental differences           [0,2] (only (-1,1) produce 2s)
          2         - literal 2                         2
           n        - not equal?                        [1,0] (indexes of * will be 0)
            ×       - multiply by x (vectorises)        [-1,0,1] (make indexes of *s 0)
              ØD    - decimal yield                     "0123456789"
             ị      - index into (1-indexed & modular)  ['8','9','0']
                Ṛ   - reverse                           ['0','9','8']
                 ;0 - concatenate a zero                ['0','9','8',0]
                    - implicit print                     0980
                    -                              i.e. "L*SL"

```
> 6 votes

# Answer
# Python 3, ~~92~~ ~~87~~ ~~74~~ ~~69~~ 65 bytes

```
s=input()
c=1
while s:d=s<s[1:];print(d+(c<d),end='');s=s[1:];c=d

```

Uses `0` for `L`, `1` for `S`, and `2` for `*`. Wrap the input string in quote characters; I believe this is allowed by convention.

Try it online!

Example use:

```
mmiissiissiippi
002100210021000

```

*saved 5 bytes thanks to Leaky Nun, 4 bytes thanks to ovs*
> 3 votes

# Answer
# JavaScript (ES6), ~~51~~ 45 bytes

```
f=(c,d)=>c&&(d<(d=c<(c=c.slice(1))))+d+f(c,d)

```

*Saved 6 bytes thanks to @Neil.*

A recursive solution to the exercise.

```
f=(c,d)=>c&&(d<(d=c<(c=c.slice(1))))+d+f(c,d)

console.log(f('mmiissiissiippi')); //LL*SLL*SLL*SLLL   002100210021000
console.log(f('hello world'));     //L*SSL*L*LLL       02110202000
console.log(f('Hello World'));     //SSSSL*SSLLL       11110211000
console.log(f('53Ab§%5qS'));       //L*SSL*SLL         021102100
```
> 3 votes

# Answer
## JavaScript (ES6), 52 bytes

```
f=
s=>s.replace(/./g,_=>(c<(c=s<(s=s.slice(1))))+c,c=1)
```

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

Port of @L3viathan's answer.
> 2 votes

# Answer
# PHP, 70 bytes

L = 1, S = 0 , * = 2

Multibyte Support is needed for the last Testcase with the `§` +3 Bytes `mb_substr` instead `substr`

```
for(;$s=&$argn;$s=$u)$r.=$l=($l&1)+(1&$l^($s>$u=substr($s,1)));echo$r;

```

Try it online!

# PHP, 71 bytes

L = 1, S = 0 , * = 2

```
for(;$s=&$argn;$s=$u)$r.=+($s>$u=substr($s,1));echo strtr($r,[10=>12]);

```

Try it online!

# PHP, 74 bytes

```
for(;$s=&$argn;$s=$u)$r.=SL[$s>$u=substr($s,1)];echo strtr($r,[LS=>"L*"]);

```

Try it online!
> 1 votes

# Answer
# Haskell, ~~77~~ 75 bytes, linear time

```
f(a:b:c)|let g"L"|a<b="SL";g"S"|a>b="L*";g d=d++d;d:e=f$b:c=g[d]++e
f _="L"

```

Try it online!

### How it works

This uses recursion, stripping off one character at a time from the beginning of the string. (The Haskell string type is a singly-linked list of characters, so each of these steps is constant-time.)

* For a string *abc* where *a* and *b* are single characters and *c* is any (possibly empty) string,
    + *f*(*abc*) = SL*e*, if *f*(*bc*) = L*e* and *a* \< *b*;
    + *f*(*abc*) = L\**e*, if *f*(*bc*) = S*e* and *a* \> *b*;
    + *f*(*abc*) = LL*e*, if *f*(*bc*) = L*e* and *a**b*;
    + *f*(*abc*) = SS*e*, if *f*(*bc*) = S*e* and *a**b*.
* For a single-character string *a*, *f*(*a*) = L.
> 1 votes

# Answer
# C (clang), 88 bytes

```
S(S,A,I)char*S,*A;{for(;strlen(S);A=S,S++,printf("%c",I=strcmp(A,S)>0?76:I==76?42:83));}

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~65~~ 55 bytes

Recursive version, based on L3viathan's answer, using `012` as `LS*`:

```
def g(s,d=2):c=s<s[1:];return s and`c+(d<c)`+g(s[1:],c)

```

Try it online!

## Python 3, ~~65~~ 59 bytes

Recursive solution using `L`, `S`, and `*`:

```
f=lambda s:s and('LS'[s<s[1:]]+f(s[1:])).replace('LS','L*')

```

Runs through the string from the front, and replaces all instances of `LS`with `L*`

Try it online!
> 1 votes

# Answer
## PHP, 82 byte, linear time

```
for($a=$argn;a&$c=$a[$i-=1];$d=$c)$a[$i]=2+$t=$d<=>$c?:$t;echo strtr($a,[13=>12]);

```

Walks over the input from right to left and replaces each char with the type.

```
$t=$d<=>$c?:$t

```

Calculates the type given the current and the previous char (-1 or 1). If equal the type doesn't change.
> 1 votes

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


title: Dungeon of botdom

text:
# Question
Title: Dungeon of botdom
## – of crisis and martyrdom

(that's the subtitle because subtitles are cool)

In this challenge in (yup; you need go no farther to know you may not submit in java), you need to create a bot that plays a game very similar to welcome to the dungeon

## Game Rules

(note that this is not the original game)

There is a deck, an item set, and some reward cards and death cards. Base HP is 3. The deck consists of 13 monster cards numbered `1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 9` to denote their strengths.

**Item List**

1. Demonic pact: Defeat the demon (strength 7 monster), and the monster below it on the dungeon pile. \- (just defeats the demon if the demon was the last in the dungeon)
2. Health potion: When you fall to 0 HP, defeat the monster and return to 3 HP.
3. Holy grail: Defeat monsters of even-numbered strength (in the game, these are undead). If an even-numbered monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
4. Vorpal dagger: Choose one monster before entering the dungeon; this type of monster is defeated. If the targeted monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
5. Shield: Add 3 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.
6. Armour: Add 5 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.

Reward cards are used to keep track of who has succeeded in the dungeon. Death cards track who has failed in the dungeon.

**Drawing Phase**

Before the drawing phase begins all monster cards are returned to the deck, both players are restored to 3 HP, and all discarded items are restored such that there is one of each.

The first player decides whether to draw a card from the deck, hiding it from the other player. If so, they must choose to either place it on top of the dungeon pile or discard it along with an item of their choice. Discarded items and cards will be unavailable to either player until the next round.

After player one takes their turn, player two does the same. The players alternately decide whether to draw and what to do with the drawn card, until someone decides not to draw or a player takes the last card from the deck. If a player decides not to draw, or draws the last card, the drawing phase ends and the other player now has to enter the dungeon and begin spelunking.

**Spelunking Phase**

If the Vorpal dagger has not been discarded, the spelunking player must now decide which card to apply it to. There are no active decisions to be made for the rest of this phase.

The first player takes the top card; that is, the last card placed in the dungeon, and see its strength number. If demonic pact is active from the previous turn, the drawn card is discarded. Otherwise, the player's items will be checked in the order 'demonic pact', 'holy grail', 'Vorpal dagger'. The first un-discarded item capable of defeating the drawn card will then be used, and the card discarded. If demonic pact is used, it will now be active for the next card. The used item is not discarded.

If there is no applicable item available, the strength of the card is subtracted from the player's health. If their health is no longer positive they will be restored to 3 HP and the potion discarded if available, otherwise the dungeon crawl ends and they take a death card.

While the player is not defeated and there are cards remaining in the dungeon, this process of drawing the top card is repeated. Upon successfully defeating all cards in the dungeon the dungeon crawl ends and the spelunking player collects a reward card.

**Full Game Description**

A game consists of a series of rounds, each having a drawing phase and then a spelunking phase. At the end of each round one player will have collected either a death card or a reward card; once a player accumulates 5 of either type the game ends. If they have 5 death cards they lose the game. If they have 5 reward cards, they win. Either way, the other player receives the opposite result. If neither player has 5 cards of one type, play progresses to the next round and the player who went second in the previous round now goes first and vice versa.

## KOTH details

Each bot will play 400 games against every other bot according to the rules described above. Which bot is player one (and so goes first in the first round) alternates each game, and all state is reset between games.

Here are the items again:

1. Demonic pact: Defeat the demon (strength 7 monster), and the monster below it on the dungeon pile. \- (just defeats the demon if the demon was the last in the dungeon)
2. Health potion: When you fall to 0 HP, defeat the monster and return to 3 HP.
3. Holy grail: Defeat monsters of even-numbered strength (in the game, these are undead). If an even-numbered monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
4. Vorpal dagger: Choose one monster before entering the dungeon; this type of monster is defeated. If the targeted monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
5. Shield: Add 3 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.
6. Armour: Add 5 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.

and the deck: `1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 9`.

You must implement a bot class that does not use class variables, deriving from the following base class:

```
class BasePlayer:
    def start_turn(self, last_turn):
        raise NotImplementedError

    def play(self, card):
        raise NotImplementedError

    def vorpal_choice(self, last_turn):
        raise NotImplementedError

    def result(self, bot, result, dungeon, vorped):
        raise NotImplementedError

```

This base class shows methods your class needs to implement, and the number of arguments taken by each.

**Method Argument Descriptions**

* `last_turn` in `vorpal_choice` and `start_turn` is an integer or a None value. A value of 0 to 5 indicates that the enemy discarded the drawn card along with the item indicated by that value (see the list of items above). A value of 6 indicates that the enemy placed the card in the dungeon. A None value indicates that the bot is playing first in this round (not possible for `vorpal_choice`). In `vorpal_choice` last\_turn is likely to be 7, indicating that they passed that turn. The only circumstance in which it is not 7 is when the enemy drew the last card.
* `card` is a number representing the strength of one of the cards from the deck as enumerated above.

Now, the arguments for `result` are a little bit more complex:

* `bot` indicates the bot which entered the dungeon. 0 indicates entering the dungeon, and 1 indicates that the enemy entered the dungeon.
* `result` indicates the success of the trip. False indicates the spelunking bot succeeded, while True indicates they failed.
* `dungeon` is a list of cards/ints representing the cards that were in the dungeon. The dungeon is ordered by order placed; the first card placed in the dungeon is first in the list, and the last card placed in is at the end. You will not receive any info about discarded cards; they are secret from the other bot.
* `vorped` is an integer representing the `vorpal_choice` made by the spelunking bot. If `bot==0`, you already know this, but if `bot==1`, this can be useful information.

I'll be honest, I don't entirely recall why I made winning result False, but I think it was a good idea at the time.

**Return Values**

* `start_turn`: Return 1 to draw a card, or 0 to pass.
* `play`: Return 0 to 5 to discard the corresponding item and the drawn card, or 6 to place the card in the dungeon (consistent with last\_turn input, except for passing, which is done during start\_turn).
* `vorpal_choice`: Return the number of the card you wish to eliminate with the Vorpal dagger (1 to eliminate 1s, 5 to eliminate 5s). Picking a non-existent card kills you (8 is illegal, 10 is illegal, 0 is illegal).
* `result`: You may return anything, because this is an informing function to update the bot's data.

# You can check out the controller here

# Additional clarifications, or just repeating some small details you might have skipped past and might want to know quickly:

Bots play 400 games with each other bot.

### No class variables

### No targeting specific other bots

### No propping up other bots

### No reflection things like modifying the random module or other bots.

### 6 bots maximum (per person), unless it is obvious that all bots are worth including in the KOTH (but still probably don't make a bunch of bots please)

---

### There is no specific end time for this KOTH, except the end of the bounty for what that is worth. Just try to be winning at each time.

Results so far (sorry for being rather lazy with these guys :P)

```
1 GrailThief 2732 0.98
2 Steve 2399 0.86
3 DevilWorshipper 1854 0.66
4 RunAway 1336 0.48
5 BoringPlayer 1190 0.42
6 SlapAndFlap 783 0.28
7 DareDevilDumDum 750 0.27
8 RandomMandom 156 0.06

```

Grailthief "steals" the bounty. not really, because it earned it. Good work, Sleafar!

# Answer
# GrailThief

An old and experienced dungeon crawler. He knows that most of the others hope, that the holy grail saves them, therefore he makes sure it disappears.

```
from base import BasePlayer
import copy

class GrailThief(BasePlayer):
    class Stats:
        def __init__(self):
            self.deck = [1, 2, 3, 4, 5] * 2 + [6, 7, 9]
            self.items = {0, 1, 2, 3, 4, 5}
            self.dungeon_known = []
            self.dungeon_unknown = 0
            self.monsters_safe = {2, 4, 6, 7}
            self.update()

        def update(self):
            self.dungeon_total = len(self.dungeon_known) + self.dungeon_unknown
            deck_factor = float(self.dungeon_unknown) / len(self.deck) if len(self.deck) > 0 else 1.0
            self.dungeon_weighted = [(i, 0.0 if i in self.monsters_safe else 1.0) for i in self.dungeon_known] + [(i, 0.0 if i in self.monsters_safe else deck_factor) for i in self.deck]
            dungeon_weighted_sums = dict.fromkeys(self.dungeon_known + self.deck, 0.0)
            for i in self.dungeon_weighted:
                dungeon_weighted_sums[i[0]] += i[0] * i[1]
            self.vorpal = max(dungeon_weighted_sums, key = dungeon_weighted_sums.get)
            if 3 in self.items:
                self.dungeon_weighted = [(i[0], 0.0 if i[0] == self.vorpal else i[1]) for i in self.dungeon_weighted]

        def discard_item(self, item, card):
            new = copy.copy(self)
            new.items = {i for i in new.items if i != item}
            if item == 0:
                new.monsters_safe = {i for i in new.monsters_safe if i != 7}
            elif item == 2:
                new.monsters_safe = {i for i in new.monsters_safe if i not in {2, 4, 6}}
            if card is not None:
                new.deck = list(new.deck)
                new.deck.remove(card)
            new.update()
            return new

        def to_dungeon(self, card):
            new = copy.copy(self)
            if card is None:
                new.dungeon_unknown += 1
            else:
                new.deck = list(new.deck)
                new.deck.remove(card)
                new.dungeon_known = list(new.dungeon_known)
                new.dungeon_known.append(card)
            new.update()
            return new

        def effective_hp(self):
            hp = 3.0
            if 1 in self.items:
                hp += 3.0
                if self.dungeon_total > 0:
                    hp += sum([(i[0] - 1) * i[1] for i in self.dungeon_weighted]) / self.dungeon_total
            if 4 in self.items:
                hp += 3.0
            if 5 in self.items:
                hp += 5.0
            return hp

        def effective_damage(self):
            damage = sum([i[0] * i[1] for i in self.dungeon_weighted])
            if 0 in self.items:
                if self.dungeon_total > 1:
                    damage -= damage / (self.dungeon_total - 1)
            return damage

    def __init__(self):
        self.stats = self.Stats()

    def process_last_turn(self, last_turn):
        if last_turn in [0, 1, 2, 3, 4, 5]:
            self.stats = self.stats.discard_item(last_turn, None)
        elif last_turn == 6:
            self.stats = self.stats.to_dungeon(None)

    def start_turn(self, last_turn):
        self.process_last_turn(last_turn)
        if self.stats.effective_hp() > self.stats.effective_damage() + 1.5:
            return 1
        else:
            return 0

    def play(self, card):
        if 2 in self.stats.items:
            self.stats = self.stats.discard_item(2, card)
            return 2
        else:
            self.stats = self.stats.to_dungeon(card)
            return 6

    def vorpal_choice(self, last_turn):
        self.process_last_turn(last_turn)
        return self.stats.vorpal

    def result(self, bot, result, dungeon, vorped):
        self.stats = self.Stats()

```
> 3 votes

# Answer
# DevilWorshipper

My first attempt at a KOTH challenge:

```
from base import BasePlayer
#from random import randint

class DevilWorshipper(BasePlayer):
    def reset(self):
        self.items = [0, 1, 2, 3, 4, 5]
        self.turns = 0
        self.demon = False
        self.dragon = False

    def __init__(self):
        self.reset()

    def start_turn(self, last_turn):
        if last_turn in self.items:
            self.items.remove(last_turn)

        if last_turn is not None:
            #self.demon = True if randint(1, 13 - self.turns) <= 2 else False
            self.turns += 1

        if (((self.demon == True and not (0 in self.items)) or (self.dragon == True)) and not (3 in self.items)):
            return 0
        if (len(self.items) <= 1):
            return 0
        return 1

    def play(self, card):
        self.turns += 1

        if (card == 9):
            self.dragon = True
            return 6

        if (card == 7):
            self.demon = True
            return 6

        for i in [3, 0, 2, 1, 5, 4]:
            if (i in self.items):
                self.items.remove(i)
                return i

        return 6

    def vorpal_choice(self, last_turn):
        return 5 #If it works for others maybe it will work for us

    def result(self, bot, result, dungeon, vorped):
        self.reset()

```

Essentially, we get rid of the pact and the vorpal dagger, wait for the demon to get into the deck, and pass. Every round the opponent may have drawn the demon, it has the % chance that the last card the opponent drew was a demon to just assume they played the demon already.

Let me know if there's anything I did wrong; I haven't messed with python in a while, this is my first KOTH, and it's 2 am, so there's bound to be something.

**EDITS:**

Taking out the randomness turns out to help it a lot. With the randomness in it is very dumb. Also, as said in the comments below, it tries to summon the demon or dragon.

# Steve

```
from base import BasePlayer
from random import choice

class Steve(BasePlayer):

    def reset(self):
        self.items = [0, 1, 2, 3, 4, 5]
        self.turns = 0
        self.dungeon = []
        self.possibledungeon = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 9]
        self.lastDied = 0

    def __init__(self):
        self.TRIALS = 10 #How many dungeon runs to do each turn
        self.PASS = 8    #How many dungeon runs have to have died to pass
        self.SMASHITEMS = 4 #If less dungeon runs died, smash items.
        self.reset()

    def start_turn(self, last_turn):
        if (last_turn is not None):
            self.turns += 1

            if (last_turn in self.items):
                self.items.remove(last_turn)
            else:
                self.dungeon.append(-1)

        #Check if the dungeon is lethal
        died = 0
        total_hp = 3
        if (5 in self.items):
            total_hp += 5
        if (3 in self.items):
            total_hp += 3
        vorpal = self.vorpal_choice(None)
        for i in range(self.TRIALS):
            hp = total_hp
            temppossible = self.possibledungeon.copy()
            usedpotion = False
            killedDemon = False
            #Going for a crawl
            for j in self.dungeon[::-1]:
                if (killedDemon == True): #If last round we killed the Demon
                    killedDemon = False
                    j = 0
                if (j == -1): #If we don't know what this card is
                    j = choice(temppossible)
                    temppossible.remove(j)
                if (j == 7 and 0 in self.items): #If we kill demon with the pact
                    j = 0
                    killedDemon = True
                if (j % 2 == 0 and 2 in self.items) or (j == vorpal): #If we vorpal or grail
                    j = 0

                hp -= j

                if (hp <= 0):
                    if (not usedpotion and 1 in self.items):
                        hp = 3
                        usedpotion = True
                    else:
                        died += 1
                        break

        if (died >= self.PASS):
            return 0

        died = self.lastDied
        return 1

    def play(self, card):
        self.possibledungeon.remove(card)

        if (self.lastDied < self.SMASHITEMS):
            if (7 in self.dungeon) and (0 in self.items):
                self.items.remove(0)
                return 0
            if ( (9 in self.dungeon) or (5 in self.dungeon) ) and (3 in self.items):
                self.items.remove(3)
                return 3
            for i in [2, 1, 5, 4, 3, 0]:
                if (i in self.items):
                    self.items.remove(i)
                    return i

        self.dungeon.append(card)
        return 6

    def vorpal_choice(self, last_turn):
        if (last_turn is not None):
            self.turns += 1

            if (last_turn in self.items):
                self.items.remove(last_turn)
            else:
                self.dungeon.append(-1)

        if (self.dungeon.count(5) == 2):
            return 5
        if (9 in self.dungeon):
            return 9
        if (self.dungeon.count(4) == 2 and not 2 in self.items):
            return 4
        if (7 in self.dungeon and not 0 in self.items):
            return 7
        for i in range(6)[::-1]:
            if (i+1 in self.dungeon):
                return i+1
        return 5

    def result(self, bot, result, dungeon, vorped):
        self.reset()

```

Steve tries to guess whether or not the dungeon is lethal. If he thinks it is, he passes. Other than that, I tried to make him get rid of items smartly. He used to adjust his PASS threshold depending on if he died in the dungeon or the opponent lived, but it ended up making him a lot dumber so I got rid of it.

He still doesn't beat GrailThief on my machine, but at least comes closer.
> 3 votes

# Answer
## SlapAndFlap

First time in KOTH, so slap me hard for mistakes.

This one simpleton is always trying to remove all good items with low-strength monsters, while keep powerful ones and then just forces opponent to play.
It beats RunAway and DumDum at least :D
My other bot in deleted answer for some time, I need to fix him by tommorow

```
from base import BasePlayer

class SlapAndFlap(BasePlayer):

    def reset(self):
        # Monsters that you pushed in
        self.know_monster = list(self.deck)

        # Items still in game
        self.items_in_game = [True, True, True, True, True, True]

        # List of items, sorted by value
        self.valuables = [3,1,5,0,2,4]

        # Counter
        self.cards = 13

    def __init__(self):
        # Deck
        self.deck = (1,1,2,2,3,3,4,4,5,5,6,7,9)
        # Indexes of item cards
        self.items = (0, 1, 2, 3, 4, 5)

        self.reset()

    def start_turn(self, last_turn):
        if last_turn is not None:
            self.cards -= 1

        # Sneak peak at items removed by opponent
        if last_turn is not None and  last_turn < 6:
            self.items_in_game[last_turn] = False
            self.valuables.remove(last_turn)

        # Flap!
        if self.cards < 6:
            return 0
        return 1

    def play(self, card):
        if card < 6 and any(self.items_in_game):
            self.know_monster.remove(card)
            to_return = self.valuables[0]   # remove the best of the rest
            self.valuables = self.valuables[1:]
            self.items_in_game[to_return] = False
            return to_return
        else:
            return 6

    def vorpal_choice(self, last_turn):
        # We can just guess what monster will be there
        # But we know ones, we removed

        # If we have pact, no need to remove demon
        if self.items_in_game[0]:
            self.know_monster.remove(7)
        # If we have grail, no need to remove even monsters (kinda)
        if self.items_in_game[2]:
            self.know_monster = [i for i in self.know_monster if i%2]

        # Find what threatens us the most, counting its strength multiplied by number
        weight = [i * self.know_monster.count(i) for i in self.know_monster]
        return weight.index(max(weight)) + 1

    def result(self, bot, result, dungeon, vorped):
        self.reset()  # we live for the thrill, not the result!

```
> 2 votes

# Answer
# RandomMandom

The obligatory random bot. Appropriately, he loses hard to the default bots, which is good, because it means that the game has at least some strategy.

```
from base import BasePlayer
from random import randint
from random import choice
class RandomMandom(BasePlayer):
    def __init__(self):
        self.items = [0,1,2,3,4,5]

    def start_turn(self, last_turn):
        if last_turn in self.items:
            self.items.remove(last_turn)
        if len(self.items) > 0:
            return randint(0,1)
        return 1

    def play(self, card):
        if len(self.items) > 0:
            if randint(0,1) == 1:
                selection = choice(self.items)
                self.items.remove(selection)
                return selection
        return 6

    def vorpal_choice(self, last_turn):
        return choice([1,2,3,4,5,6,7,9])

    def result(self, bot, result, dungeon, vorped):
        # Never learns
        pass

```
> 2 votes

# Answer
# DareDevilDumDum

kinda clear. never backs down. the only way you can (consistently; RunAway loses sometimes but it still beats this most of the time) lose to this bot is if you don't remove any items or are a super coward. think of this bot as a reminder to remove items, otherwise even this can win.

```
from base import BasePlayer

class DareDevilDumDum(BasePlayer):
    def start_turn(self, last_turn):
        return 1  # damn squiggles. Draw a card

    def play(self, card):
        return 6+card*0  # put the card in the dungeon, and use card to avoid squiggles :P

    def vorpal_choice(self, last_turn):
        return 9+last_turn*0  # dragon

    def result(self, bot, result, dungeon, vorped):
        pass  # we live for the thrill, not the result!

```

And

# RunAway

pretty much they remove armour and then run away some time before the end. as daredevildumdum, it doesn't remember anything, except for the number of cards in the deck (which tbh wouldn't be remembered in the actual game (you'd just check)) and whether someone removed the armour (mostly same as before).

```
from base import BasePlayer

class RunAway(BasePlayer):

    def __init__(self):
        self.cards = 13
        self.armoured = True

    def start_turn(self, last_turn):
        if last_turn is not None:
            self.cards -= 1  # opponents play
        if last_turn is 5:
            self.armoured = False

        if self.cards < 4:
            return 0 * last_turn  # avoid the ---noid--- squiggles
        else:
            return 1

    def play(self, card):
        if self.cards > 11 and self.armoured:  # if it is the first turn and armour has not been removed
            choice = 5  # remove armour
        else:
            choice = 6  # put the card in the dungeon
        self.cards -= 1  # this play
        return choice

    def vorpal_choice(self, last_turn):
        return 5  # without using more memory, this is the best choice statistically

    def result(self, bot, result, dungeon, vorped):
        self.cards = 13
        self.armoured = True

```

Also because I am special challenge poster, these bots do not count toward my bot count, because they are example bots that are dumb
> 1 votes

# Answer
# BoringPlayer

The opposite of RandomMandom, BoringPlayer always makes the same choices. The problem is that it appears that it is too successful for such a simple bot. It scores 3800+ in my local test.

```
from base import BasePlayer

class BoringPlayer(BasePlayer):
    def start_turn(self, last_turn):
        return 1

    def play(self, card):
        return 6

    def vorpal_choice(self, last_turn):
        return 5

    def result(self, bot, result, dungeon, vorped):
        # Never learns
        pass

```
> 1 votes

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


title: MacGyver's Toolbox

text:
# Question
Title: MacGyver's Toolbox
In this question each answer will get a "toolbox" that can be used to construct a program/function. The toolbox will consist of two things:

* a list of programming languages
* a list of valid characters

You must write a valid program/function in one of the languages provided using only the characters in the toolbox. Your program/function should output the number of answers already present on this question.

Once you have written and posted an answer the language and characters you have used will be removed from the toolbox and 1 new language and 12 new characters will be randomly added to be used as the toolbox for the next answer.

## Rules

* Each answer will:

+ Output the number of valid answers coming before it
    + Contain a subset of the characters provided in the toolbox for that answer. (repeats are allowed)
    + Be in one of the languages from the provided toolbox
* The next toolbox will determined by this python program. To generate the next toolbox put in the remaining languages and characters along with the *post id* of the last answer.
* The language list here is all the languages available on try it online at the time of this post. The characters have char codes 0-127.
* You may write either a full program or a function as your answer. Since REPLs are different languages they will not be allowed. (use the TIO version of every language)
* If a language uses a special encoding the characters should be interpreted as *bytes* (decoded from ASCII and padded with a zero).
* The starting toolbox will be randomized from this questions post id (126063), there will be 7 languages to start and I will add the characters `echoprint0` and ascii 0-31 for free to get people started.
* You may not answer twice in a row

## Scoring

Each person will have a score equal to the number valid answers they have provided. There will not necessarily be an end and I will not be accepting any answers.

## Sporting

This is a competition, but I encourage you to put fun above winning while still staying competitive (if I could make the winning criteria "fun had" I would). Some things that are not fun:

* Intentionally using characters you don't need to stunt future answers.
* Attempting to game the post id system to make future tool boxes harder to use.
* Attempting to game the post id system to make future tool boxes easier to use.

I can't prevent any one from doing these things, but I will be downvoting any answers I suspect are doing this.

On a more positive note, here are some things that are good sporting and encouraged:

* Coordinating with other users in chat.
* Saving characters for harder or more restrictive languages

# Answer
# 2. Cubix, `(no@`

Third time's the charm

```
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((no@((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((

```

Try it online!

Next toolbox
> 7 votes

# Answer
# 1. 3var (1 byte)

## Toolbox

```
['elf', 'cubix', 'sml-mlton', 'forte', 'logicode', 'python1', '3var']
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e.0@BGN`ceghilnoprtvwz}'

```

## Code

```
p

```

Try it online!

Next toolbox
> 5 votes

# Answer
# 3. Pari/GP, 3 bytes

```
`
2

```

Exploits a syntax error.

Try it online!

Next toolbox
> 4 votes

# Answer
# 5. J, 3 Bytes

```
5|9

```

Performs 5 mod 9, outputting 4

Next toolbox!
> 4 votes

# Answer
# 15. Half-Broken Car in Heavy Traffic

```
#
^
^
^
^
^
^
^
^
^
^
^
^   >>v
  < ^
^ >   v
  ov ^
^< <  <

```

Outputs is in cell -2.

Try it online!

Next Toolbox
> 4 votes

# Answer
# 6. Forte

Uses `\n 187-DENPUT`

```
1 PUT 71-18
7 END

```

Try it online!

Next toolbox
> 3 votes

# Answer
# 7. Standard ML (MLton), 7 bytes

```
fun$n=6

```

Try it online! This declares a function `$` which takes any argument and returns `6`, eg. by calling with `$()`.

New toolbox. Powershell is the newly added language.
> 3 votes

# Answer
# 23. DStack, 5 bytes

```
222cK

```

**Explanation**

DStack is read in pairs and moves the cursor one char at a time, so the instructions become `22`, `22`, `22`, and `cK`.

```
22  Multiplies register by 10 (initially 0), adds 2
22  Multiplies register by 10, adds 2
2c  Does nothing
cK  Displays number of the register

```

Try it online!

Next Toolbox
> 3 votes

# Answer
# 27. Assembly (x64, Linux, as)

```
.text
  .global _start
_start:
movl $len,%edx
movl $msg,%ecx
movl $1,%ebx
movl $4,%eax
int $0x80
movl $0,%ebx
movl $1,%eax
int $0x80
.data
msg:
.byte 0b110010,0b110110
len = . - msg

```

Try it online!

# Explanation

I don't really know Assembly as, and information online seems hard to find ,so this is modified from the Hello World test on TIO.

The main issue here is that we lack the `2` byte, (turns out we did, but hey looks like I saved a 2 for the next answer) this makes it relatively hard to print `26`. We can't use raw ascii or even Hexadecimal (`0x32`) so I ended up using binary.

```
msg:
.byte 0b110010,0b110110

```

Tells it to output the two bytes `2` and `6`.

Next toolbox
> 3 votes

# Answer
# 35. ELF 32-bit LSB executable (Linux), 48 bytes

```
0000000: 7f 45 4c 46 01 00 00 00 00 00 00 00 00 90 43 0d  .ELF..........C.
0000010: 02 00 03 00 19 90 43 0d 19 90 43 0d 04 00 00 00  ......C...C.....
0000020: b9 2e 90 43 0d b2 0d cd 80 cc 20 00 01 00 33 34  ...C...... ...34

```

I've done it! I have conquered the elusive ELF. ELF has been the first language in the list ever since the first toolbox. Now we can move on.

I've never used or even heard of ELF before, so this one was an adventure to figure out. I eventually copied much of Dennis' 32 bit Hello, World! program (64 bit version here). I modified it to print 33 and was able to remove a line of bytes.

Chars used: `\x00\x01\x02\x03\x04\r\x19 .34CEFL\x7f\x80\x90\xb2\xb9\xcc\xcd`

Try it online!

Next Toolbox
> 3 votes

# Answer
# 9. JavaScript (Babel Node), 14 bytes

```
console.log`8`

```

Try it online!

Miraculously all the characters needed were available.

Next toolbox New language: pylons (Should be easy ;).
> 2 votes

# Answer
# 18. C# (.NET Core), 33 bytes

```
()=>System.Console.WriteLine(17);

```

Try it online!

Next Toolbox
> 2 votes

# Answer
# 20. TRANSCRIPT, 45 bytes

```
You can see a Q here.
>SET Q TO 19
>X Q
>QUIT

```

**Explanation:**

TRANSCRIPT is designed to resemble interactive fiction scripts. So rather than using variables, objects and NPCs are used. Commands and dialog (essentially comments) are mixed together.

```
You can see a Q here.    Creates an object named Q
>SET Q TO 19             Assign Q to 19
>X Q                     Display Q
>QUIT                    End the program

```

Chars used: `.19>EIOQSTUXYZacehnorsu`

Try it online!

Next Toolbox
> 2 votes

# Answer
# 29. Pushy, `TL#`

```
TTTTTTTTTTTTTTTTTTTTTTTTTTTTL#

```

This pushes `10` to the stack 28 times, then gets the length of the stack and prints it.

Try it online!

Next toolbox
> 2 votes

# Answer
# 34. Java (OpenJDK 9), 63 bytes

```
interface a{static void main(String[]a){System.out.print(33);}}

```

I figured this was getting a bit too easy, with all the characters available and all...

Try it online!

Next toolbox
> 2 votes

# Answer
# 45. Templates Considered Harmful, `Ad<T,>`

```
Add<Add<Add<Add<Add<Add<T,T>,Add<T,T>>,Add<Add<T,T>,Add<T,T>>>,T>,Add<T,T>>,Add<Add<T,T>,Add<Add<Add<Add<T,T>,Add<Add<Add<Add<Add<Add<Add<T,T>,Add<T,T>>,Add<Add<T,T>,Add<T,T>>>,T>,Add<T,T>>,Add<Add<T,T>,Add<Add<Add<Add<T,T>,Add<T,T>>,Add<Add<T,T>,Add<T,T>>>,T>>>,T>>,Add<Add<T,T>,Add<T,T>>>,Add<T,T>>>>

```

Try it online!

Next Toolbox
> 2 votes

# Answer
# 4. Python 1 `print+3`

```
print+3

```

Try it online!

Next toolbox
> 1 votes

# Answer
# 8. PowerShell Core, 1 byte

```
7

```

Try it online!

I had no idea what powershell is, but it turns out that 7 outputs 7 in TIO.

Next toolbox
> 1 votes

# Answer
# 10. Prelude, `3+!`

We finally got an `!`!

```
3333333333333333333++++++++++++++++++!

```

Try it online!

Next toolbox

## Explanation

`9` is 57 in ASCII, which is 3 times 19. So in order to get `9` we add 19 3s and use `!` to output.
> 1 votes

# Answer
# 11. Convex, 1 byte

```
A

```

Try it online!

Next toolbox
> 1 votes

# Answer
# 12. Logicode, 6 bytes

```
out 11

```

Try it online!

trivial, right language for 11

Next toolbox
> 1 votes

# Answer
# 16. Scala, 13 bytes

```
()=>print(15)

```

Try it online!

Next Toolbox
> 1 votes

# Answer
# 17. 2sable (Prints 16)

```
4n

```

Try it online!

```
4  # Push 4
 n # Square it

```

Next Toolbox, new language: golfscript
> 1 votes

# Answer
# 19. pbrain, 58 bytes

```
+++++++++++++++++++++++++++++++++++++++++++++++++.+++++++.

```

Prints ASCII values 49 and 56 (`18`).

Try it online!

Next toolbox
> 1 votes

# Answer
# 22. MarioLANG, 44 bytes

```
+++++++++++++++++++++:
=====================

```

Boring but shortest.

Try it online!

Next Toolbox
> 1 votes

# Answer
# 24. Chez Scheme, 12 bytes

```
(display 23)

```

Try it online! Next toolbox. Arcyóu is the new language.
> 1 votes

# Answer
# 28. Haskell, 6 bytes

```
f x=27

```

Try it online! Declares a function `f` which takes any argument and returns `27`.

Next toolbox:

```
['elf', 'logicode', 'visual-basic-net-mono', 'python2-pypy', 'silos', 'pushy', 'agony']
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f!"#$%&\'()*+,-./1234569:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`cdghijkopqrtuvwxz{|}~\x7f'

```
> 1 votes

# Answer
# 30. Visual Basic .NET (Mono), 9 bytes

```
MSGBOX 29

```

Pops up a system dialog box containing 29. Very similar to `alert` in javascript. It is case insensitive, but is usually written as `MsgBox`.

This can't be tested on TIO because `MsgBox` is a system window and that can't be seen online. The easiest way to test it is by pasting the code into a `.vbs` text file and running it on Windows. A `.vbs` file uses VBScript, a scripting version of VB that is very similar (`MsgBox` is the same between the two).

It's fun to use `MsgBox` again as that was the very first thing I ever programmed. In fifth grade, I made a series of `MsgBox` scripts to mess with friends.

Next Toolbox
> 1 votes

# Answer
# 31. Python 2 (PyPy), `print-31`

```
print--31-1

```

Try it online!

`--31` is the same thing as `31`, then `-1` subtracts 1, making it 30.

Next toolbox
> 1 votes

# Answer
# 33. Minkolang, 9 bytes

```
"332"(O).

```

Try it online!

Next Toolbox

Never heard of this one before, I have no idea how it works. It just did weird stuff and I went "ok fine" and got it to print what I wanted. :D
> 1 votes

# Answer
# 38. Go, 20 bytes

First 20 byte Go solution on PPCG..? :P

```
func()int{return 37}

```

Try it online!

Next toolbox.
> 1 votes

# Answer
# 39. wsf, 58 bytes

```

```

Try it online!

Next toolbox
> 1 votes

# Answer
# 42. S.I.L.O.S, 8 bytes `print 41`

```
print 41

```

Try it online!

Little boring, but it works

Next toolbox
> 1 votes

# Answer
# 43. Logicode, 19 bytes

```
out @110100+@110010

```

Try it online!

Next toolbox
> 1 votes

# Answer
# 46. uBASIC, `PRINt45`

```
4PRINt45

```

I ran out of uppercase letters, so I used a lowercase `t`! I guess you could call it PRIN-t or Printy!

Try it online!

Next Toolbox
> 1 votes

# Answer
# 48. Racket, `cake eating peril (#47)`

```
#lang racket (print 47)

```

"Cake eating peril?!?", you might ask. Well, if I said `peak #7 in a rectilinear triple integral r(4)` instead, then you'd all be confused and `pinkcartgel() #47` just doesn't make sense, so `cake eating peril (#47)` was a natural choice. Plus, maybe Racket eats cake in it's free time. We'll never know.

It's no fun to say the chars you used sorted alphabetically. Anagrams are better. I'd suggest you do the same :).

Try it online!

Next Toolbox
> 1 votes

# Answer
# 54. ///, 2 bytes

```
53

```

Sorry for taking your numbers but there's really no better solution.

(oh wait, 5 and 3 got added to the toolbox again)

Try it online!

Next Toolbox
> 1 votes

# Answer
# 56. Go

```
package main

import "fmt"

func main() {
   fmt.Println("55")
}

```

I learned this language just for this challenge. If I understood the challenge correctly, this should be valid.

Try it Online!

Next Toolbox
> 1 votes

# Answer
# 13. Pylons, 14 bytes

```
2+2+2+2+2+2+2,

```

Try it online!

Next toolbox

(We now have all the characters)
> 0 votes

# Answer
# 14. CJam, 2 bytes

I'll try to be a bit more creative next time.

```
13

```

Try it online!

Next toolbox
> 0 votes

# Answer
# 21. Turtlèd

```
"20"

```

Try it online!

Next Toolbox:

```
['elf', 'assembly-as', 'scheme-chez', 'logicode', 'golfscript', 'dstack', 'mariolang']
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'

```
> 0 votes

# Answer
# 25. Arcyóu

```
24

```

Boring, but ¯\\\_(ツ)\_/¯

Try it online!

Next Toolbox:

```
['elf', 'assembly-as', 'logicode', 'golfscript', 'visual-basic-net-mono', 'python2-pypy', 'silos']
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'

```
> 0 votes

# Answer
# 26. GolfScript, 2 bytes

```
25

```

GolfScript makes this way too easy.

It pushes `25` to the stack, then when the program ends, it prints the stack.

Try it online!

Next Toolbox

**Available Languages**

* elf
* assembly-as
* logicode
* visual-basic-net-mono
* python2-pypy
* silos
* haskell
> 0 votes

# Answer
# 32. rk, 27 bytes

```
rk:start print: "31" rk:end

```

Chars used: `"13:adeiknprst`

The code is pretty self explanatory, but what surprised me is that rk was created by a 13 year old.

Try it online!

Next Toolbox
> 0 votes

# Answer
# 36. Foo, 10 bytes

```
&2+1$h&5$h

```

Try it online!

God I hope I understood this challenge correctly.

Chars used: `$&+125h`

## Explanation

```
&2+1$h&5$h
&2          Set current cell to 2
  +1        Add 1 to current cell
    $h      Print as hexadecimal (i was taken so couldn't print as decimal
              thankfully 0-10 are the same in hex as in decimal)
      &5    Set current cell to 5
        $h  Print as hexadecimal

```

Next Toolbox

Looks like Go's on the menu now, hope to see something awesome from totallyhuman
> 0 votes

# Answer
# 37. Oasis, 36 bytes

```
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

```

Try it online!

Next Toolbox
> 0 votes

# Answer
# 40. Reticular, 7 bytes

```
12+:9O;

```

Try it online!

Next toolbox
> 0 votes

# Answer
# 41. Random Brainfuck, 19 bytes

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

```

Try it online!

Next toolbox
> 0 votes

# Answer
# 44. ,  `"().34;adeilmnoprstvw{}`

```
import std.stdio;void main(){writeln("43");}

```

Try it online!

Next toolbox
> 0 votes

# Answer
# 47. Forth (forth-gforth), `46 .`

```
46 .

```

**Try it online**

Well that was easy.

Next Toolbox
> 0 votes

# Answer
# 49. brainbool, 26 bytes `+><.`

```
+>+<.>.>.>.>.>.

```

Try it online!

Outputs `110000`, which is `48` in base 2

Next toolbox
> 0 votes

# Answer
# 50. Kotlin, 4 bytes

```
->49

```

Try it online!

Next toolbox.
> 0 votes

# Answer
# 51. Unlambda, ``.05i`

```
`.0`.5i

```

Try it online!

Next Toolbox
> 0 votes

# Answer
# 52. Factor, 17 bytes

```
USE: io
"51"print

```

Try it online!

Next toolbox
> 0 votes

# Answer
# 53. Actually, `6DP*`

```
6DP6DD*

```

Try it online!

---

```
6       push 6
 D      pop 6, push 6-1=5
  P     pop 5, push the 5th prime = 13
   6DD  push 6-1-1=4
      * pop 13 and 4, push 13*4=52

```

---

Next toolbox
> 0 votes

# Answer
# 55. Agony

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++.-.

```

I don't really get this language, but it seems to be a superset of brainfuck.

Try it online!

Next toolbox
> 0 votes

---
Tags: restricted-source, answer-chaining
---


title: Counting Gems on the Ground

text:
# Question
Title: Counting Gems on the Ground
# Counting Gems

## Background

My jewel box just fell down! There're too many gems of different shape on the ground. And your task is to count number of a certain type of gem.

## I/O

* Your code should take two inputs `S` and `G`, which could be a string with newlines, an array of lines, a two-dimensional array of characters, a textfile or in any reasonable format (if so, please state it clearly).
* These two strings will only contain `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~` (from `0x21` to `0x7E` in ASCII table), space and newlines (binary form depending on your platform).
* In each string, lines are in same length.
* `S` is the gem we want to count. There're two circumstances.
    1. Enclosed and doesn't contain any nested enclosed area. (in example 1/2)
    2. Doesn't contain any enclosed area. (in example 3/4)
* Surrounding spaces are not regarded as a part of the gem.
* `G` is the shape of gems on the ground.
* It is acceptable that your code requires extra input to specify the dimension(s) of `S` and `G`
* It is acceptable that your code take ASCII values as inputs, instead of characters themselves. But you should **not** substitute characters with simpler integers (0,1,2,3). Your program should be able to process characters, or ASCII values.

## Example 1 (Character as input)

Input `S`:

```
+-+
| +-+
| | |
| | |
| +-+
+-+

```

Input `G`:

```
    +-+       +-+
    | +-+   +-+ |
    | | |   | | |
    | | |   | | |
    | +-+   +-+ |
    +-+       +-+
         +-+
+---+    | +-+
|   |    | | |
|   |    | | |
|   |    | +-++
|   |    +-+| +-+
+---+       | | |
            | | |
  +-+       | +-+
  | +-+     +-+
  | |-|
  | |-|
  | +-+
  +-+

```

Ouptut:

```
2

```

## Example 2 (ASCII value as input)

Input `S`:

```
32 32 32 32 32 32 32 32
32 32 32 32 99 32 99 32
32 32 32 99 32 99 32 99
32 32 32 99 32 32 32 99
32 32 32 99 32 32 32 99
32 32 32 99 32 32 32 99
32 32 32 32 99 32 99 32
32 32 32 32 32 99 32 32
32 32 32 32 32 32 32 32

```

Input `G`:

```
32 99 32 99 32 99 32 99 32 32 99 32
99 32 99 32 99 32 99 32 99 99 32 99
99 32 32 32 99 32 32 32 99 32 32 99
99 99 32 32 99 32 32 32 99 32 32 99
99 32 32 32 99 32 32 32 99 32 32 99
32 99 32 99 32 99 32 99 99 32 99 32
32 32 99 32 32 32 99 32 32 99 32 32

```

Output:

```
1

```

Visualized `S` (32 replaced with --):

```
-- -- -- -- -- -- -- --
-- -- -- -- 99 -- 99 --
-- -- -- 99 -- 99 -- 99
-- -- -- 99 -- -- -- 99
-- -- -- 99 -- -- -- 99
-- -- -- 99 -- -- -- 99
-- -- -- -- 99 -- 99 --
-- -- -- -- -- 99 -- --
-- -- -- -- -- -- -- --

```

Visualized `G`:

```
-- 99 -- 99 -- 99 -- 99 -- -- 99 --
99 -- 99 -- 99 -- 99 -- 99 99 -- 99
99 -- -- -- 99 -- -- -- 99 -- -- 99
99 99 -- -- 99 -- -- -- 99 -- -- 99
99 -- -- -- 99 -- -- -- 99 -- -- 99
-- 99 -- 99 -- 99 -- 99 99 -- 99 --
-- -- 99 -- -- -- 99 -- -- 99 -- --

```

## Example 3 (Not enclosed)

Thanks to @Draco18s

Input `S`

```
AB

```

Input `G`

```
AAB BA CAB

```

Output

```
2

```

## Example 4 (Not enclosed 2D)

Input `S`

```
ABCD
  GE
   F

```

Input `G`

```
ABCD
BGGED
CDEFE
    F

```

Output

```
1

```

## Remarks

* Only two gems of exact one shape are considered the same.
* Same shape in different directions are not considered the same.
* However, as is described in example I/O, overlapping is possible. Under such circumstances, only complete ones are counted.
* `+`, `-` and `|` in the example have no special meanings. They do not indicate any corner or edge of the shape.
* You may assume input is always valid.
* **You may assume two target gems never share an exactly same edge.**
* Standard loopholes are forbidden.
* This is a code-golf, so shortest code wins!

# Answer
> 1 votes
# C (gcc), 303 ~~305~~ ~~326~~ bytes

All optimizations need to be turned off and only work on 32-bit GCC.

```
#define r(z,k)for(z=0;z<k;z++)
#define c s[i][j]
x,y,o,p,t,i,j;char**s;h(i,j){!((i<0)+(j<0)+i/x+j/y+c-32)?h(i+1,j),h(i-1,j),h(i,j+1),h(i,j-1),c=0:0;}f(w,e,u,v,a,g)char**a,**g;x=w,y=e,s=a;r(o,x)h(o,0),h(o,y-1);r(p,y)h(0,p),h(x-1,p);w=0;r(o,u-x+1)r(p,v-y+1){t=1;r(i,x)r(j,y)t*=!(c*(c-g[i+o][j+p]));w+=t;}}

```

The code uses floodfill to replace surrounding spaces with `\0` and looks for matches while ignoring `\0`.

ungolfed and macros calculated (some letters are different from the golfed version, but logic stays the same):

```
int x, y, o, p, c, d, t;
char **s, **g;
h(int i, int j) {                             // Floodfill function
    if(i<0 || j<0) return;                    // Boundary detection
    if(i>=x || j>=y) return;
    if(s[i][j] != ' ') return;                // Character detection

    s[i][j] = 0;                              // Replace it with \0
    h(i+1, j);
    h(i-1, j)
    h(i  , j+1);
    h(i  , j-1);
}
f(
    int w,    //1st dimension of S
    int e,    //2nd dimension of S
    int u,    //1st dimension of G
    int v     //2nd dimension of G
    char** i, //Input S
    char** j, //Input G
    );
{
    x=w,y=e,s=i,g=j;
    for(o=0; o<x; o++)                        // Replace all surrounding spaces using floodfill
    {
        h(o, 0);
        h(o, y-1);
    }
    for(p=0; p<y; p++)
    {
        h(0,   p);
        h(x-1, p);
    }
    w = 0;
    for(o=0; o<=u-x; o++)                     // Main O(w*e*u*v) matching process
        for(p=0; p<=v-y; p++) {
            t=1;
            for(c=0; c<x; c++)
                for(d=0; d<y; d++)
                if(s[c][d]*(s[c][d]-g[c+o][d+p]))
                    t=0;
            w+=t;
        }
}

```

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