title: Military projection of a cube

text:
# Question
Title: Military projection of a cube
### Challenge closed, the shortest answer has been acccepted.

A military projection is a projection where all lengths and the angles in the X-Z plane remain unattuned.

Your task is to print a cube in military projection using `/`, `|`, `\`, `-`, and any whitespaces you want, given any integer greater than zero as it's side length. You can leave sides out that are not visible to the human eye. Here are some examples:

```
  /-\
 /   \
|\   /| Side length:
| \ / | 2
 \ | /
  \|/

     /-\
    /   \
   /     \
  /       \
 /         \
|\         /|
| \       / | Side length:
|  \     /  |
|   \   /   | 5
|    \ /    |
 \    |    /
  \   |   /
   \  |  /
    \ | /
     \|/

 /-\  Side length:
|\ /|
 \|/  1

```

(Printing the side lengths is not required.)

For the uppermost corner you must use the dash. As you can see, all sides are equal in length (when measured in characters). You may use any kind of spacing you wish, and omit any characters that don't change the appearance of the cube.

This is , so the shortest answer in bytes wins!

# Answer
> 3 votes
# Charcoal, 19 bytes

```
Ｎθ←¹↙θ↓θ→↘θ↑↑θ←↖θ‖Ｂ

```

Try it online!

# Answer
> 1 votes
# Python 2.7, ~~198~~ ~~185~~ 172 bytes

```
i=n=input();x=1;s,l,r,p='/|\ '
print p*n+'/-\\'
exec'x+=2;i-=1;print p*i+s+p*x+r;'*~-n+'i-=2;'+'i+=1;print l+p*i+r+p*x+s+p*i+l;x-=2;'*n+'print(n-i)*p+r+p*i+l+p*i+s;i-=1;'*n

```

Try it online!

Immense scope for golfing. I'm missing something out here, most probably!

Edit 1: -13 bytes: That's a start

Edit 2: -13 bytes: courtesy Erik the Outgolfer

# Answer
> 0 votes
# SOGL V0.12, ~~39~~ ~~38~~ ~~34~~ 33 bytes

```
∫:┘ž}³№↕≥++┌.I1ž.┐∙:.2+.Iž0.I╬5╬⁷

```

Try it Here!

Explanation:

```
∫   }                              for 1-indexed range in the input
 :                                   duplicate current index
  ┘ž                                 at [index; index] in POP (by default the input, but in the 1st cycle it gets overwritten) insert a "\"
     ³                             triplicate that array of a big diagonal
      №↕                           mirror/reverse one of those vertically
        ≥                          put that at the stacks bottom
         ++                        join the three items together, resulting in the 3 diagonal lines of the result
           ┌.I1ž                   insert a dash at coordinates [input+1; 1] insert the dash
                .┐∙                get an array of vertical bars with the size of the input (aka a vertical bar)
                   :               duplicate that
                    .2+.Iž         at postition [input+2; input+1] insert the 2nd vertical bar in the 1st (resulting in the required vertical bars the correct distance apart)
                          0.I╬5    at position [0; input+1] insert the vertical bars without overwriting spaces; as the position numbers are 1-indexed this extends the array left
                               ╬⁷  palindromize horizontally, mirroring the required characters and with 1 overlap

```

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


title: remove duplicates from array

text:
# Question
Title: remove duplicates from array
You have given an array from which we need to remove duplicates.

Rules:

1. First or immediate duplicates gets removed first.
2. Array contains natural numbers `a[i]>0 for i>=0`
3. no. of elements in the array is greater than 1 i.e. `n>1`

e.g.

```
{1,2,3,4,5,5,4,6,6,7,8}=> {1,2,3,7,8}
{1,2,3,3,4,5,6,7,7,8} => {1,2,4,5,6,8}
{1,1,3,3,4,4,6,6}=>{}
{4,2,6,8,3,1,1,3,8,6,2,4}=>{}
{6,6,6,1}=>{6,1}

```

Only adjacent duplicate elements like `[1, 2, 2, 1]` are removed, but not `[1, 2, 1, 2]`. This process is repeated until no further modifications are made.

For winning criteria is the one which gives the fastest result.

# Answer
# Python 2, 201 bytes

```
array = input()
index = 0
while index < len(array) - 1:
	if index >= 0 and array[index] == array[index + 1]:
		array = array[:index] + array[index + 2:]
		index -= 1
		continue
	index += 1
print(array)

```

Try it online!

Optimizations thanks to Mr. Xcoder
> 1 votes

---
Tags: array, fastest-code, fastest-algorithm, algorithm
---


title: Word Chain Reloaded

text:
# Question
Title: Word Chain Reloaded
This is a variant of Play the word chain and Building a long chain of words .

---

The input is a non-empty list of unique words at least 2 chars long made of characters in \[a-z\]. You need to output the length of the longest possible chain, where each subsequent word starts with the last letter of the previous word. You can start with any word on the list.

Another twist is that you are allowed to repeat any single word on the list. However, you can not repeat any two-word block. For example, `cat->tac->cat` is allowed, but `cat->tac->cat->tac` is not, because you repeated a two-word block (`cat->tac`). Also, you can not use the same word twice in a row (e.g. `eye->eye`).

## Examples:

* `cat dog tree egg` =\> 3 (cat-\>tree-\>egg)
* `new men ten whim` =\> 5 (ten-\>new-\>whim-\>men-\>new)
* `truth fret heart his` =\> 5 (fret-\>truth-\>heart-\>truth-\>his)
* `we were stew early yew easy` =\> 9 (stew-\>were-\>early-\>yew-\>were-\>easy-\>yew-\>we-\>easy)
* `tac cat tac cot tac can` =\> 6 (tac-\>cat-\>tac-\>cot-\>tac-\>can)

(Let me know if I made a mistake on any of these examples or if you come up with more.)

# Answer
> 3 votes
# Python 3, 150 149 145 bytes

```
def f(d):
 a=[[w]for w in d]
 while a:b=a[0];a=[f+[l,y]for*f,l in a for y in{*d}-{b for a,b in zip(f,f[1:])if a==l}if l[-1]==y[0]]
 return len(b)

```

Try it online!

The idea for constructing successively longer paths (or in this case trails) until none longer could be created was directly inspired by grc's answer on the Play the word chain question.

# Answer
> 1 votes
# Haskell, ~~131~~ 141 bytes

Basically the brute force approach.. The idea is to generate all possible *domino pieces*, permute them, check if it's a valid combo and maximize the whole thing. The time complexity is ridiculous, the 4th test case already takes ~4s on my PC and on the TIO it doesn't seem to work!

```
import Data.List
p w=2+maximum[length$takeWhile(\(x,y)->x!!1==y!!0)$zip p$tail p|p<-permutations[[a,b]|(a,b)<-(,)<$>w<*>w,a/=b,last a==b!!0]]

```

Try it online!

### Ungolfed

```
p w = maximum
  [ 2 + length c | p <- permutations [ [a,b] | (a,b) <- (,)<$>w<*>w
                                             , a /= b
                                             , last a == head b
                                     ]
                 , c <- [ takeWhile (\(x,y) -> x!!1 == y!!0) $ zip p (tail p) ]
  ]

```

*Edit*: Changed from Lambdabot to bare Haskell but saved a few bytes by golfing it, such that it's still less than `145` bytes :)

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


title: lastIndexOf in CJam

text:
# Question
Title: lastIndexOf in CJam
For the question Find the highest unique digit , here is my answer :

```
9A,sqfe=W%X#-

```

At the end I am essentially trying to achieve a lastIndexOf. I do that by reversing my array, using indexOf, and subtracting from 9. This adds 4 (`9` `W` `%` `-`) extra bytes to get from indexOf to lastIndexOf.

Furthermore, if I didn't know my array was length 10 the code would be even longer, and secondly, this code returns `10` when indexOf is `-1` which may not be acceptable in many situations.

Any suggestions on a shorter way to do the lastIndexOf operation (generally or just as needed for this challenge)?

# Answer
> 2 votes
Splitting is sometimes a good way to do this. E.g.

```
e# Stack: ... haystack needle
a/);S*,

```

With variants, such as removing the `a` if both needle and haystack are strings.

# Answer
> 0 votes
# 9 bytes

```
_,(@@W%#-

```

Try it online!

You must have `...element list` exactly like this in the stack. If `W` doesn't contain `-1` you must replace it with something that does evaluate to `-1`.

---
Tags: tips, cjam
---


title: Logical Order of Operations

text:
# Question
Title: Logical Order of Operations
## Task

Given an input, evaluate it as a mathematical equation following the order of operations.

But, instead of the using PEMDAS, we drop the parentheses and exponentiation and introduce spaces - SMDAS - spaces, then multiplication & division, then addition & subtraction.

### How does that work?

Every operator with more spaces around it gets more precedence - but that can change from one side to the other. Usual precedence test - `2+2*2` still gets evaluated to 6 - so does `2 + 2*2` \- which would be spelled out like `two .. plus .. two-times-two`, but `2+2 *2` or `2+2 * 2` would equal 8 - `twoPlusTwo .. times two`.

So, from any operator to any side every operator and number with less spaces can be grouped as in parentheses and then calculated as normal.

Alternatively, you can think of it as spaces around operators dropping the operator lower in precedence, or if the spaces are different on each side, drop the precedence on each side differently.

## Examples

```
input = output
2+2*2 = 6
2+2-2 = 2
2+12/6 = 4
228+456/228 = 230
2+0*42 = 2
73-37-96+200 = 140

2+2 * 2 = 8
5*6  +  7*8   -3  *5 = 415
4+4*4+ 4*4-4*2  /  4*4-2 = 2
228+456 /228 = 3
2+2 * 3-6 * 4/2 + 4*3  +  1000 / 5*5 / 5-3  +  1 = 9
2+0 * 42 = 84
5*5 *7-1 = 174

```

## Notes

* The input will always be valid - it will always contain at least 2 numbers, separated by a sign (`-+/*` (for which you may use alternatives such as  or `÷`))
* The input will never end or start in spaces.
* There will never be unary subtraction - `-4*-6`.
* There will never be division by zero.
* There may be negative integers in the process but never in the output.
* Division is only required to work for integers.
* Floating-point inaccuracies at any step of the process are fine.
* This is , shortest answer per language wins!

# Answer
> 16 votes
# Japt, 15 bytes

```
OvUr" +%d"_rS'(

```

Test it online!

### How it works

This challenge was practically made for Japt. I shall attempt to explain how:

Japt is basically a shortened version of JavaScript. In fact, after making some changes to the code ("transpiling" to JS), it is evaluated directly as JavaScript. What comes in handy here is that a space in Japt becomes `)` in JavaScript (a feature I occasionally regret adding, as it makes it hard to write "ungolfed" Japt code), and missing parentheses are automatically added.

What this all means for this challenge is that we can obtain the correct result simply by changing all spaces after an operator (before a number) to left-parentheses:

```
5*6  +  7*8   -3  *5    Original string
5*6  +((7*8   -3  *5    Japt code that evaluates to the correct number

```

When transpiled to JS, the changes mentioned above are made, which results in this:

```
     5*6  +((7*8   -3  *5    Japt code
(((((5*6))+((7*8)))-3))*5    transpiled JS code

```

The JS code is then evaluated, which gives the expected result.

```
OvUr" +%d"_rS'(    Implicit: U = input string
  Ur" +%d"         Replace each match of / +\d/ in U with
          _rS'(      the match with each Space replaced with a '('.
Ov                 Evaluate the result as Japt.
                   Implicit: output result of last expression

```

# Answer
> 3 votes
# , 59 bytes

```
òÍ ¨Ä*[+*¯-]©/)±
Í¨[+*¯-]Ä*© /±(ò
Ïò])|é(kòJïò[(Á)jòHDi="

```

Try it online!

I'm looking into golfing this down more later. The idea is that it turns spaces on the left of an operator into `)` and `(` on the right, the surrounds with appropriate `()` to make all parens match, and calculates the line. Mostly my regexes need work:

```
 \(\D*[+*\/-]\)/)\1
\([+*\/-]\D*\) /\1(

```

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

```
f=
s=>(s=s.replace(/./g,c=>c>` `?(b=1/c?`)`:`(`,c):b),g=c=>s.split(c).length,eval(`(`.repeat(g`)`)+s+`)`.repeat(g`(`)))
```

```
<input><input type=button value=Evaluate onclick=o.textContent=``,o.textContent=f(this.previousSibling.value)><pre id=o>
```

Changes the spaces into the appropriate brackets, then adds matching brackets on each side (at least one pair of which will be redundant, not that it matters) and evaluates the result.

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


title: Cover a set with multiples

text:
# Question
Title: Cover a set with multiples
Lets take a set of integers greater than 1 and call it **X**. We will define **S(i)** to be the set of all members of **X** divisible by **i** where **i \> 1**. Would like to choose from these subsets a group of sets such that

* Their union is the set **X**
* No element of **X** is in two of the sets.

For example we can regroup `{3..11}` as

```
      {3,4,5,6,7,8,9,10,11}
S(3): {3,    6,    9,     }
S(4): {  4,      8,       }
S(5): {    5,        10,  }
S(7): {        7,         }
S(11):{                 11}

```

Some sets cannot be expressed in this way. For example if we take `{3..12}`, `12` is a multiple of both 3 and 4 preventing our sets from being mutually exclusive.

Some sets can be expressed in multiple ways, for example `{4..8}` can be represented as

```
      {4,5,6,7,8}
S(4): {4,      8}
S(5): {  5,     }
S(6): {    6,   }
S(7): {      7, }

```

but it can also be represented as

```
      {4,5,6,7,8}
S(2): {4,  6,  8}
S(5): {  5,     }
S(7): {      7, }

```

## Task

Our goal is to write a program that will take a set as input and output the smallest number of subsets that cover it in this fashion. If there are none you should output some value other than a positive integer (for example `0`).

This is a question so answers will be scored in bytes, with less bytes being better.

## Tests

```
{3..11}       -> 5
{4..8}        -> 3
{22,24,26,30} -> 1
{5}           -> 1

```

# Answer
# Python 2, 167 bytes

```
lambda a:([q for q in range(a[-1])if a in[sorted(sum(j,[]))for j in combinations([[p for p in a if p%i<1]for i in range(2,1+a[-1])],q)]]+[0])[0]
from itertools import*

```

Try it online!

-9 bytes thanks to Zacharý
-4 bytes thanks to Mr. Xcoder
-2 bytes by using lists instead of sets
-5 bytes by using `a in [...]` rather than `any([a == ...])`.
-2 bytes thanks to Mr. Xcoder
-8 bytes by merging statements
-5 bytes thanks to Mr. Xcoder
-7 bytes thanks to Mr. Xcoder / Zacharý
+7 bytes to fix bug
-1 byte thanks to ovs

### note

This is extremely slow for larger maximum numbers because it is in no way optimized; it did not within 2 minutes on Mr. Xcoder's device for `[22, 24, 26, 30]`.
> 6 votes

# Answer
# Clingo, 51 bytes

```
{s(2..X)}:-x(X).:-x(X),{s(I):X\I=0}!=1.:~s(I).[1,I]

```

### Demo

```
$ echo 'x(3..11).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(3) x(4) x(5) x(6) x(7) x(8) x(9) x(10) x(11) s(3) s(4) s(5) s(7) s(11)
Optimization: 5
OPTIMUM FOUND

Models       : 1
  Optimum    : yes
Optimization : 5
Calls        : 1
Time         : 0.003s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.010s
$ echo 'x(4..8).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(4) x(5) x(6) x(7) x(8) s(3) s(4) s(5) s(7)
Optimization: 4
Answer: 2
x(4) x(5) x(6) x(7) x(8) s(2) s(5) s(7)
Optimization: 3
OPTIMUM FOUND

Models       : 2
  Optimum    : yes
Optimization : 3
Calls        : 1
Time         : 0.001s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.000s
$ echo 'x(22;24;26;30).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(22) x(24) x(26) x(30) s(5) s(8) s(22) s(26)
Optimization: 4
Answer: 2
x(22) x(24) x(26) x(30) s(3) s(22) s(26)
Optimization: 3
Answer: 3
x(22) x(24) x(26) x(30) s(2)
Optimization: 1
OPTIMUM FOUND

Models       : 3
  Optimum    : yes
Optimization : 1
Calls        : 1
Time         : 0.004s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.000s
$ echo 'x(5).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(5) s(5)
Optimization: 1
OPTIMUM FOUND

Models       : 1
  Optimum    : yes
Optimization : 1
Calls        : 1
Time         : 0.001s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.000s

```
> 5 votes

# Answer
# Mathematica, 105 bytes

```
Length@Select[Subsets@Table[Select[s,Mod[#,i]==0&],{i,2,Max[s=#]}],Sort@Flatten@#==Sort@s&][[1]]~Check~0&

```

***Try it online***
copy and paste the code with ctrl+v,
paste the input at the end of the code,
hit shift+enter to run

**input**

> \[{3,4,5,6,7,8,9,10,11}\]

takes a list as input
outputs 0 if there are none
> 4 votes

# Answer
## Haskell, 136 bytes

```
import Data.List
f l|m<-maximum l=(sort[n|(n,c)<-[(length s,[i|j<-s,i<-[j,2*j..m],elem i l])|s<-subsequences[2..m]],c\\l==l\\c]++[0])!!0

```

Try it online!

How it works

```
f l     =                           -- input set is l
   |m<-maximum l                    -- bind m to maximum of l
       [   |s<-subsequences[2..m]]  -- for all subsequences s of [2..m]
        (length s, )                -- make a pair where the first element is the length of s
            [i|j<-s,i<-[j,2*j..m],elem i l]
                                    -- and the second element all multiples of the numbers of s that are also in l
     [n|(n,c)<-       ,c\\l==l\\c]  -- for all such pairs (n,c), keep the n when c has the same elements as l, i.e. each element exactly once
   sort[ ]++[0]                     -- sort those n and append a 0 (if there's no match, the list of n is empty)
 (     )!!0                         -- pick the first element

```

Take a lot of time for `{22,24,26,30}`.
> 4 votes

# Answer
# Jelly, ~~38~~ ~~35~~ ~~34~~ ~~33~~ ~~31~~ ~~28~~ ~~25~~ ~~24~~ ~~23~~ ~~20~~ 19 bytes

```
ṀḊŒPð%þ@⁹¬Sḟ1ðÐḟL€Ḣ

```

-5 bytes thanks to Leaky Nun

Try it online!

I **think** the third test case works, but it is very slow. `0` is outputted when there are no solutions.

Explanation (might have gotten this explanation wrong):

```
ṀḊŒPð%þ@⁹¬Sḟ1ðÐḟL€Ḣ     (input z)
ṀḊ                      - 2 .. max(z)
  ŒP                    - powerset
    ð                   - new dyadic chain
     %þ@⁹               - modulo table of z and that
         ¬              - logical not
          S             - sum
           ḟ1           - filter out 1's
             ðÐḟ        - filter out elements that satisfy that condition
                L€      - length of each element
                  Ḣ     - first element

```
> 3 votes

# Answer
# Julia, 91 bytes

```
x->(t=[];for i in x z=findfirst(x->x==0,i%(2:maximum(x)));z∈t?1:push!(t,z) end;length(t))

```
> 2 votes

---
Tags: code-golf, set-partitions
---


title: Is this any number?

text:
# Question
Title: Is this any number?
*Inspired (like 2 others) by this chat message. (and to some extent, my CMC)*

Given a string as an input, your task is to check whether or not that string is a number.

## What is a number?

This is a list of all input formats that are "numbers":

* Integers: An integer is a string made entirely of characters from `1234567890`, without any other character e.g. `152`
* Floats: A float is a integer with 1 (no more, no less) decimal points (`.`) in the middle of the number. A decimal point must always be preceded and followed by a number e.g. `1.0` or `3.14`
* Complex: A complex number is a number that follows the format `a+bj` where `a` and `b` are numerical values. The plus sign can also be a minus sign e.g. `1+10j` or `143-1j`. If it saves bytes (or you want to), you may use `i` instead of `j`.
* Longs: A long is any number that would be classed as an integer or a float, with an `L` at the end e.g `1325963L`
* Hexadecimal: A hexadecimal number is a number which consists entirely of characters in `1234567890abcdef`. Upper case characters are valid hex, but only when used consistently e.g. `10a` or `afa` not `A5c`
* Scientific: A scientific number is a number which consists of a run of digits (`1234567890.`) followed by an `e` followed by a run of digits, optionally preceded by a `-`. A `E` may also be used.

Any of these 5 may also be preceded by a minus sign (`-`) but any whitespace in the number causes it to no longer be a number e.g. `-3.5 + 2i` isn't a number. Longs may not be hexadecimal but may be floats

You must output 2 distinct values (preferably truthy and falsy but you may choose) for inputs that are either numbers as defined above, or not.

## Test Cases

These should result in truthy

```
10
-9.34
-3.5+2j
ab1
100000L
3.14159L
-73e-7
7E53C80
1.2e3
12E3.4

```

And these should be falsy

```
abcdefghijklmnop
10.10.10
2569LL
10L+9j
8+45io
4aE3
3.
.3

```

Now because small numbers are easier to work with, this is a so shortest code, *in bytes*, wins!

# Answer
> 4 votes
# SOGL V0.12, ~~53~~ ~~52~~ 50 bytes

```
O[►~hΘP█⁵\↔<sK⁹>¼⅝┘d⁾Δo≡7ξδ¾▓↑ΧGj4<eu╝t┼Pπ»‘øβ!d!-

```

Try it Here! or test all test cases (first number indicates amount of test cases)

based on a regex - `^(-?\d+((\.\d+|)(L|e-?\d+(\.\d+|)|\+\d+(\.\d+|)j|)|)|[A-F\d]+)$`

# Answer
> 2 votes
# Javascript, ~~72~~ ~~71~~ 65 bytes

*saved one byte thanks to @Cowsquack* *saved 6 bytes thanks to @dzaima*

```
a=>/^(-?\d+((\.\d+|)(L|e-?\d+(\.\d+|)|\+\d+(\.\d+|)j|)|)|[A-F\d]+)$/.test(a)

```

JS port of @dzaima's answer. Credit to @dzaima for the regex.

# Answer
> 1 votes
# Python 3, ~~290~~ ~~136~~ 105 bytes

Python port of @dzaima's answer. All credit to @dzaima for the regex :)

```
lambda s:re.match('^(-?\d+((\.\d+|)(L|e-?\d+(\.\d+|)|\+\d+(\.\d+|)j|)|)|[A-F\d]+|[a-f\d]+)$',s)
import re

```

Try it online!

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


title: Team of The Hill!

text:
# Question
Title: Team of The Hill!
This challenge was inspired by @HelkaHomba's excellent challenge Red vs. Blue - Pixel Team Battlebots. That challenge was probably the best one I've seen on this site. Ever.

My challenge is still a lot different, but @HelkaHomba deserves credit for the inspiration.

# Overview

This is a team where your team wins by having all players alive on your team. In other words, last team standing wins. Draws will be re-done.

You are on a board. You know your position *on the first round (tick 0).* You also know who is in the area around you:

In this case, you are all alone (or so you think) with no-one around you. You can see surrounding items in the first argument to your `ontick` handler. More about the API later.

# Your team

Your team is determined by your user ID. To find that out, click on your profile picture:

Then find your user ID in the address bar:

**If it is odd, you are on the blue team.**

**If it is even, you are on the red team.**

You're welcome for the hand-drawn circles.

# Your (bot's) name

Your bot's name starts with the first letter of your team ("r" or "b"). It must match the regex `/^(r|b)[A-Za-z_-]$/`. Other than that, you can pick your bot's name. Please don't use an already-existing one.

# Starting

The red players will start near the top of the map, and the blue will start near the bottom. You are given special info on the first tick (turn) in the `environment` parameter for the `ontick` function. I recommend storing that. See the API for details.

# On your turn

Turn order is randomized initially, but then stays the same.

## Turn actions

You may only do one action per turn.

* ### Move

When you would like to move, you call `this.move(num)` in the API. `num` is the cell you would like to move to:

The relative locations of the numbers you can move to are stored in the global constant `threeByThree`:

```
[
    [0, 1, 2],
    [3, undefined, 4],
    [5, 6, 7]
]

```

If you move into a wall, or another player, *nothing happens.*

* ### Rotate

To rotate, you call `this.rotate(num)`. Num is the direction you want to rotate:

Rotation is absolute.
* ### Kill

If another player (from another team) is in the cell you are facing, you can call `this.kill()` and kill them. If there is no-one there, or they are on your team, this does nothing. Example:

If you are turned to `0`, you can kill green. If you are are turned to 1, you can kill blue. If you are are turned to 2, you can kill orange. If you are are turned to 3, you can kill yellow.
* ### Bomb

Bombing kills *all players **including you and teammates*** in the 9 squares around you. Example:

**Why would you ever want to do this?** Kamikaze. If there are more players *not on your team* in the 9 cells around you then there are on your team, you might consider bombing. (I suggest you notify your comrades first!)
* ### Place a landmine

This creates a death square for others not on your team. When you place a land mine, you also move so you don't step on it. You call `this.landMine(num)` where num is the square you want to go to. Example:

Then you call `this.landMine(4)`:

See that "M"? It's a landmine. Others can see it...for now. Anyone, even those not on your team, can see a landmine on the tick it is placed. But after that tick is over, *no-one, not even you* can see it. But it will explode as soon as an enemy walks over it. Example:

Blue moved on your landmine, and BOOM! You just got another kill.

For every 2 kills you get (from direct killing or land mines), you get 1 extra landmine to place. You also get one at the start.
* ### Dig

When you dig, you look for landmines in a 5x5 area centered around you. This does not show the team of the bot that placed the landmine. (Remember that you can't be killed by a landmine placed by someone on your team.) For example, if this was the grid around you:

Then the return value of `this.dig()` would be:

```
[undefined,undefined,undefined,true,undefined,
undefined,undefined,undefined,undefined,undefined,
undefined,undefined,undefined,undefined,
undefined,undefined,true,undefined,undefined,
true,undefined,undefined,undefined,undefined]

```

The array indexes are from starting in the top left, going right, than down, not including yourself:

There are 23 in total, and their relative locations are stored in the global constant `fiveByFive`:

```
[
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [10, 11, undefined, 12, 13],
    [14, 15, 16, 17, 18],
    [19, 20, 21, 22, 23]
]

```

Note that dig reveals mines placed on previous ticks, unlike `aroundMe`.

## Communication

When you want to talk to someone, you call `this.sendMessage(recipients, team, data)`. The data can be *anything you want,* and you can send it to *anyone you want, even players on other teams.* This can be used to trick poorly-programmed bots, but all players can see who sent a message and who's team they are on.

Example:

### Send something to a bot named "redisbest":

```
this.sendMessage("redisbest", undefined, "Hi!");

```

### Send something to a bot named "redisbest" and "blueiscool":

```
this.sendMessage(["redisbest", "blueiscool"], undefined, {hello: "there"});

```

### Send something to the entire red team

```
this.sendMessage(undefined, "red", {hello: "red"});

```

### Send something to *everyone*

```
this.sendMessage(undefined, "*", {hello: "everyone"});

```

### Send something to the entire red team and a bot named "blueiscool":

```
this.sendMessage("blueiscool", "red", {hello: "bots"});

```

## API

### Your code must consist of a *single call* to the `createBot` function. Nothing else. Sample code:

```
createBot({
    ontick: function(environment) {
        return new Promise((resolve, reject)=>{
            this.move(0);//example
            resolve();//please call this when you are done
        });
    },
    onmessage: function(data, from, fromBot) {
        console.log("onMessage: " + this.name + " from " + this.team + " got message ", data, " from " + from + ", on team " + fromTeam);
        this.sendMessage(["bot", "otherbot"], "team", "some data");
    },
    team: "red",//your team
    name: "rmyteamname",//team name must begin with the first letter of your team's name
    onkill: function(){
        //say goodbye
    }
});

```

(You are free to copy-paste this. Just modify it for your team, etc.)

### Methods

* `ontick(environment)`

Called when it's your turn. Must return a `Promise` that resolves in 1 second or less or it will be ignored. This is for performance reasons and has the nice side-effect of not having the tab hang.

**`this` (when in ontick)**

+ `landMines` How many land mines you have left. *The more kills you have, the more land mines you get.* For every 2 bots you kill, you get 1 more landmine. You also get 1 to start.
    + `direction` The direction you are facing.
    + `storage` Storage that persists between calls to `onTick` and `onMessage`. An empty object at start. Modify for any purpose, but make sure it's an array or object always to ensure it persists correctly.
    + `move(num)` Move to the specified position. Does nothing if invalid. See above for details.
    + `rotate(num)` Rotate to the specified position. Does nothing if invalid. See above for details.
    + `kill()` Kills the player you are facing, if exists and is not on your team. See above for details.
    + `bomb()` Kills anyone in the 9 squares around you, including yourself.
    + `landMine(num)` Places a land mine where you are, and then moves to the specified position. Does nothing if invalid `num` or you have none left. See above for details.
    + `dig()` **new!** Returns an array of info about the landmines in a 5x5 area centered around you. See above for details.
    + `sendMessage(recipients, team, data)` `recipients` can either be a single bot (string), an array of bot, or `undefined`/`null`. It is who you would like to send the message. `team` is a string of the team you would like to send the message. Use `"*"` to send a message to everyone. `data` is anything that can be passed to a JS function. It is send to the recipients. If it is an object or array, it is *passed by reference*, so you and the recipient(s) can save that to their `storage` and any modifications to the object affects both bot's copies. Note that recipients that are in *either* the list of bots, the exact bot specified in the string, *or* a bot on the team you specified, it will get the message.

**`environment`**

*On the first tick*

* `x`: Your player's x-position
* `y`: Your player's y-position
* `gridWidth`: The width of the grid (in cells)
* `gridHeight`: The height of the grid (in cells)

*On all ticks*
* `aroundMe`: An array of players and landmines. The players are objects that look like `{name: "bot name", team: "bot team"}`, and the landmines are `{team: "team of bot who placed mine"}`. The indexes of the array:

Note that landmines placed on a tick *other than* the current one will not be shown.

**`aroundMe` example:**

Let's say this is the grid (you are red):

Your `aroundMe` will look like this:

```
[
    {name: "bexamplebluebot", team: "blue"},
    undefined,//sparse array, nothing in index 1
    undefined,//there is technically a landmine here, but it wasn't placed this tick, so it is not shown
    undefined,//nothing in 3
    {name: "yexampleyellowbot", team: "yellow"},
    {team: "red"},//this is a landmine, you can tell is not a bot because it has no name. mines have the team name of the player they were placed by. This mine was placed this tick, otherwise you couldn't see it
    //nothing else after index 5, so the array's length is 5.
]

```

The indexes of the array are explained here:

Your bot effectively sees this:

* `onmessage(data, fromBot, fromTeam)`

**`this` (when in onmessage)**

+ `sendMessage(recipients, team, data)` Standard message sending function.
    + `storage` Standard storage.

`data` The data sent from the sender. `fromPlayer` The player the message was sent from. `fromTeam` The team the message was sent from.
* `onkill()`

**`this` (when in onkill)**

+ `sendMessage(recipients, team, data)` Standard message sending function.

## Convenient (constant) global arrays:

### `threeByThree`:

```
[
    [0, 1, 2],
    [3, undefined, 4],
    [5, 6, 7]
]

```

Useful for passing data to the move function as well as interpreting `aroundMe`. See above.

### `fiveByFive` :

```
[
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [10, 11, undefined, 12, 13],
    [14, 15, 16, 17, 18],
    [19, 20, 21, 22, 23]
]

```

Useful for the `this.dig()` function in the `ontick` handler.

# Try it out!

The controller will be run from my machine on localhost for performance reasons, but you can use the CodePen to test your bot out.

Note that you must paste your code in the console and press `Enter` before you click run. You can paste in as many bots as you'd like. The "Test bots" are examples for you to test against. If you can beat or tie all of them, you have at least a decent bot.

# Submissions

## Rules

### Rules (enforced by the controller)

* Your main `ontick` code must not take more than 1 second. We don't want rounds to take forever. If your code takes \> 1 second, it will be stopped.
* If you attempt to do more than 1 action per turn, or do an invalid action (eg. `this.move(-1)` or moving into a wall), it will be ignored.
* More may come soon...

### Rules (enforced by me, can result in DQ)

* Don't *write* global variables (*reading is fine*).
* Your code must work in Nodejs (in case the controller is ported to Nodejs), so `JSON.parse(...)` is fine, but `alert()` is not.
* You are not allowed to call `createBot` or interfere with the controller in *any way*.
* Don't use someone's else's code without permission and significant changes. No copybots.
* Please, no loopholes!
* More may come soon...

## My bots

Here are some bots:

This bot randomly chooses an action. Well, it's a weighted random, but still pretty random. If you can *kill* this bot (it will eventually kill itself, that doesn't count), than you have at least a decent bot. Post it and see what happens!

```
createBot({
  ontick: function(environment) {
    return new Promise((resolve, reject)=>{
      if(Math.random() < 0.02){
        this.bomb();
      }else if(Math.random() < 0.1){
        this.kill();
      }else if(Math.random() < 0.3){
        this.rotate(~~(Math.random() * 4));
      }else{
        this.move(~~(Math.random() * 8));
      }
      resolve();
    });
  },
  team: "none",
  name: "xrandomness2",
  onkill: function(){
    console.log("Goodbye world... :(");
  }
});
```

My bots have a name beginning with "x" and a team of "none". You are welcome to use some of this code, but please do at least *some* modification. If you can't be bothered to at least tweak a number, you won't win.

## Formatting your submission

Please use this format:

```
# rmyamazingbot

    createBot({
        ontick: function(environment) {
            return new Promise((resolve, reject)=>{
                this.move(0);//example
                resolve();//please call this when you are done
            });
        },
        onmessage: function(data, fromTeam, fromBot) {
            console.log("onMessage: " + this.name + " from " + this.team + " got message ", data, " from " + from + ", on team " + fromTeam);
            this.sendMessage(["bot", "otherbot"], "team", "some data");
        },
        team: "red",//your team
        name: "rmyteamname",//team name must begin with the first letter of your team's name
        onkill: function(){
            //say goodbye
        }
    });

Long, but cool explanation...

```

# Feature requests, bugs, questions, etc?

Comment below! Please check to see if there is already a comment with that. If there is one already, upvote it.

# Want to talk to your team?

Use the chat rooms for red and blue.

# Language

Currently, only JS and something that compiles to JS is supported, but if you know of a way to get other languages to work with Nodejs I would be happy to port the controller to Nodejs.

# Final notes

## Strategy ideas

Help your team! Creating a bot that is designed to help another bot and work together. This strategy worked well for Red vs. Blue - Pixel Team Battlebots

## Rep seekers

I will accept the highest voted answer on the winning team. Keep in mind that earlier answers tend to get more votes, but their weaknesses are more likely to be found and exploited.

Also, if you answer soon, you might get the +100 bounty.

# Answer
# xscared (non-competing)

```
createBot({
    ontick: function(environment) {
        var reverse = [0, 1, 2, 3, 4, 5, 6, 7].reverse();
        return new Promise((resolve, reject)=>{
            (this.aroundMe || []).forEach((item,idx)=>{
                this.move(reverse[idx]);
                return resolve();
            });
            this.move(~~(Math.random() * 8));
            return resolve();
        });
    },
    onmessage: function() {
    },
    team: "none",
    name: "xscared",
    onkill: function(){
    }
});

```

Very scared of people. Goes away from the first person (or landmine) it sees. Otherwise, it moves randomly. Note that this is not competing, just an example. Try to beat it!
> 7 votes

# Answer
# backup, a blue bot

As warned in chat, I never wrote anything in javascript in my life, so if you find any mistake, please tell me! (Thanks to @programmer5000 for already helping me with it)
The concept of this bot is that it communicates with other bots from the same team and send them its position along with a map of the mines it found. It tries to join the closest blue bot (if one send its position data \[given as an \[x,y\] array\]), and stays near it (with its back to it as much as possible), killing approaching red bots or looking ahead for mines.

```
createBot({
    team: 'blue',
    name: 'backup',
    ontick: function(environment) {
        return new Promise((resolve, reject) => {
            //if (typeof this.x != "undefined") this.storage['position'] = [this.x, this.y];
            if (typeof environment.x != "undefined") this.storage['position'] = [environment.x, environment.y]; //Modified according to @WasteD
            if (typeof this.storage['map'] == "undefined") { //Create empty map
                var map = [[]];
                //for(i=0;i<this.gridHeight;i++) map[i]=[];
                for(i=0;i<environment.gridHeight;i++) map[i]=[]; //Modified according to @WasteD
                this.storage['map'] = map;
            }
            var blue = []
            var red = []
            var x = this.storage['position'][0];
            var y = this.storage['position'][1];
            var dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
            var dy = [1, 1, 1, 0, 0, 0, -1, -1, -1]
            (this.aroundMe || []).forEach((item, idx) => { // Update map and list positions of surrounding blues and reds
                if (item && item.team == 'red' && typeof item.name != "undefined") red += idx;
                if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx[idx]][y+dy[idx]] = 'M';
                if (item && item.team == 'blue' && typeof item.name != "undefined") blue += idx;
            });
            this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']}); //Send to buddies my position and the map
            if (red.indexOf([1, 4, 6, 3][this.direction]) > -1) this.kill() ; //If red guy is in front of
            else if (red.indexOf([1,4,6,3]) > -1) this.rotate(red.indexOf([1,4,6,3])); //If red guy is next but not in front of
            else if (blue.indexOf(3) > -1){ //If blue buddy on the left
                if (blue.indexOf(4) > -1){ //If another one is on the right
                    if (blue.indexOf(1) > -1 && this.direction != 2) this.rotate(2); //...and a third one at the top
                    else var digging = this.dig();
                    }
                else if (this.direction != 1) this.rotate(1);
                else var digging = this.dig();
            }
            else if (blue.indexOf(1) > -1){
                if (blue.indexOf(6) > -1 && this.direction != 3) this.rotate(3);
                else if (this.direction != 2) this.rotate(2);
                else var digging = this.dig();
            }
            else if (blue.indexOf(4) > -1){
                if (this.direction != 3) this.rotate(3);
                else var digging = this.dig();
            }
            else if (blue.indexOf(6) > -1 && this.direction != 0) this.rotate(0);
            else if (blue.indexOf([0,2]) > -1){ //If no blue next to me but one in diagonal, move next
                this.move(1);
                this.storage['position'][1] = y+1; //Update position
            }
            else if (blue.indexOf([5,7]) > -1){
                this.move(6);
                this.storage['position'][1] = y-1;
            }
            else if (typeof this.storage['other_blue'] != "undefined"){ //Check if buddies said where they were, try to go near the closest one
                var dmin = 99999;
                var pos = []
                (this.storage['other_blue'] || {}).forEach((item, idx) => {
                    var d = Math.sqrt(Math.pow(item['position'][0]-x,2) + Math.pow(item['position'][1]-y,2));
                    if (d < dmin){
                        dmin = d;
                        pos = item['position'];
                        }
                });
                if (pos[0]-x > 0){
                    this.move(4);
                    this.storage['position'][0] = x+1
                }
                else if (pos[0] < 0){
                    this.move(3);
                    this.storage['position'][0] = x-1
                }
                else if (pos[1] > 0){
                    this.move(1);
                    this.storage['position'][1] = y+1
                }
                else{
                    this.move(6);
                    this.storage['position'][1] = y-1
                }
            }
            else var digging = this.dig();
            if (typeof digging != "undefined"){ //Check out surroundings if dig() was played and update the map accordingly
                var dx2 = [-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2];
                var dy2 = [2,2,2,2,2,1,1,1,1,1,0,0,0,0,0,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2];
                (digging || []).forEach((item, idx) => {
                    //if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M';
                    if (item) this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M'; //previously misread what dig() returned
                });
            }
            resolve();
        });
    },
    onmessage: function(data, fromTeam, fromBot) {
        if (typeof data['position'] != "undefined" && fromTeam == 'blue') { //If position sent by a blue bot
            if (typeof this.storage['other_blue'] == "undefined") this.storage['other_blue'] = [];
            for (i in this.storage['other_blue']){
                var found = false;
                if ('name' in i){
                    if (i['name'] == fromBot){
                        i['position'] = data['position'];
                        found = true; //Update if position already known from previous ticks
                        }
                }
            }
            if (!found) this.storage['other_blue'] += {'position':data['position'], 'name':fromBot}; //Add position if previously unknown
            this.sendMessage(fromBot, undefined, "roger.");
        }
    },
    onkill: function() {this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']});}
});

```
> 5 votes

# Answer
# Blue, blue, my world is blue

```
createBot({
    team: 'blue',
    name: 'blue-blue-my-world-is-blue',
    ontick: function(environment) {
        return new Promise((resolve, reject) => {
            var red = 0;
            // See who's around me
            (this.aroundMe || []).forEach((item, idx) => {
                if (item && item.team == 'red') red++;
            });
            // If surrounded, take one for the team
            if (red >= 6) this.bomb();
            else {
                // Translate direction into position
                var kill = [1, 4, 6, 3][this.direction];
                // Random values
                var move = Math.floor(Math.random() * 8);
                var nsew = Math.floor(Math.random() * 4);
                // Lay a landmine if possible
                if (this.landMines) this.landMine(move);
                // Kill if someone is in the way
                else if (this.aroundMe && this.aroundMe[kill] && this.aroundMe[kill].team == 'red' && this.aroundMe[kill].name) this.kill();
                else {
                    // Move somewhere if already in the requested direction
                    if (nsew == this.direction) this.move(move);
                    // Otherwise just rotate to the requested direction
                    else this.rotate(nsew);
                }
            }
            resolve();
        });
    },
    onmessage: function(data, from, fromBot) {},
    onkill: function() {}
});

```

Mostly random, but will bomb if surrounded, and favors checking around and killing over moving.
> 4 votes

# Answer
# Relaxed-Bomber

This bot searches for a spot with at least 1 free cell on each side then plants a mine. It camps on it until an enemy approaches. When someone draws near, he'll step back back and forth on his mine to bait the other bot on it. He'll also rotate and kill if needed. When he doesn't have any mine left, he'll seek refuge on the top-left corner with its back to the wall and retaliate if he's threatened.

No special teamplay here, apart from broadcasting his position to his team with `self` keyword.

```
createBot({
    team: 'red',
    name: 'relaxed-bomber',
    ontick: function(environment) {
        return new Promise((resolve, reject) => {
            if (typeof this.storage['dropped'] == "undefined") {
                this.storage['dropped'] = false;
                this.storage['covered'] = false;
                this.storage['baited'] = false;
            }
            if (typeof environment.x != "undefined" && typeof environment.y != "undefined") {
                this.storage['pos'] = [environment.x, environment.y];
            }
            if (typeof environment.gridWidth != "undefined" && typeof environment.gridHeight != "undefined") {
                this.storage['grid'] = [environment.gridWidth, environment.gridHeight];
            }
            var x = this.storage['pos'][0];
            var y = this.storage['pos'][1];
            var x0 = this.storage['grid'][0];
            var y0 = this.storage['grid'][1];
            var source = [1, 4, 6, 3];
            var dest = [6, 3, 1, 4];
            var rot = [0, 1, 2, 3];
            var movex = [-1, 0, 1, -1, 1, -1, 0, 1];
            var movey = [-1, -1, -1, 0, 0, 1, 1, 1];
            var action = false;
            if (this.landMines > 0) {
                var move = [false, false, false, false];
                var moveIndex = -1;
                if (x <= 0) { move[1] = true; }
                if (x >= x0 - 1) { move[3] = true; }
                if (y <= 0) { move[2] = true; }
                if (y >= y0 - 1) { move[0] = true; }
                if (move[0] && !move[1] && !move[2] && move[3]) { moveIndex = 0; }
                if (move[0] && !move[1] && !move[2] && !move[3]) { moveIndex = 1; }
                if (move[0] && move[1] && !move[2] && !move[3]) { moveIndex = 2; }
                if (!move[0] && !move[1] && !move[2] && move[3]) { moveIndex = 3; }
                if (!move[0] && move[1] && !move[2] && !move[3]) { moveIndex = 4; }
                if (!move[0] && !move[1] && move[2] && move[3]) { moveIndex = 5; }
                if (!move[0] && !move[1] && move[2] && !move[3]) { moveIndex = 6; }
                if (!move[0] && move[1] && move[2] && !move[3]) { moveIndex = 7; }
                if (moveIndex >= 0) {
                    this.storage['pos'] = [ x + movex[moveIndex], y + movey[moveIndex]];
                    this.move(moveIndex);
                } else {
                    this.storage['dropped'] = true;
                    this.storage['covered'] = false;
                    this.landMine(1);
                }
            } else {
                if (this.storage['dropped']) {
                    this.storage['dropped'] = false;
                    this.storage['covered'] = true;
                    this.storage['pos'] = [ x + movex[6], y + movey[6]];
                    this.move(6);
                } else if (this.storage['covered']) {
                    for (var i = 0; i < source.length; i++) {
                        if (typeof environment.aroundMe[source[i]] != "undefined" && typeof environment.aroundMe[source[i]].team != "undefined" && environment.aroundMe[source[i]].team == "blue" && typeof environment.aroundMe[source[i]].name != "undefined") {
                            this.storage['covered'] = false;
                            this.storage['baited'] = true;
                            this.storage['mine'] = this.storage['pos'].slice();
                            this.storage['reverse'] = source[dest[i]];
                            this.storage['pos'] = [ x + movex[dest[i]], y + movey[dest[i]]];
                            this.move(dest[i]);
                            action = true;
                        }
                    }
                    if (!action) {
                        this.dig();
                    }
                } else if (this.storage['baited']) {
                    for (var i = 0; i < source.length; i++) {
                        if (typeof environment.aroundMe[source[i]] != "undefined" && typeof environment.aroundMe[source[i]].team != "undefined" && environment.aroundMe[source[i]].team == "blue" && typeof environment.aroundMe[source[i]].name != "undefined") {
                            if (this.direction == rot[source[i]]) {
                                this.kill();
                                this.storage['baited'] = false;
                                action = true;
                            } else {
                                this.rotate(rot[source[i]]);
                                action = true;
                            }
                        }
                    }
                    if (!action) {
                        if (this.storage['mine'][0] == this.storage['pos'][0] && this.storage['mine'][1] == this.storage['pos'][1]) {
                            this.storage['pos'] = [ x + movex[this.storage['reverse']], y + movey[this.storage['reverse']]];
                            this.move(this.storage['reverse']);
                            this.storage['reverse'] = source[this.storage['reverse']];
                        } else {
                            this.storage['pos'] = [ x + movex[this.storage['reverse']], y + movey[this.storage['reverse']]];
                            this.move(this.storage['reverse']);
                            this.storage['reverse'] = dest[this.storage['reverse']];
                        }
                    }
                } else {
                    for (var i = 0; i < source.length; i++) {
                        if (typeof environment.aroundMe[source[i]] != "undefined" && typeof environment.aroundMe[source[i]].team != "undefined" && environment.aroundMe[source[i]].team == "blue" && typeof environment.aroundMe[source[i]].name != "undefined") {
                            if (this.direction == rot[source[i]]) {
                                this.kill();
                                this.storage['baited'] = false;
                                action = true;
                            } else {
                                this.rotate(rot[source[i]]);
                                action = true;
                            }
                        }
                    }
                    if (!action) {
                        if (x > 0 && y > 0) {
                            this.storage['pos'] = [ x + movex[0], y + movey[0]];
                            this.move(0);
                        } else if (x > 0 && y == 0) {
                            this.storage['pos'] = [ x + movex[3], y + movey[3]];
                            this.move(3);
                        } else if (x == 0 && y > 0) {
                            this.storage['pos'] = [ x + movex[1], y + movey[1]];
                            this.move(1);
                        } else {
                            this.rotate(1);
                        }
                    }
                }
            }
            this.sendMessage(undefined, "red", {'self': this.storage['pos'] });
            resolve();
        });
    },
    onmessage: function(data, fromTeam, fromBot) {},
    onkill: function() {}
});

```
> 2 votes

# Answer
# Backup 1 another blue bot (forgot to do this earlier)

```
createBot({
    team: 'blue',
    name: 'backup1',
    ontick: function(environment) {
        return new Promise((resolve, reject) => {
            //if (typeof this.x != "undefined") this.storage['position'] = [this.x, this.y];
            if (typeof environment.x != "undefined") this.storage['position'] = [environment.x, environment.y]; //Modified according to @WasteD
            if (typeof this.storage['map'] == "undefined") { //Create empty map
                var map = [[]];
                //for(i=0;i<this.gridHeight;i++) map[i]=[];
                for(i=0;i<environment.gridHeight;i++) map[i]=[]; //Modified according to @WasteD
                this.storage['map'] = map;
            }
            var blue = []
            var red = []
            var x = this.storage['position'][0];
            var y = this.storage['position'][1];
            var dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
            var dy = [1, 1, 1, 0, 0, 0, -1, -1, -1]
            (this.aroundMe || []).forEach((item, idx) => { // Update map and list positions of surrounding blues and reds
                if (item && item.team == 'red' && typeof item.name != "undefined") red += idx;
                if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx[idx]][y+dy[idx]] = 'M';
                if (item && item.team == 'blue' && typeof item.name != "undefined") blue += idx;
            });
            this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']}); //Send to buddies my position and the map
            if (red.indexOf([1, 4, 6, 3][this.direction]) > -1) this.kill() ; //If red guy is in front of
            else if (red.indexOf([1,4,6,3]) > -1) this.rotate(red.indexOf([1,4,6,3])); //If red guy is next but not in front of
            else if (blue.indexOf(3) > -1){ //If blue buddy on the left
                if (blue.indexOf(4) > -1){ //If another one is on the right
                    if (blue.indexOf(1) > -1 && this.direction != 2) this.rotate(2); //...and a third one at the top
                    else var digging = this.dig();
                    }
                else if (this.direction != 1) this.rotate(1);
                else var digging = this.dig();
            }
            else if (blue.indexOf(1) > -1){
                if (blue.indexOf(6) > -1 && this.direction != 3) this.rotate(3);
                else if (this.direction != 2) this.rotate(2);
                else var digging = this.dig();
            }
            else if (blue.indexOf(4) > -1){
                if (this.direction != 3) this.rotate(3);
                else var digging = this.dig();
            }
            else if (blue.indexOf(6) > -1 && this.direction != 0) this.rotate(0);
            else if (blue.indexOf([0,2]) > -1){ //If no blue next to me but one in diagonal, move next
                this.move(1);
                this.storage['position'][1] = y+1; //Update position
            }
            else if (blue.indexOf([5,7]) > -1){
                this.move(6);
                this.storage['position'][1] = y-1;
            }
            else if (typeof this.storage['other_blue'] != "undefined"){ //Check if buddies said where they were, try to go near the closest one
                var dmin = 99999;
                var pos = []
                (this.storage['other_blue'] || {}).forEach((item, idx) => {
                    var d = Math.sqrt(Math.pow(item['position'][0]-x,2) + Math.pow(item['position'][1]-y,2));
                    if (d < dmin){
                        dmin = d;
                        pos = item['position'];
                        }
                });
                if (pos[0]-x > 0){
                    this.move(4);
                    this.storage['position'][0] = x+1
                }
                else if (pos[0] < 0){
                    this.move(3);
                    this.storage['position'][0] = x-1
                }
                else if (pos[1] > 0){
                    this.move(1);
                    this.storage['position'][1] = y+1
                }
                else{
                    this.move(6);
                    this.storage['position'][1] = y-1
                }
            }
            else var digging = this.dig();
            if (typeof digging != "undefined"){ //Check out surroundings if dig() was played and update the map accordingly
                var dx2 = [-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2];
                var dy2 = [2,2,2,2,2,1,1,1,1,1,0,0,0,0,0,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2];
                (digging || []).forEach((item, idx) => {
                    //if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M';
                    if (item) this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M'; //previously misread what dig() returned
                });
            }
            resolve();
        });
    },
    onmessage: function(data, fromTeam, fromBot) {
        if (typeof data['position'] != "undefined" && fromTeam == 'blue') { //If position sent by a blue bot
            if (typeof this.storage['other_blue'] == "undefined") this.storage['other_blue'] = [];
            for (i in this.storage['other_blue']){
                var found = false;
                if ('name' in i){
                    if (i['name'] == fromBot){
                        i['position'] = data['position'];
                        found = true; //Update if position already known from previous ticks
                        }
                }
            }
            if (!found) this.storage['other_blue'] += {'position':data['position'], 'name':fromBot}; //Add position if previously unknown
            this.sendMessage(fromBot, undefined, "roger.");
        }
    },
    onkill: function() {this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']});}
});

```
> 0 votes

# Answer
# Blue Fighter

```
createBot({
  team: "blue",
  name: "blue-fighter",
  ontick: function(environment) {
    return new Promise((resolve, reject)=>{
      let map = environment.aroundMe;
      let sides = [1, 4, 6, 3];
      let facing = sides[this.direction];
      let isTeam = (team,a) => a && a.team === team;
      let isRed = (a)=>isTeam("red",a);
      let isBlue = (a)=>isTeam("blue",a);
      let randomSquare = ()=>Math.floor(Math.random()*8);
      let redNum = map.filter(isRed).length;
      let blueNum =  map.filter(isBlue).length;
      if(redNum > blueNum && redNum > 2){
        this.bomb();
      }else if(isRed(map[facing])){
        this.kill();
      }else if(sides.includes(map.findIndex(isRed))){
        this.rotate(sides.indexOf(map.findIndex(isRed)));
      }else if(Math.random() < 0.5 && this.landMines > 0){
        this.landMine(randomSquare());
      }else{
        this.move(randomSquare());
      }
      resolve();
    });
  },
  onmessage: function(data, from, fromBot) {},
  onkill: function(){}
});

```

Blue fighter moves and landmines randomly and rotates toward red players. If the surrounding blocks have more red than blue, it bombs. If it is facing a red player, it kills it.
> 0 votes

---
Tags: grid, game, king-of-the-hill, javascript
---


# Question
Title: Net neutrality: Is my internet being throttled?
From the wikipedia:

> Net neutrality is the principle that Internet service providers and governments regulating the Internet should treat all data on the Internet the same, not discriminating or charging differentially by user, content, website, platform, application, type of attached equipment, or mode of communication.

Your task is to find if your internet connection is being throttled by your ISP or if the net is neutral.

## What you actually have to do

Your program or function will be run twice. It needs to have some form of memory or storage between its two calls, like writing to a file, a `static` var in C++, setting a property on a function in JS, or just a global variable.

The first time it is run, it must connect to google.com (a fairly popular site), and a *different* website with an Alexa rank of **greater than** 1 million, like unlicense.org.

It must record the time it took google.com to respond\*, and the time it took the other website to respond\*.

The second time it is run, it must do the above, and print a truthy value if these are both true:

1. The response time between google.com the first and second time varied by less than 5%. (Google paid ISP to not throttle)
2. The response time between the other site the first and second time **increased** by more than 50%. (Other site didn't)

Shortest code wins!

---

* The time it to get the response body, headers, or just connect with the server. You choose.

# Answer
> 4 votes
# Python 3 \+ requests, 185 bytes

```
lambda t=[]:t.append([g("http://google.com"),g("http://a.co")])or len(t)>1and abs(1-t[0][0]/t[1][0])<.05<1.5<t[1][1]/t[0][1]
g=lambda s:get(s).elapsed.microseconds
from requests import*

```

Unfortunately `requests` doesn't work with TIO, so I'll have to post a link on another service later. Uses http://a.co as the website with a ranking greater than 1 million.

## 207 bytes, if time is required for the full body

```
f=lambda t=[]:t.append([g("http://google.com"),g("http://a.co")])or len(t)>1and abs(1-t[0][0]/t[1][0])<.05<1.5<t[1][1]/t[0][1]
def g(s):t=time();get(s);return time()-t
from requests import*
from time import*

```

---
Tags: code-golf, internet, networking
---


title: Rapunzel, Rapunzel, let down your hair!

text:
# Question
Title: Rapunzel, Rapunzel, let down your hair!
### Description

I guess everyone knows the fairy tale of Rapunzel and the prince. For those who do not: read it here. However, Rapunzel had just had her hair cut, so it might not be long enough to let her prince climb up! She may get very sad..

### Challenge

Your task is to write a function that evaluates what Rapunzel will be saying when the prince calls for her to let her hair down: When her hair is longer than or equal to the tower is tall plus an extra meter (safety guidelines), she becomes veeeery happy and says `Aaaah!`, with the number of `a`s being the same as `length of her hair - height of the tower`. Otherwise, her hair does not have sufficient length, and she starts crying: `Booho!`, where the `o`s before the `h` equal two thirds of `height of the tower - length of her hair`, and the `o`s after the h being the rest. The number of `o`s after the `B` must be rounded, so if you get `2.6`, there will be 3 `o`s, and the others must be after the `h`.

### I/O

You are given positive integers (including null) as arguments, as a list or as two single numbers, in the order you find it the most convenient, but you must state in which order you take them. As the output, print what Rapunzel will be saying.

### Test cases

In the test cases, the first number will be the hair length.

```
0, 0 -> 'Bh!' (probably a dry sob..)
2, 1 -> 'Aah!'
1, 2 -> 'Boh!'
1, 4 -> 'Booho!'
4, 1 -> 'Aaaah!'
2, 4 -> 'Boho!'

```

This is , so the shortest answer in bytes wins!

# Answer
> 5 votes
# Jelly,  ~~43 41 40 38 34 33 32~~  31 bytes

*~~There's probably a much~~ Is there a shorter way though~~!~~ ? ...this was quite some golfing!*

```
‘:3;ạ¥⁸4ẋ+;€⁹¦7Ṛṭ;8ị“øŻPLC»
ạç>

```

A full program printing the result\*.

**Try it online!**

### How?

```
‘:3;ạ¥⁸4ẋ+;€⁹¦7Ṛṭ;8ị“øŻPLC» - Link 1: number, abs(hair-tower); number, (hair > tower)?
‘                           - increment -> abs(hair-tower)+1
 :3                         - integer divide by 3 -> (abs(hair-tower)+1)//3
                            -   ...the remainder amount after removing 2/3 rounded
      ⁸                     - chain's left argument, abs(hair-tower)
     ¥                      - last two links as a dyad:
    _                       -   subtract (yields the 2/3 rounded amount)
   ;                        - concatenate
       4ẋ                   - repeat 4 (vectorises) (i.e. [[4,4,...],[4,...]])
         +                  - add (hair > tower)? (vectorises) (i.e. 4s->5s if so)
             ¦              - sparse application:
          ;€  7             - of:  concatenate €ach with a 7
            ⁹               - to indexes: chain's right argument, (hair-tower)?
               Ṛ            - reverse the list
                ṭ           - tack (hair-tower)?
                 ;8         - concatenate an 8
                    “øŻPLC» - compression of the word "Abroach" & the string "!B"
                   ị        - index into "Abroach!B" (1-indexed & modular, so 0->B)
                            - implicit (smashed) print

ạç> - Main link: number, hair; number, tower
ạ   - absolute difference -> abs(hair-tower)
  > - greater than? -> (hair > tower)? (1 if so, else 0)
 ç  - call the last link (1) as a dyad

```

* As a monadic link it returns a list of characters and lists of characters e.g. `['B', [['o', 'o', 'h'], ['o']], '!']`, as a full program the implicit print smashes this e.g. `Booho!`

# Answer
> 4 votes
# Python 3, 87 bytes

```
lambda l,h:["B"+"o"*round((h-l)*2/3)+"h"+"o"*round((h-l)/3),"A"+"a"*(l-h)+"h"][l>h]+"!"

```

Try it online!

Arguments to the function are taken in the order `length of hair`, `height of tower`.

# Answer
> 4 votes
# Javascript, ~~105~~ 97 bytes

Thanks to Oki for helping save 7 bytes!

```
p=(t,s)=>(s||"o").repeat(t)
l=>h=>(d=l-h,o=d/3-.5|0,l>h?`A${p(d,"a")}h`:`B${p(o-d)}h`+p(-o))+"!"

```

Defines an anonymous currying function. Use like `f(length)(height)`

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~38~~ ~~35~~ 32 bytes

Input order: `length of hair`, `height of tower`

```
‹i¹α'a×"Aÿh!"ë¹-x‚>3÷R'o×'hý…Bÿ!

```

Try it online!

**Explanation**

```
‹i                                  # if h < l
  ¹α                                # push absolute difference of h and l
    'a×                             # repeat "a" that many times
       "Aÿh!"                       # interpolate between "A" and "h!"
 ë                                  # else
  ¹-                                # push h-l
    x‚                              # pair with its double
      >3÷                           # increment and integer divide by 3
         R                          # reverse the list
          'o×                       # for each, repeat "o" that many times
             'hý                    # merge the o's on "h"
                …Bÿ!                # interpolate between "B" and "!"

```

# Answer
> 2 votes
# Jelly, 32 bytes

```
_‘”aẋŒt;⁾h!ɓ_÷1.,3+.”oẋ“Bh!”żð>?

```

Try it online!

-1 thanks to Jonathan Allan.

Only works as full program.

Arguments are in order: hair, tower

# Answer
> 2 votes
# PHP\>=7.1, 111 bytes

```
[,$h,$t]=$argv;echo BA[$b=$h>$t],($r=str_repeat)(oa[$b],$c=round(($a=abs($h-$t))*($b?:2/3))),h,$r(o,$a-$c),"!";

```

PHP Sandbox Online

# Answer
> 0 votes
# Julia, 101 bytes

```
g(h,t)=h>t?string("A","a"^(h-t),"h!"):string("B","o"^round(Int,(t-h)*2/3),"h","o"^round(Int,(t-h)/3))

```

Arguments to the function are taken in the order `length of Hair`, `height of Tower`.

# Answer
> 0 votes
# Jelly, 84 76 bytes

It's really rather long, but I spent too much time on this not to post it. Takes two integer arguments:

1. length of hair
2. length of tower

Any tips on golfing this would be appreciated.

```
³>⁴×111ð;ø³>⁴¬×97
97ðxø³ạ⁴
111ðxø¢L÷3×⁸ær0:1
2Çṭ2£“h”ṭµ1ÇṭµFḟ1£
>¬+65¥;¢;33Ọ

```

Try it online!

# Answer
> 0 votes
## Perl, 107 bytes

Takes hair length first, tower length second.

```
sub b{(($c=$_[0]-$_[1])>0?'A'.'a'x--$c.'h':do{$o=int(2/3*($c*=-1)+.5);'B'.('o'x$o).'h'.('o'x($c-$o))}).'!'}

```

# Answer
> 0 votes
# R, 117 bytes

```
x=diff(scan());cat(`if`(x>0,paste0("A",rep("a",x),"h!"),paste0("B",rep("o",F<-round(-2*x/3)),"h",rep("o",-x-F),"!")))

```

A bit long, pretty sure this can be golfed down. Takes input from STDIN in the order `Tower, Hair`.

# Answer
> 0 votes
# Python 2, 77 bytes

```
lambda h,t:("BA"+(abs(h-t)*2+1)/3*"oa"+"h"+(abs(h-t)+1)/3*"ao"+"h!!")[h>t::2]

```

An unnamed function taking hair length, `h`, and tower height, `t`, and returning a string.

**Try it online!**

Builds a string starting with `BA`, followed by two thirds of the difference rounded of the string `oa` repeated, followed by a single `h`, then the remainder amount of `ao` repeated, and finally `h!!`. The return value is then every second character starting with either the `B` or `A` via the slice notation `[h>t::2]`.

---
Tags: code-golf
---


# Question
Title: Ordered sequence of ascending integer combinations
Write a program or function to produce the following output in the correct order.

**EDIT:** The symbols are not mathematical! The numbers just represent unique data and the `+` and `-` could be any two arbitrary symbols.

Take an non-negative integer input n. The first line is always `-`, even for n=0.

* If the current line is `-`, the next line is `1+2+ ... (n-1)+n-`
    + n=4: `-` =\> `1+2+3+4-`
* If the last integer is equal to n, remove all integers from the end that are immediately followed by a `-`, then change the last `+` to a `-`
    + n=4: `1-2+3-4-` =\> `1-2-`
    + **EDIT:** When the string is full (all the integers from 1 to n are included), remove all integers from the end that are followed by a `-`, until you reach an integer followed by a `+`. Leave that integer but change its following `+` to a `-`
    + Using the same example as immediately above (which does **not** follow `-`), remove `4-`, remove `3-`, change `2+` to `2-`. `1-` doesn't change since we stop at `2`. Result: `1-2-`
* If the last integer is less than n, append the remaining integers with a `+` after each one, except the final integer which should have a `-` appended
    + n=4: `1+2-` =\> `1+2-3+4-`
    + **EDIT:** If the current string is not full (does not contain all the integers from 1 to n), add each integer not already included in ascending order up to n-1 with a `+` after each one, and then append the last integer n followed by a `-`
    + If the current line is `1-`, append `2+`, append `3+` which is n-1 if n=4. Then append `4-`. Result: `1-2+3+4-`
* If the current line contains all the integers and each one is immediately followed by a `-`, exit the code
    + n=4: `1-2-3-4-` =\> END

There must be no leading or trailing spaces on any line. There must be a line break between each line. There may or may not be a line break on the last line.

**EDIT:** You should test your code up to at least n=10 (over 1000 lines of output so I can't include it here). Any number that doesn't cause your code to run out of resources should (eventually!) produce the correct output but you don't have to wait for the universe to end!

This is , so shortest code in bytes wins!

Input n=0:

```
-

```

Input n=1:

```
-
1-

```

Input n=2:

```
-
1+2-
1-
1-2-

```

Input n=4:

```
-
1+2+3+4-
1+2+3-
1+2+3-4-
1+2-
1+2-3+4-
1+2-3-
1+2-3-4-
1-
1-2+3+4-
1-2+3-
1-2+3-4-
1-2-
1-2-3+4-
1-2-3-
1-2-3-4-

```

# Answer
# Haskell, 89 bytes

`g` takes an integer and returns a string.

```
g n=unlines$max"-".foldr(\(s,i)r->id=<<[show i++s:r|s:r>"+"])""<$>mapM(mapM(,)"+-")[1..n]

```

Try it online!

# How it works

* Loosely speaking, the algorithm constructs a list of all `2^n` combinations `1+2+...n+`, `1+2+...n-` up to `1-2-...n-`, strips away the final `+`-terminated numbers, and if the result is empty, replaces it with `-`.
* `mapM(,)"+-"` is a shorter way (using the function monad) to write `\i->[('+',i),('-',i)]`.
* `mapM(mapM(,)"+-")[1..n]` generates (using the list monad for the outer `mapM`) a list with all combinations as lists of tuples e.g. `[(1,'+'),(2,'-'),...,(n,'+')]`.
* `foldr ... <$> ...` combines each of these lists of tuples into a string, using the lambda expression to build it from the right.
    + `(s,i)` is a tuple of a sign and a number, and `r` is the string constructed from the tuples to its right.
    + `id=<<[show i++s:r|s:r>"+"]` prepends `i` and `s` to the string `r` constructed so far, but *not* if the sign `s` is positive and `r` is empty.
        - This is tested by comparing `s:r` to `"+"`. By luck this is the lexicographically smallest string that can result from concatenating them, so the comparison can use `>` rather than `/=`.
* Also by luck, `"-"` is smaller than any nonempty string that can be constructed by the fold, so the empty string can be replaced with it by using `max`.
* Finally `unlines` turns the strings into a single string of lines.
> 5 votes

# Answer
# Python 2, 101 bytes

```
n=input()
for i in range(2**n):s='';m=n;exec"s=`m`+'+-'[i%2]+s;s*='-'in s;i/=2;m-=1;"*m;print s or'-'

```

Try it online!
> 5 votes

# Answer
# Python 2, 136 141 133 bytes

```
def f(n,s="+"):
 while"+"in s:s=s[:s.rfind("+")]+"-";print s[s>"-":];s+="+".join(map(str,range(len(s)/2+1,n+1)))+"-";print(n>0)*s[1:]

```

Try it online!

The first `-` (un)surprisingly added a fair few bytes to the code.
> 3 votes

# Answer
# Python 2, ~~150~~ ~~164~~ ~~159~~ ~~154~~ ~~146~~ ~~118 bytes~~ ~~115~~ 112 bytes

```
def f(n,i=0):
 while i<2**n:t=''.join(`j+1`+'+-'[i>>n+~j&1]for j in range(n));print t[:t.rfind('-')+1]or'-';i+=1

```

Try it online!

Edit: Oops! It has to work for numbers **greater than** 4 as well... then chip away... until I realized I was overthinking it and saved 28 bytes... and then 6 more via little golfs.
> 3 votes

# Answer
# Pyth, 23 bytes

```
j+\-mssVSQd<Lx_d\-t^"+-

```

Demonstration

The basis of this program is noticing that other than the initial `-`, the plus and minus sequence corresponds to the standard sequence of combinations of `+` and `-` with replacement, with all trailing `+` removed.

**Explanation:**

```
j+\-mssVSQd<Lx_d\-t^"+-
j+\-mssVSQd<Lx_d\-t^"+-"Q    Implicit string completion and variable introduction
                   ^"+-"Q    Form all sequences of + and - of length equal to
                             the input, ordered lexicographically.
                  t          Remove the first one, which we don't use.
           <L                Take the prefix of each one of length
             x               index in
              _d             the reversed string
                \-           of '-'.
    m                        Map the results to
      sV                     Apply the sum function to pairs of
        SQ                   [1, 2, 3 ... input]
          d                  and the previous string
     s                       Sum the pairs.
 +\-                         Add a '-' on to the front of the list
j                            Join on newlines.

```
> 3 votes

# Answer
# Python 2, 73 bytes

```
f=lambda n,a=2,d='\n1':a<n+2and f(n,a+1,d+'+'+`a`)+d+f(n,a+1,d+`-a`)or'-'

```

Try it online!
> 2 votes

# Answer
# Haskell, 70 bytes

```
f n=unlines$"-":foldr(\i x->tail[show i++s:y|s<-"+-",y<-"":x])[][1..n]

```

Try it online!
> 2 votes

# Answer
# Python 3, 305 bytes

```
x=int(input())
o=lambda:list(range(1,x+1))or[0]
q=o()
q[-1]*=-1
print('-')
def f(a):print(''.join(str(abs(x))+'-+'[x>0]for x in a))
while any([k>0 for k in q])or[-k for k in q]!=o():
	f(q)
	if-q[-1]==x:
		while q[-1]<0:q=q[:-1]
		q[-1]*=-1
	elif-q[-1]<x:
		while q[-1]<x:q+=[abs(q[-1])+1]
		q[-1]*=-1
f(q)

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence
---


title: Pulse Measurement of Heart Arrhythmia

text:
# Question
Title: Pulse Measurement of Heart Arrhythmia
In this challenge you have to make an ascii pulsing heart with rhythm problems (Heart arrhythmia) and then measure the pulse.Don't worry it's easy!

**Making the heart**

The heart alternates between these 2 states:
***state 1***

```
    ,d88b.d88b,
    88888888888
    `Y8888888Y'
      `Y888Y'
        `Y'

```

***state 2***

```
     d8b d8b
    888888888
    `Y88888P'
     `Y888P'
      `Y8P'
       `Y'

```

each step has **X seconds delay**
where X is a Random (Real) number between 0.3 and 1.4 (0.3\<=X\<=1.4)

**Measuring the Pulse**

When your arrhythmia-heart starts beating, you have to measure the pulse.
We want to know the heartbeats/min.
But (like many doctors do) you only have to count the heartbeats for 15 sec and then multiply by 4

**Final output**

Given no input, your code must run for 15 seconds (displaying the beating heart) and then **print the heart rate**.

Your output should look exactly like this!
(I will run my code 2 times for you to see the different results)

First example run:

Second example run:

you must output **one** heart
Good Luck!

this is code-golf
shortest answer in bytes wins!

# Answer
# Mathematica, 212 bytes

```
g=",d88b.d88b,
88888888888
`Y8888888Y'
  `Y888Y'
    `Y'";h=" d8b d8b
888888888
`Y88888P'
 `Y888P'
  `Y8P'
   `Y'";t=1;TimeConstrained[Monitor[While[1<2,If[OddQ@t,b=g,b=h];Pause@RandomReal@{.3,1.4};t++],b],15];4t

```
> 0 votes

# Answer
# Python \[on Windows\], 262 bytes

```
from time import*
import os,random
t,i=time(),0
while time()-t<15:print([""",d88b.d88b,
88888888888
`Y8888888Y'
  `Y888Y'
    `Y'""",""" d8b d8b
888888888
`Y88888P'
 `Y888P'
  `Y8P'
   `Y'"""][i%2]);i+=1;sleep(random.randint(3,14)/10);os.system('cls')
print(i*4)

```

For linux and macOS use `os.system('clear')` for 2 more bytes.
> 3 votes

# Answer
# Java, 374 bytes

```
class G{public static void main(String[]a)throws Exception{long t=System.currentTimeMillis(),i=0;while(System.currentTimeMillis()<15000+t){p(",d88b.d88b,\n88888888888\n`Y8888888Y'\n  `Y888Y'\n    `Y'\n");Thread.sleep((long)(300+(Math.random()*1100)));i++;p(" d8b d8b\n888888888\n`Y88888P'\n `Y888P'\n  `Y8P'\n   `Y'\n");}p(i*4);}static<T>void p(T s){System.out.println(s);}}

```

Ungolfed:

```
public class Golf {
    public static void main(String[]a)throws Exception {
        long t=System.currentTimeMillis(),i=0;
        while(System.currentTimeMillis()<15000+t) {
            p(",d88b.d88b,\n88888888888\n`Y8888888Y'\n  `Y888Y'\n    `Y'\n");
            Thread.sleep((long)(300+(Math.random()*1100)));
            i++;
            p(" d8b d8b\n888888888\n`Y88888P'\n `Y888P'\n  `Y8P'\n   `Y'\n");
        }
        p(i*4);
    }
    static<T>void p(T s){System.out.println(s);}
}

```
> 0 votes

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


title: Check If my String is Prime

text:
# Question
Title: Check If my String is Prime
We define a *prime character* as a character that has a prime ASCII value. We define a *prime string* as a String that only contains *prime* characters.

Given a String that only contains printable ASCII, determine whether that String is prime.

## Input / Output

You can take input either as a String or as a list of individual characters. You have to output two different and ***consistent*** values depending on whether the String is prime, following the standard rules for a . You are guaranteed that the input will be non-empty.

## Test Cases

**Truthy cases (Prime Strings):**

```
"aeg"
"aIS5"
"aaaaaaaaaaaaaa"
"/S/S"
"=;+"

```

**Falsy cases (not Prime Strings):**

```
"maTHS"
"Physics"
"\\\\"
"PPCG"
"Code Golf"
"Prime"

```

---

This is , so the shortest code in bytes wins! Standard rules for this tag apply.

# Answer
# Jelly, 4 bytes

```
OÆPẠ

```

Try it online!

### Explanation

Remember that a string is an array of characters, so operations like `O` will apply to each individual character.

```
OÆPẠ
O        Ord; cast each character to a number
 ÆP      Is it ÆPrime? gives 1 for truthy and 0 for falsey
   Ạ     Ạll; returns 1 if the array contains no falsey values

```
> 5 votes

# Answer
# 05AB1E, 3 bytes

```
ÇpW

```

Try it online!

---

```
Ç   # To ASCII array.
 p  # Is prime?
  W # Min value from.

```

---

`ÇpP` also works.
> 5 votes

# Answer
# Python 3, 56 bytes

```
lambda s:all(x%i for x in map(ord,s)for i in range(2,x))

```

Try it online!
> 4 votes

# Answer
# MATL, 3 bytes

```
ZpA

```

Outputs `1` for prime string, `0` otherwise.

Try it online!

### Explanation

```
     % Implicit input
Zp   % Isprime. Applies element-wise to the code point of each entry
A    % All. Gives 1 iff all results are non-zero.
     % Implicit display

```
> 3 votes

# Answer
# Brachylog, 3 bytes

```
ạṗᵐ

```

Try it online!
> 2 votes

# Answer
## Haskell, 32 bytes

```
all(`elem`"%)+/5;=CGIOSYaegkmq")

```

Try it online!
> 2 votes

# Answer
# CJam, 8 bytes

```
q:i:mp:&

```

Try it online!

### Explanation

```
q         e# Read input
 :i       e# Convert to code points
   :mp    e# Check if each is prime
      :&  e# Reduce by AND

```
> 1 votes

# Answer
# , 113 bytes

```
p(int c){for(int i=1;++i<c;)if(!(c%i))return 1;return 0;}c(char*s){char*a="p";while(*s++)if(p(*s))++a;printf(a);}

```
> 1 votes

# Answer
# APL (Dyalog), 21 bytes

```
⎕CY'dfns'
∧/1pco⎕UCS⎕

```

Try it online!

### Explanation

```
⎕CY'dfns' This allows us to use pco
⎕UCS⎕     Convert the characters in the input to its respective code points
1pco      pco with 1 as the left argument gives 1 iff the right argument is prime
          This is applied across the array of code points
∧/        Reduce by AND; return 1 if all elements are truthy, otherwise give false

```
> 1 votes

# Answer
## Perl, 46 bytes

**45 bytes code + 1 for `-p`.**

```
$_=y///c==grep!/^(11+?)\1+$/,map"1"x ord,/./g

```

Try it online! (`-l` added to run all tests at once)
> 1 votes

# Answer
# , 42 bytes

```
all(pracma::isprime(utf8ToInt(scan(,''))))

```

Reads from `stdin`, requires the `pracma` (practical math) package to be installed. Checks if all the UTF-8 encoding of the characters are prime. Unfortunately, this won't work on TIO...

Try it online!
> 1 votes

# Answer
# Mathematica, 30 bytes

```
And@@PrimeQ@ToCharacterCode@#&

```

Quite self-explanatory.
> 1 votes

# Answer
# QBIC, 28 bytes

```
[_l;||q=q*µasc(_sA,a,1)]?q=0

```

This prints -1 for non-prime strings, and 0 for prime ones. That is opposite to QBasic's usual approach to true/false, but this is the shortest way t comply with the 'consistent values' criterium. Output would otherwise be 0 or 1/-1.

## Explanation

```
[    |          FOR a = 1 to
 _l |             the length of
   ;              A$ (read from the cmd line)
q=q*            Multiply q (which starts as 1) by
µ                -1 if the following is prime, 0 otherwise:
 asc(       )   take the ASCII value of
     _sA,a,1      a substring of A$, starting at pos a, for 1 char
]               NEXT
?q=0            If we've tested all chas in the string, print -1 if q=0
                and we've found a non-prime, or a 0 for prime strings

```
> 1 votes

# Answer
# Mathematica, 36 bytes

```
FreeQ[PrimeQ@ToCharacterCode@#,1<0]&

```

Try it online!

*-2 bytes from @JungHwanMin*
> 0 votes

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

```
s=>s.All(i=>Enumerable.Range(2,(int)i-2).All(j=>((int)i)%j))

```
> 0 votes

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


# Question
Title: Computers will never taste a refreshing cookie
Inspired by github.com/JackToaster/Reassuring-Parable-Generator, in turn inspired by xkcd.com/1263. The possible words are derived from the reassuring.cfg of that repository.

Having a look at the reassuring.cfg (use the 12th commit) is suggested to see the grammar the output matches (The output is a list of all strings matching the grammar).

**Task:** Your program must output all 7968 case-sensitive lines of the exact text contained in the pastebin pastebin.com/2SNAJ1VH. A copy of the pastebin is saved in the Wayback Machine

Here is a sample of 33 motivating lines from the pastebin:

```
Computers can't enjoy a salad.
Computers can't enjoy a cake.
Computers can't enjoy a ice cream cone.
Computers can't enjoy a meal.
Computers can't enjoy a drink.
Computers can't enjoy a steak.
Computers can't enjoy a chicken dinner.
Computers can't enjoy a piece of cake.
Computers can't enjoy a piece of pie.
Computers can't enjoy a cookie.
Computers can't enjoy a sandwich.
Computers can't taste a salad.
Computers can't taste a cake.
Computers can't taste a ice cream cone.
Computers can't taste a meal.
Computers can't taste a drink.
Computers can't taste a steak.
Computers can't taste a chicken dinner.
Computers can't taste a piece of cake.
Computers can't taste a piece of pie.
Computers can't taste a cookie.
Computers can't taste a sandwich.
Computers can't experience eating a salad.
Computers can't experience eating a cake.
Computers can't experience eating a ice cream cone.
Computers can't experience eating a meal.
Computers can't experience eating a drink.
Computers can't experience eating a steak.
Computers can't experience eating a chicken dinner.
Computers can't experience eating a piece of cake.
Computers can't experience eating a piece of pie.
Computers can't experience eating a cookie.
Computers can't experience eating a sandwich.

```

### Challenge rules:

* The lines output may be ordered in any way you want, but all 7968 of them must be included.
* The output should be as a single flat string, not as a list of strings.
* Your program should accept no input or an empty unused input.
* Your program may not fetch data from any online source.
* A single trailing newline is optional.

This is , so shortest code wins.

# Answer
> 7 votes
# Zsh, 765 bytes

This may be the first thing I’ve ever written in zsh, but it has the incredibly convenient feature of being able to convert arrays to brace expansions (though it’s not as convenient as it should be…). Run with `zsh -P` (counted as +1 byte), which turns on `RC_EXPAND_PARAM`.

```
a=able\ to
b=" be $a"
d=wonderful
i=ing\ a
o=omputer
n="No c$o "
r=ever
p=capable\ of
u=will
w=$u\ n$r
x=experienc
e=(\ {{{enjoy,tast,$x'ing eat'}$i,tast$i\ {delicious,fresh,tasty,refreshing,$d}}\ {salad,cake,'ice cream cone',meal,drink,steak,chicken\ dinner,'piece of '{cake,pie},cookie,sandwich},{understand$i,{enjoy,$x}$i{,\ {beautiful,$d,{inspir,amaz}ing,superb}}}\ {son{net,g},poem,story,play,'piece of music'}}.)
f=(${e:s/cing/ce/:s/sting/ste/:s/ding/d/:s/ying/y})
l=($w won\'t$b {$w,n$r\ $u}{$b,' have the ability to'})
v=($l "won't $r$b")
k=({ca,wo}n\'t $l is{"n't ",\ un}$a)
c=(C$o\s A\ c$o)
printf %s\\n $c\ $k$f C$o's '$v$f $n{can,is\ $a,$u\ $r$b,"is $r going to",{can,$u}\ $r}$f{,} $c\ {is{\ in,"n't "}$p,"cannot $x"e}$e $n{{is,$u\ be}\ $p,"can $x"e}$e

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), ~~1234~~ 1091 bytes

That's a nice byte count to start! Time to golf down that huge string.

```
f=

_=>(G=`beautiful|wonderful|inspiring|amazing|superb
sonnet|poem|story|play|song${p=`|piece of `}music
cake${p}cake${p}pie|salad|ice cream cone|meal|drink|steak|chicken dinner|cookie|sandwich
delicious|fresh|tasty|refreshing|wonderful
can|is ${a=`able to`}|is ever going to|can ever|will ever${b=` be `+a}|will ever
is ${C=`capable of`}|will be ${C}|can${E=` ${e=`experience`}
${w=`will never`}${b}|${w}${h=` have the ability to|never will`}${h}${b}|won't${b}|${w}|won't`} ever${b}
isn't ${C}|is in${C}|cannot${E}|can't|isn't ${a}|is un${a}`.split`
`.map(l=>l.split`|`),F=S=>[].concat(...S.split`|`.map(s=>eval(s.match(/\d/g).map(n=>`for(f[${n}]of G[${n}])`).join``+`A.push(s.replace(/\\d/g,n=>' '+f[n]));A`,A=[]))),G[9]=F(p=`enjoy a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`),G[9]=F(p=`${e=`enjoy`} a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`),G[0]=F(p.replace(/([^g])e? (a|e)/g,'$1ing $2')),F(`C${o=`omputer`}s89.|A c${o}89.|C${o}s69.|No c${o}49.|C${o}s70.|A c${o}70.|No c${o}50.|No c${o}49.`).join`
`)

document.write('<pre>'+f())
```

Less golfed:

```
f=

_=>(

G=`beautiful|wonderful|inspiring|amazing|superb
sonnet|poem|story|play|song${p=`|piece of `}music
cake${p}cake${p}pie|salad|ice cream cone|meal|drink|steak|chicken dinner|cookie|sandwich
delicious|fresh|tasty|refreshing|wonderful
can|is ${a=`able to`}|is ever going to|can ever|will ever${b=` be `+a}|will ever
is ${C=`capable of`}|will be ${C}|can${E=` ${e=`experience`}
${w=`will never`}${b}|${w}${h=` have the ability to|never will`}${h}${b}|won't${b}|${w}|won't`} ever${b}
isn't ${C}|is in${C}|cannot${E}|can't|isn't ${a}|is un${a}`.split`
`.map(l=>l.split`|`),

F=S=>[].concat(...S.split`|`.map(s=>eval(s.match(/\d/g).map(n=>`for(f[${n}]of G[${n}])`).join``+`A.push(s.replace(/\\d/g,n=>' '+f[n]));A`,A=[]))),

G[9]=F(p=`enjoy a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`),
G[9]=F(p=`${e=`enjoy`} a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`),

G[0]=F(p.replace(/([^g])e? (a|e)/g,'$1ing $2')),

F(`C${o=`omputer`}s89.|A c${o}89.|C${o}s69.|No c${o}49.|C${o}s70.|A c${o}70.|No c${o}50.|No c${o}49.`).join`
`

)

document.write('<pre>'+f())
```

---

## How?

(This is by far one of my most favorite golfs of all time!)

The grammar is stored in the array `G`, which evaluates to this:

```
[["beautiful","wonderful","inspiring","amazing","superb"],
 ["sonnet","poem","story","play","song","piece of music"],
 ["salad","cake","ice cream cone","meal","drink","steak","chicken dinner","piece of cake","piece of pie","cookie","sandwich"],
 ["delicious","fresh","tasty","refreshing","wonderful"],
 ["is capable of","can experience","will be capable of"],
 ["can","is able to","is ever going to","can ever","will ever be able to","will ever"],
 ["will never be able to","will never have the ability to","never will have the ability to","never will be able to","won't ever be able to","will never","won't be able to"],
 ["is incapable of","isn't capable of","cannot experience"],
 ["can't","won't","will never","won't be able to","will never be able to","will never have the ability to","never will have the ability to","never will be able to","isn't able to","is unable to"]]

```

`F` is a function that splits a string by the delimiter `|` and iterates through it. So far so good.

```
F=S=>[].concat(...S.split`|`.map( ... )),

```

Now what's going on with this inner function?

```
s=>eval(
    s.match(/\d/g).map(n=>`for(F[${n}]of G[${n}])`).join``+
    `A.push(s.replace(/\\d/g,n=>F[n]));A`,
    A=[]
)

```

First we initialize an array `A`. Then we find all the digits in the passed string `s` and build a sub-program: Using each digit `n`, we generate a `for`-`of` loop that iterates through the entries in `G[n]` (stored as properties of `F`, since functions in JavaScript are also objects). The loops are then appended one after another.

For example, the generated sub-program for `s="1 2 3"` starts like this:

```
for(F[1]of G[1])for(F[2]of G[2])for(F[3]of G[3])

```

On each iteration, the sub-program replaces each digit in `s` with its corresponding replacement, stored in `F[n]`, and the result is pushed to `A`. The sub-program is `eval`ed and `A` is implicitly returned.

```
for(F[1]of G[1])for(F[2]of G[2])for(F[3]of G[3])A.push(s.replace(/\d/g,n=>F[n]));A

```

Using `F`, the rest of the program simply builds the remainder of the grammar from the production rules that already exist; replacements are simply defined by a single-digit index in `G`.

# Answer
> 4 votes
# PHP, 877 bytes

Ah that was fun!

```
for($p="piece of ";$c="AEIMQUY]aeBFJNRVZ^bfQUY]iIMCGKOSWmqunrvoswCGKOSW"[$m++];)foreach([409,T19,"71 eat59",T19delicious,T1916,T19Ty,T19re165,T1914,409,719,40912,40914,409105,409115,40913,understand09,71912,71914,719105,719115,71913]as$i=>$v)foreach($i<8?[salad,cake,"ice cream cone",meal,drink,steak,"chicken dinner",$p.cake,$p.pie,cookie,sandwich]:[sonnet,poem,story,play,song,$p.music]as$u)echo trim(strtr([C17s,"A c17","No c17"][$o=3&$d=ord($c)-65]." ".($o&2?[6,is3,"is 8 go5 to","6 8","2 8 be3","2 8",11=>"is 15","6 7e","2 be 15"]:["6't",$t="won't",$w="2 n8","$t be3","2 n8 be3",$w.$z=" have the ability to","n8 2$z","n8 2 be3","isn't3","is unable to","$t 8 be3","is in15","isn't 15","6not 7e"])[$d/4]." $v",($c>l?[ing,ing]:["",e])+[2=>will," able to",enjoy,ing,can,experienc,ever," a ",inspir,amaz,beautiful,superb,wonderful,"capable of",fresh,omputer,T=>tast]))," $u.
";

```

Feel free to try digging up one more byte if You can.

**ungolfed**

```
while($c="AEIMQUY]aeBFJNRVZ^bfQUY]iIMCGKOSWmqunrvoswCGKOSW"[$p++])
    foreach(["enjoy0 a","tast1 a","experienc1 eating a","tast1 a delicious","tast1 a fresh","tast1 a tasty","tast1 a refreshing","tast1 a wonderful",
    "enjoy0 a","experienc1 a","enjoy0 a beautiful","enjoy0 a wonderful","enjoy0 a inspiring","enjoy0 a amazing","enjoy0 a superb",
    "understand0 a","experienc1 a beautiful","experienc1 a wonderful","experienc1 a inspiring","experienc1 a amazing","experienc1 a superb"]as$i=>$v)
        foreach($i<8
            ?[salad,cake,"ice cream cone",meal,drink,steak,"chicken dinner","piece of cake","piece of pie",cookie,sandwich]
            :[sonnet,poem,story,play,song,"piece of music"]
        as$u)
            echo[Computers,"A computer","No computer"][$o=3&$d=ord($c)-65]," ",
                ($o&2
                    ?[can,"is able to","is ever going to","can ever","will ever be able to","will ever",11=>"is capable of","can experience","will be capable of"]
                    :["can't","won't","will never","won't be able to","will never be able to","will never have the ability to","never will have the ability to","never will be able to","isn't able to","is unable to","won't ever be able to","is incapable of","isn't capable of","cannot experience"]
                )[$d/4]," ",
                strtr($v,$c>l?[ing,ing]:["",e]),
                " $u.\n"
            ;

```

**explanation**

The output can be split to 48 chunks of 166 lines each. Within each chunk, each line begins with one of `Computers|A computer|No computer` followed by one of 14 negative (for `Computers` and `A computer`) or 9 positive (for `No computer`) capabilities.
I encoded these chunks to 6 bit each, (3 different subjects -\> lower 2 bits; the positive and negative caps share keys -\> upper 4 bits), and (probably obvious) added 65 to use the values as ASCII codes.

Within these chunks, 8 verb/adjective combinations for 11 different foods and 13 different combinations for 6 different arts, always in the same order; so they can simply be looped through, using the verb/adjective key to determine wether I have to list foods or beverages in the next loop.

One tricky part remained: Some of the caps require the gerund form of the verb; and some of the verbs lose an `e` in the transformation. The cap index tells wether that is necessary or not.
(and thanks to the order of bits in the encoding I can simply use the ASCII character for the comparison).
But how? After juggling with regexes for a while, I simply put a `1` where the `e` has to be replaced with `ing` and a `0` where `ing` has to be appended and let `strtr` do the job.

That´s the story of the ungolfed version above. (1199 bytes packed)

---

The **golfing** consisted mainly in 3 steps:

1. Most used character sequences were stored to variables.
2. `strtr` was extended to everything except the subject in order to move variables to `strtr`.
3. Most of the sequences were moved from variables to `strtr`.

The 19th word, `tast`, was replaced with a capital letter to get rid of a couple of quotation marks.

---

I wonder what would happen if I also encoded the verb/adjective combinations.
Maybe I could beat Zsh; but I´m not sure if I wonder enough to try.

# Answer
> 1 votes
# Retina, ~~1249~~ 1192 bytes

```

CFs 1 5.¶A cF 1 5.¶C O nG beH 5.¶C O nGKtheJto 5.¶C nG OKtheJto 5.¶C nG O beH 5.¶C won't G beH 5.¶C O nG 5.¶C won't beH 5.¶nNo cF 3 5.¶C 2 6.¶A cF 2 6.¶nNo cF 4 6.¶nNo cF 3 5.
1
can't$%'¶$%`won't$%'¶$%`O nG$%'¶$%`won't beH$%'¶$%`O nG beH$%'¶$%`O nGKtheJto$%'¶$%`nG OKtheJto$%'¶$%`nG O beH$%'¶$%`isn'tH$%'¶$%`is unIto
2
is incapIof$%'¶$%`isn't capIof$%'¶$%`cannot De
3
can$%'¶$%`isH$%'¶$%`is G goQ to$%'¶$%`can G$%'¶$%`O G beH$%'¶$%`O G
4
is capIof$%'¶$%`can De$%'¶$%`O be capIof
5
E a 8$%'¶$%`Le a 8$%'¶$%`De eatQ a 8$%'¶$%`Le a 7 8$%'¶$%`E a 9$%'¶$%`De a 9$%'¶$%`E a B 9$%'¶$%`P a 9$%'¶$%`De a B 9
6
EQ a 8$%'¶$%`LQ a 8$%'¶$%`DQ eatQ a 8$%'¶$%`LQ a 7 8$%'¶$%`EQ a 9$%'¶$%`DQ a 9$%'¶$%`EQ a B 9$%'¶$%`PQ a 9$%'¶$%`DQ a B 9
7
delicious$%'¶$%`fresh$%'¶$%`Ly$%'¶$%`refreshQ$%'¶$%`wonderful
8
salad$%'¶$%`cake$%'¶$%`ice cream cone$%'¶$%`meal$%'¶$%`drink$%'¶$%`steak$%'¶$%`chicken dinner$%'¶$%`Mof cake$%'¶$%`Mof pie$%'¶$%`cookie$%'¶$%`sandwich
9
sonnet$%'¶$%`poem$%'¶$%`story$%'¶$%`play$%'¶$%`song$%'¶$%`Mof music
B
beautiful$%'¶$%`wonderful$%'¶$%`inspirQ$%'¶$%`amazQ$%'¶$%`superb
D
experienc
E
enjoy
F
omputer
G
ever
H
 Ito
I
able
J
 ability
K
 have
L
tast
M
piece
O
will
P
understand
Q
ing

```

Output exceeds TIO limitations. I wanted to use `%`` stages to avoid all the `$%'¶$%`` but for some reason that doesn't do what I want. Edit: Saved 57 bytes thanks to @fireflame241.

# Answer
> 0 votes
# Bubblegum, 23353 bytes

Yup. Most of it won't fit in an answer so... Both the code and the TIO link are in pastes.

**Code** (a hexdump of the code)

**TIO link** (the output exceeds TIO's limitations)

---
Tags: code-golf, string, kolmogorov-complexity, grammars
---