# Question
Title: Convert tiers between credit rating system
*Related: Sort these bond ratings*

Credit rating agencies assign ratings to bonds according to the credit-worthiness of the issuer. The rating business is mostly controlled by "Big Three" credit rating agencies (i.e. Fitch Ratings, Moody's, and Standard & Poor's (S&P)), which use a similar tiered rating system.

## Task

For this challenge, we will consider only long-term non in-default tiers of two rating formats, Moody's and Fitch/S&P. NA-style ratings such as `NR` or `WR` will not be included.

Your task is to design a program or function that takes as input a rating tier in one of the two format and outputs the equivalent tier in the other format. Your program must support both formats in input and output, i.e. your program cannot be able only to convert from Moody's to Fitch/S&P or vice versa.

**Edit**: your program may output trailing whitepaces.

The following table shows the tier pairs.

```
Moody's Fitch/S&P
------- ---------
Aaa     AAA
Aa1     AA+
Aa2     AA
Aa3     AA-
A1      A+
A2      A
A3      A-
Baa1    BBB+
Baa2    BBB
Baa3    BBB-
Ba1     BB+
Ba2     BB
Ba3     BB-
B1      B+
B2      B
B3      B-
Caa     CCC
Ca      CC
Ca      C

```

#### Notes

* there are no tiers in the two formats that are identical;
* for each rating tier (except `Ca`) there is one (and only one) equivalent tier in the other format;
* `Ca` is equivalent to either `CC` or `C`, depending on the specific case;
    + when your program takes as input `Ca`, it must output either `CC` or `C` indifferently;
    + your program must output `Ca` when the input is `CC` or `C`.

## Rules and scoring

This is code golf, so lowest byte count wins, standard loopholes disallowed.

# Answer
# Jelly, 36 bytes

Assumes that we may use ASCII only input (so `-` rather than the similarly looking  used in the post) and that "indifferently" is being used to mean either/or (here `Ca` produces `CC` only).

```
;⁼¡“C”Ḣð;“13-+a”,Ṛ$y⁹⁸;;ḟẇ“¶®O^»$?”2

```

A monadic Link that accepts a list of characters (one of the ratings) and outputs the equivalent rating from the other agency.

**Try it online!**

### How?

```
;⁼¡“C”Ḣð;“13-+a”,Ṛ$y⁹⁸;;ḟẇ“¶®O^»$?”2 - Link: list of characters, R
   “C”                               - set the right argument to ['C']
  ¡                                  - repeat...
 ⁼                                   - ...times: is {R} equal to {['C']}?
;                                    - ...action: {R} concatenate {['C']}
                                         -> R="C" becomes "CC" others unaffected
      Ḣ                              - head
       ð                             - start a new dyadic chain - f(Head, say 'H', Rest)
        ;“13-+a”                     - {Head} concatenate "13-+a"
                ,Ṛ$                  - pair with its reverse -> ["H13-+a","a+-31H"]
                   y⁹                - translate {Rest} using {that mapping}
                     ⁸;              - left arg {=Head} concatenate {translated Rest}
                                  ”2 - set the right argument to '2'
                                 ?   - if...
                         ẇ“¶®O^»$    - ...condition: is sublist of "AaBaa"?
                       ;             - ...then: concatenate {'2'}
                        ḟ            - ...else: filter discard {'2'}

```
> 5 votes

# Answer
# Google Sheets, 168 bytes

`iferror(find())` by JvdV, **168 bytes**:

```
=let(b,left(A1),c,right(A1),f,len(split(A1,"123+-")),iferror(rept(b,f)&mid("+-",find(c,"132a"),1),b&rept("a",f-1+(A1="C"))&rept(mid(1223,find(c,"+AB-C"),1),A1<>"AAA")))

```

Brute force `hlookup()`, **217 bytes**:

```
=let(m,split("Aaa0Aa10Aa20Aa30A10A20A30Baa10Baa20Baa30Ba10Ba20Ba30B10B20B30Caa0Ca0Ca",0),f,split("AAA0AA+0AA0AA-0A+0A0A-0BBB+0BBB0BBB-0BB+0BB0BB-0B+0B0B-0CCC0CC0C",0),ifna(hlookup(A1,{m;f},2,0),hlookup(A1,{f;m},2,0)))

```

`regexextract()` and `regexmatch()`, **221 bytes**:

```
=let(a,regexextract(A1,"[A-c]+"),c,left(a)&rept("a",len(a)-1)&switch(right(A1),"+","1","-","3",),if(regexmatch(A1,"[a-c\d]"),rept(left(a),len(a))&switch(right(A1),"1","+","3","-",),c&if(regexmatch(c,"^(Aa?|Ba?a?)$"),2,)))

```

Convoluted arrays of regexes applied two ways, **298 bytes**:

```
=let(r,lambda(a,b,reduce(A1,sequence(rows(a)),lambda(t,i,regexreplace(t,index(a,i),index(b,i))))),a,{"Baa";"Ba";"Caa";"Ca";"1";"2";"3";"$12";"Ca"},b,{"BBB";"BB";"CCC";"^C$";"\+";"ø";"-";"^(AA?|Ba?a?)$";"^CC$"},regexreplace(if(regexmatch(A1,"[a-c\d]"),upper(r(a,b)),proper(r(b,a))),"\\|Ø|\^|\$",""))

```

Put the rating in cell `A1` and the formula in cell `B1`.
> 5 votes

# Answer
# JavaScript (ES6), 91 bytes

*-1 thanks to @l4m2*
*-4 thanks to @tsh*

The output may contain a trailing space.

```
([o,...a],s=o+` +-a213`)=>"C"+a.map(c=>o+=s[s.indexOf(c)^4])<s?"Ca":/^A?$|B$/.test(a)?o+2:o

```

Try it online!

### Commented

```
( [o,            // o = 1st character of the input
      ...a],     // a[] = remaining characters
  s = o +        // s is a lookup string used to transpose:
      ` +-a213`  //   "a" <-> first character
                 //   "+" <-> "1"
                 //   " " <-> "2"
                 //   "-" <-> "3"
) =>             //
"C" +            // prefix the result of the map() with "C"
a.map(c =>       // for each character c in a[]:
  o += s[        //   append to o ...
    s.indexOf(c) //   ... the character corresponding to
    ^ 4          //   the transposition of c
  ]              //
)                // end of map()
< s ?            // if o is "C":
  "Ca"           //   return "Ca"
:                // else:
  /^A?$|B$/      //   if the input was any of "A", "AA", "B",
  .test(a) ?     //   "BB" or "BBB":
    o + 2        //     append a "2"
  :              //   else:
    o            //     leave o unchanged

```
> 3 votes

# Answer
# Retina 0.8.2, 59 bytes

```
^C$
CC
(?<!AA)[AB]$
$&,
1>T`321+--aL`-_+1-3#a`.
+`(.)#
$1$1

```

Try it online! Link is to test suite that does some magic splitting and joining. Converts `Ca` to `CC`. Explanation:

```
^C$
CC

```

Change `C` to `CC`.

```
(?<!AA)[AB]$
$&,

```

Except for `AAA`, append a `,` to any string ending with `A` or `B`. The choice of `,` is important for the transliteration as it is between `+` and `-` in ASCII.

```
1>T`321+--aL`-_+1-3#a`.

```

Excluding the first character, transliterate `3` to `-`, delete `2`, transliterate `1` to `+`, `+` to `-` to `1` to `3`, `a` to `#` and all uppercase letters to `a`. (Having the `-` be first in the target pattern makes it a literal `-`. I couldn't do that in both patterns but fortunately in the source pattern I could use a range from `+` to `-`.)

```
+`(.)#
$1$1

```

Make `#`s copy the preceding letter.
> 2 votes

# Answer
# Python, 171 bytes

```
dict(zip(a:="Aaa Aa1 Aa2 Aa3 A1 A2 A3 Baa1 Baa2 Baa3 Ba1 Ba2 Ba3 B1 B2 B3 Caa Ca Ca C CC CCC B- B B+ BB- BB BB+ BBB- BBB BBB+ A- A A+ AA- AA AA+ AAA".split(),a[::-1])).get

```

Try it online!

Boring hard-code Python answer is shorter than current ones...
> 2 votes

# Answer
# Charcoal, 38 bytes

```
⭆×⁻θ2⊕⁼θC⎇κ§⁺§θ⁰13-+a⌕a+-31ιι¿№AABBBθ2

```

Try it online! Link is to verbose version of code. Explanation: Port of @JonathanAllan's Jelly answer.

```
⭆×⁻θ2⊕⁼θC⎇κ§⁺§θ⁰13-+a⌕a+-31ιι

```

Remove any `2` from the input, double it if it's `C`, and then transliterate all characters after the first from `a+-31` to `#13-+a`, where `#` is the first character of the input; characters in the input that don't match the source string are replaced with the last character of the destination string.

```
¿№AABBBθ2

```

Append a `2` if the input is a substring of `AABBB`.
> 1 votes

# Answer
# Excel ms365, ~~207~~179 bytes

Thanks to @doubleunary's idea for nesting `TEXTSPLIT()` inside `LEN()`.

Assuming input in `A1`:

```
=LET(a,A1,b,LEFT(a),c,RIGHT(a),e,LEN(@TEXTSPLIT(a,{1,2,3,"+","-"})),IFERROR(REPT(b,e)&MID("+-",FIND(c,"132a"),1),b&REPT("a",e-1+(a="C"))&IF(a="AAA",,MID(1223,FIND(c,"+AB-C"),1))))

```
> 1 votes

# Answer
# Python 3, 200 bytes

```
def f(x):
 r=str.replace;d=(6,0)[(x*2)[1]in'a123'];y=x
 for i in 0,1,2:y=r(y,chr(49+i-d),chr(43+i+d))
 y=r(y,',','')*((x=='C')+1)+'2'[not d*(x in'ABBBAA'):]
 return x[0]+r(y[1:],*('a',x[0])[::1-d//3])

```

Try it online!

Probably can be optimized, but it's the best I could come up with.

```
r=str.replace
# Set an alias for `str.replace`, we'll use it three times

d=(6,0)[(x*2)[1]in'a123']
# Detects if `x` is on Moody's format by checking the 2nd character.
# If positive, set `d` to 0, otherwise set `d` to 6.
# The multiplication by 2 is to handle single-character strings.

y=x
# Create a variable for the following replacements:

for i in 0,1,2:y=r(y,chr(49+i-d),chr(43+i+d))
# If `d` is 0, it will replace all '123' occurrences with '+,-', respectively
# If `d` is 6, it will replace all '+,-' occurrences with '123', respectively

y=r(y,',','')
# An annoying comma will appear in the first conversion, so remove it
y=y*((x=='C')+1)
# Handle the special case where `x` is equal to 'C', duplicating it
y=y+'2'[not d*(x in'ABBBAA'):]
# If `x` is on Fitch/S&P format, add a trailing '2' to the
# result if `x` is either 'A', 'AA', 'B', 'BB' or 'BBB'

return x[0]+r(y[1:],*('a',x[0])[::1-d//3])
# Since the first character of the input string will not change,
# keep it. For the remaining characters, if `x` is on Moody's
# format, replace all 'a's with the first character. Otherwise,
# replace all occurrences of the first character with 'a's.

```
> 1 votes

# Answer
# C (gcc), ~~285~~ ~~275~~ 248 bytes

-10 bytes by moving `strcmp` inside `for` condition and using "incorrect" pointer types (thanks @ceilingcat)

-27 by assuming 64-bit little-endian `long`

```
i;*t="Aaa AAA Aa1 AA+ Aa2 AA  Aa3 AA- A1  A+  A2  A   A3  A-  Baa1BBB+Baa2BBB Baa3BBB-Ba1 BB+ Ba2 BB  Ba3 BB- B1  B+  B2  B   B3  B-  Caa CCC Ca  CC  Ca  C   ";f(int*s){long j=538976288;memcpy(&j,s,strlen(s));for(i=38;t[--i]-j;);j=t[i^1];puts(&j);}

```

Try it online!
> 1 votes

# Answer
# Python 3, 235 bytes

```
eval('lambda x:(x?a",x[0])?1","+")?2","")?3","-")if"a"in x or x[-1]in"123"else x[0]+x[1:]?+","1")?-","3")?B","a")?C","a")?A","a")+("2"if x[-1]not in"+-"else""))?Aaa2","Aaa")?C2","Ca")?Ca2","Ca")?Caa2","Caa")'.replace('?','.replace("'))

```

Try it online!

Returns an anonymous function.
> 1 votes

# Answer
# Python 3 (256)

I know its not very short or optimized, but here is my first attempt at code golf! Please let me know if you have a tip for me to improve!

```
f=lambda r:(s:=r.replace("1","+").replace("3","-"))[0]*len(s.strip("+-2"))+s[-1].strip("2a")if "a" in r or r[-1]in[1,2,3] else r[0]+"a"*(l:=len(r.strip("+-"))-1)+(""if r[0]=="C"or r=="A"*3 else str(["+"," ","-"].index((r+" ")[l+1])+1))+("a"if r=="C"else"")

```

I do see that it is longer than the hardcoded python option, so I'll definitely have to try to beat that at the very least. Also comment if you want an explanation.

Edit: Here is another method using regex that turned out to unfortunately be longer (**268**) with the import

```
import re
t=str.maketrans("+-13","13+-")
f=lambda r: (r.replace("a",r[0]).translate(t).strip("2"))if r[-1]in"123"or"a"in r else((o:=re.sub("(Aa?|Ba*)$",lambda m:m.group()+"2",re.sub("(?<=\\w)\\w+",lambda m:"a"*len(m.group()),r)).translate(t))+("a"if len(o)<2 else""))

```
> 0 votes

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


title: Fusing Fireworks

text:
# Question
Title: Fusing Fireworks
### Overview

Given a list of fireworks `a-z` and times `3-78`, arrange them with fuses to make them all light up at the correct time.

A line of input is given as space separated letters and numbers:

```
a 3 b 6 c 6 d 8 e 9 f 9

```

That example shows that firework `a` need to light at time `3`, `b` and `c` both at `6`, `d` at `8`, with `e` and `f` both at `9`. Each line corresponds to one map.

Output is a fuse/firework map for each line, using the symbols `|-` to show fuses and the letters to show fireworks.

A `-` fuse connects to fuses and fireworks directly left/right of it, while a `|` fuse connects with those above/below. For example, the fuses `||` are *not* connected, and `-|` *are*.

For example, two possible answers to the above are:

```
---a        ---------f
  |         |||   ||
  |-c       |||   de
--|--d      a||
| b |        |c
f   e        b

```

All fuse maps should start with a single `-` in the upper left corner. That is the point where you light the fuse. Each character of fuse takes one second to burn. As you can see, the `a` is reached in three seconds in both diagrams, `b` in six, etc.

Now, both of the maps given above are valid for the input given, but one is clearly more efficient. The left one only uses 13 units of fuse, while the right one takes 20.

Fuses **do not** burn through fireworks! So, for input `a 3 b 5`, this is not valid:

```
---a--b

```

### Challenge

Your goal is to minimize the amount of fuse used over all test cases. Scoring is very simple, the total units of fuse used.

If you *cannot* produce a map for a test case, whether it's an impossible case or not, the score for that case is the sum of all times (41 for the example above).

In the case of a tie, the scoring is modified so that the most *compact* maps win. The tiebreak score is the *area* of the bounding box of each map. That is, the length of the longest line times the number of lines. For "impossible" maps this is the square of the largest number (81 for the example above).

In the case that submissions tie both of these scoring methods, the tie goes to the earlier entry/edit.

Your program must be deterministic, for verification purposes.

### Test Cases

There are 250 test cases, located here. Each has between 4 and 26 fireworks. The minimum fuse time for a firework is 3. The fireworks in each case are "sorted" by time and letter, meaning `b` will never light *before* `a`.

When posting, please include your full program, your total score, and the resulting map for (at least) the first test case given in the file:

```
a 6 b 8 c 11 d 11 e 11 f 11 g 12 h 15 i 18 j 18 k 21 l 23 m 26 n 28 o 28 p 30 q 32 r 33 s 33 t 34

```

# Answer
## C++

## Total Length: 9059, Total Area: 27469, Failures: 13.

*Note:* Score includes failure penalties.

---

**Sample output:**

```
a 6 b 8 c 11 d 11 e 11 f 11 g 12 h 15 i 18 j 18 k 21 l 23 m 26 n 28 o 28 p 30 q 32 r 33 s 33 t 34
------ae
     | |
     |---c
     b||-g
      |d|
      f |
    i---|
  k---| h
   |  j
   |---m
   l  | t
     o-n|
      |s-r
      |-|
      p q
Length: 39, Area: 150.

```

---

```
a 6 b 6 c 6 d 6 e 6 f 6 g 6 h 8 i 9 j 9 k 9 l 12 m 12 n 13 o 14 p 15 q 15 r 15 s 17 t 17 u 17 v 17 w 17 x 20 y 23 z 26
------a  n|--w
|d-||---k|-o|
| g|b  |--m --x
|-|c    ||--r|
||f     l|-q |
||--j u--|--s|-
e|-i    |p|  y|
 h      v t  z-
Length: 56, Area: 120.

```

---

**Full output:** http://pastebin.com/raw.php?i=spBUidBV

---

Don't you just love brute-force solutions? This is a little more than a simple backtracking algorithm: our tireless worker moves around the map, placing fuses and fireworks as necessary, while testing all possible moves at any point. Well, almost---we do restrict the set of moves and abandon nonoptimal states early so that it doesn't take unbearably long (and, in particular, so that it terminates.) Special care is taken not to create any cycles or unintended paths and not to go back the same way we came, so it's guaranteed that we don't visit the same state twice. Even so, finding an optimal solution can take a while, so we eventually give up on optimizing a solution if it takes too long.

This algorithm still has some headroom. For one thing, better solutions can be found by increasing the `FRUSTRATION` parameters. There's no competition ATM but these numbers can be cranked up if and when...

Compile with: `g++ fireworks.cpp -ofireworks -std=c++11 -pthread -O3`.

Run with: `./fireworks`.

Reads input from STDIN and writes output to STDOUT (possibly out-of-order.)

```
/* Magic numbers */
#define THREAD_COUNT 2
/* When FRUSTRATION_MOVES moves have passed since the last solution was found,
 * the last (1-FRUSTRATION_STATES_BACKOFF)*100% of the backtracking states are
 * discarded and FRUSTRATION_MOVES is multiplied by FRUSTRATION_MOVES_BACKOFF.
 * The lower these values are, the faster the algorithm is going to give up on
 * searching for better solutions. */
#define FRUSTRATION_MOVES 1000000
#define FRUSTRATION_MOVES_BACKOFF 0.8
#define FRUSTRATION_STATES_BACKOFF 0.5

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <thread>
#include <mutex>
#include <string>
#include <sstream>
#include <cassert>

using namespace std;

/* A tile on the board. Either a fuse, a firework, an empty tile or an
 * out-of-boudns tile. */
struct tile {
    /* The tile's value, encoded the "obvious" way (i.e. '-', '|', 'a', etc.)
     * Empty tiles are encoded as '\0' and OOB tiles as '*'. */
    char value;
    /* For fuse tiles, the time at which the fuse is lit. */
    int time;

    operator char&() { return value; }
    operator const char&() const { return value; }

    bool is_fuse() const { return value == '-' || value == '|'; }
    /* A tile is vacant if it's empty or OOB. */
    bool is_vacant() const { return !value || value == '*'; }

    /* Prints the tile. */
    template <typename C, typename T>
    friend basic_ostream<C, T>& operator<<(basic_ostream<C, T>& os,
                                            const tile& t) {
        return os << (t.value ? t.value : ' ');
    }
};
/* Fireworks have the same encoding as tiles. */
typedef tile firework;
typedef vector<firework> fireworks;

/* The fuse map. It has physical dimensions (its bounding-box) but is
 * conceptually infinite (filled with empty tiles.) */
class board {
    /* The tiles, ordered left-to-right top-to-bottom. */
    vector<tile> p_data;
    /* The board dimensions. */
    int p_width, p_height;
    /* The total fuse length. */
    int p_length;

public:
    board(): p_width(0), p_height(0), p_length(0) {}

    /* Physical dimensions. */
    int width() const { return p_width; }
    int height() const { return p_height; }
    int area() const { return width() * height(); }
    /* Total fuse length. */
    int length() const { return p_length; }

    /* Returns the tile at (x, y). If x or y are negative, returns an OOB
     * tile. */
    tile get(int x, int y) const {
        if (x < 0 || y < 0)
            return {'*'};
        else if (x >= width() || y >= height())
            return {'\0'};
        else
            return p_data[y * width() + x];
    }
    /* Sets the tile at (x, y). x and y must be nonnegative and the tile at
     * (x, y) must be empty. */
    board& set(int x, int y, const tile& t) & {
        assert(x >= 0 && y >= 0);
        assert(!get(x, y));
        if (x >= width() || y >= height()) {
            int new_width = x >= width() ? x + 1 : width();
            int new_height = y >= height() ? y + 1 : height();
            vector<tile> temp(new_width * new_height, {'\0'});
            for (int l = 0; l < height(); ++l)
                copy(
                    p_data.begin() + l * width(),
                    p_data.begin() + (l + 1) * width(),
                    temp.begin() + l * new_width
                );
            p_data.swap(temp);
            p_width = new_width;
            p_height = new_height;
        }
        p_data[y * width() + x] = t;
        if (t.is_fuse())
            ++p_length;
        return *this;
    }
    board&& set(int x, int y, const tile& t) && { return move(set(x, y, t)); }

    /* Prints the board. */
    template <typename C, typename T>
    friend basic_ostream<C, T>& operator<<(basic_ostream<C, T>& os,
                                            const board& b) {
        for (int y = 0; y < b.height(); ++y) {
            for (int x = 0; x < b.width(); ++x)
                os << b.get(x, y);
            os << endl;
        }
        return os;
    }
};

/* A state of the tiling algorithm. */
struct state {
    /* The current board. */
    board b;
    /* The next firework to tile. */
    fireworks::const_iterator fw;
    /* The current location. */
    int x, y;
    /* The current movement direction. 'N'orth 'S'outh 'E'ast, 'W'est or
     * 'A'ny. */
    char dir;
};

/* Adds a state to the state-stack if its total fuse length and bounding-box
 * area are not worse than the current best ones. */
void add_state(vector<state>& states, int max_length, int max_area,
                state&& new_s) {
    if (new_s.b.length() < max_length ||
        (new_s.b.length() == max_length && new_s.b.area() <= max_area)
    )
        states.push_back(move(new_s));
}
/* Adds the state after moving in a given direction, if it's a valid move. */
void add_movement(vector<state>& states, int max_length, int max_area,
                    const state& s, char dir) {
    int x = s.x, y = s.y;
    char parallel_fuse;
    switch (dir) {
    case 'E': if (s.dir == 'W') return; ++x; parallel_fuse = '|'; break;
    case 'W': if (s.dir == 'E') return; --x; parallel_fuse = '|'; break;
    case 'S': if (s.dir == 'N') return; ++y; parallel_fuse = '-'; break;
    case 'N': if (s.dir == 'S') return; --y; parallel_fuse = '-'; break;
    }
    const tile t = s.b.get(s.x, s.y), nt = s.b.get(x, y);
    assert(t.is_fuse());
    if (nt.is_fuse() && !(t == parallel_fuse && nt == parallel_fuse))
        add_state(states, max_length, max_area, {s.b, s.fw, x, y, dir});
}
/* Adds the state after moving in a given direction and tiling a fuse, if it's a
 * valid move. */
void add_fuse(vector<state>& states, int max_length, int max_area,
                const state& s, char dir, char fuse) {
    int x = s.x, y = s.y;
    int sgn;
    bool horz;
    switch (dir) {
    case 'E': ++x; sgn = 1; horz = true; break;
    case 'W': --x; sgn = -1; horz = true; break;
    case 'S': ++y; sgn = 1; horz = false; break;
    case 'N': --y; sgn = -1; horz = false; break;
    }
    if (s.b.get(x, y))
        /* Tile is not empty. */
        return;
    /* Make sure we don't create cycles or reconnect a firework. */
    const tile t = s.b.get(s.x, s.y);
    assert(t.is_fuse());
    if (t == '-') {
        if (horz) {
            if (fuse == '-') {
                if (!s.b.get(x + sgn, y).is_vacant() ||
                    s.b.get(x, y - 1) == '|' ||
                    s.b.get(x, y + 1) == '|')
                    return;
            } else {
                if (s.b.get(x + sgn, y) == '-' ||
                    !s.b.get(x, y - 1).is_vacant() ||
                    !s.b.get(x, y + 1).is_vacant())
                    return;
            }
        } else {
            if (!s.b.get(x, y + sgn).is_vacant() ||
                s.b.get(x - 1, y) == '-' ||
                s.b.get(x + 1, y) == '-')
                return;
        }
    } else {
        if (!horz) {
            if (fuse == '|') {
                if (!s.b.get(x, y + sgn).is_vacant() ||
                    s.b.get(x - 1, y) == '-' ||
                    s.b.get(x + 1, y) == '-')
                    return;
            } else {
                if (s.b.get(x, y + sgn) == '|' ||
                    !s.b.get(x - 1, y).is_vacant() ||
                    !s.b.get(x + 1, y).is_vacant())
                    return;
            }
        } else {
            if (!s.b.get(x + sgn, y).is_vacant() ||
                s.b.get(x, y - 1) == '|' ||
                s.b.get(x, y + 1) == '|')
                return;
        }
    }
    /* Ok. */
    add_state(
        states,
        max_length,
        max_area,
        {board(s.b).set(x, y, {fuse, t.time + 1}), s.fw, x, y, dir}
    );
}
/* Adds the state after adding a firework at the given direction, if it's a
 * valid move. */
void add_firework(vector<state>& states, int max_length, int max_area,
                    const state& s, char dir) {
    int x = s.x, y = s.y;
    int sgn;
    bool horz;
    switch (dir) {
    case 'E': ++x; sgn = 1; horz = true; break;
    case 'W': --x; sgn = -1; horz = true; break;
    case 'S': ++y; sgn = 1; horz = false; break;
    case 'N': --y; sgn = -1; horz = false; break;
    }
    if (s.b.get(x, y))
        /* Tile is not empty. */
        return;
    /* Make sure we don't run into an undeliberate fuse. */
    if (horz) {
        if (s.b.get(x + sgn, y) == '-' || s.b.get(x, y - 1) == '|' ||
            s.b.get(x, y + 1) == '|')
            return;
    } else {
        if (s.b.get(x, y + sgn) == '|' || s.b.get(x - 1, y) == '-' ||
            s.b.get(x + 1, y) == '-')
            return;
    }
    /* Ok. */
    add_state(
        states,
        max_length,
        max_area,
        /* After adding a firework, we can move in any direction. */
        {board(s.b).set(x, y, {*s.fw}), s.fw + 1, s.x, s.y, 'A'}
    );
}
void add_possible_moves(vector<state>& states, int max_length, int max_area,
                        const state& s) {
    /* We add the new states in reverse-desirability order. The most
     * (aesthetically) desirable states are added last. */

    const tile t = s.b.get(s.x, s.y);
    assert(t.is_fuse());

    /* Move in all (possible) directions. */
    for (char dir : "WENS")
        if (dir) add_movement(states, max_length, max_area, s, dir);

    /* If the fuse is too short for the next firework, keep adding fuse. */
    if (t.time < s.fw->time) {
        if (t == '-') {
            add_fuse(states, max_length, max_area, s, 'N', '|');
            add_fuse(states, max_length, max_area, s, 'S', '|');
            add_fuse(states, max_length, max_area, s, 'W', '|');
            add_fuse(states, max_length, max_area, s, 'W', '-');
            add_fuse(states, max_length, max_area, s, 'E', '|');
            add_fuse(states, max_length, max_area, s, 'E', '-');
        } else {
            add_fuse(states, max_length, max_area, s, 'W', '-');
            add_fuse(states, max_length, max_area, s, 'E', '-');
            add_fuse(states, max_length, max_area, s, 'N', '-');
            add_fuse(states, max_length, max_area, s, 'N', '|');
            add_fuse(states, max_length, max_area, s, 'S', '-');
            add_fuse(states, max_length, max_area, s, 'S', '|');
        }
    } else if (t.time == s.fw->time) {
        /* If we have enough fuse for the next firework, place the firework (if
         * possible) and don't add more fuse, or else we'll never finish... */
        if (t == '-') {
            add_firework(states, max_length, max_area, s, 'W');
            add_firework(states, max_length, max_area, s, 'E');
        } else {
            add_firework(states, max_length, max_area, s, 'N');
            add_firework(states, max_length, max_area, s, 'S');
        }
    }
}

void thread_proc(mutex& lock, int& total_length, int& total_area,
                    int& failures) {
    fireworks fw;
    vector<state> states;

    while (true) {
        /* Read input. */
        string input;
        {
            lock_guard<mutex> lg(lock);

            while (!cin.eof() && input.empty())
                getline(cin, input);
            if (input.empty())
                break;
        }
        fw.clear();
        int length = 0, area;
        {
            stringstream is;
            is << input;
            while (!is.eof()) {
                char c;
                int t;
                if (is >> c >> t) {
                    /* Fireworks must be sorted by launch time. */
                    assert(fw.empty() || t >= fw.back().time);
                    fw.push_back({c, t});
                    length += t;
                }
            }
            assert(!fw.empty());
            area = fw.back().time * fw.back().time;
        }

        /* Add initial state. */
        states.push_back({board().set(0, 0, {'-', 1}), fw.begin(), 0, 0, 'A'});

        board solution;
        int moves = 0;
        int frustration_moves = FRUSTRATION_MOVES;

        while (!states.empty()) {
            /* Check for solutions (all fireworks consumed.) */
            while (!states.empty() && states.back().fw == fw.end()) {
                state& s = states.back();
                /* Did we find a better solution? */
                if (solution.area() == 0 || s.b.length() < length ||
                    (s.b.length() == length && s.b.area() < area)
                ) {
                    solution = move(s.b);
                    moves = 0;
                    length = solution.length();
                    area = solution.area();
                }
                states.pop_back();
            }

            /* Expand the top state. */
            if (!states.empty()) {
                state s = move(states.back());
                states.pop_back();
                add_possible_moves(states, length, area, s);
            }

            /* Getting frustrated? */
            ++moves;
            if (moves > frustration_moves) {
                /* Get rid of some data. */
                states.erase(
                    states.begin() + states.size() * FRUSTRATION_STATES_BACKOFF,
                    states.end()
                );
                frustration_moves *= FRUSTRATION_MOVES_BACKOFF;
                moves = 0;
            }
        }

        /* Print solution. */
        {
            lock_guard<mutex> lg(lock);

            cout << input << endl;

            if (solution.area())
                cout << solution;
            else {
                cout << "FAILED!" << endl;
                ++failures;
            }

            cout << "Length: " << length <<
                    ", Area: " << area <<
                    "." << endl << endl;
            total_length += length;
            total_area += area;
        }
    }
}

int main(int argc, const char* argv[]) {
    thread threads[THREAD_COUNT];
    mutex lock;
    int total_length = 0, total_area = 0, failures = 0;

    for (int i = 0; i < THREAD_COUNT; ++i)
        threads[i] = thread(thread_proc, ref(lock), ref(total_length),
                            ref(total_area), ref(failures));
    for (int i = 0; i < THREAD_COUNT; ++i)
        threads[i].join();

    cout << "Total Length: " << total_length <<
            ", Total Area: " << total_area <<
            ", Failures: " << failures <<
            "." << endl;
}

```

---

## Python

## Total Length: 17387, Total Area: 62285, Failures: 44.

---

**Sample output:**

```
a 6 b 8 c 11 d 11 e 11 f 11 g 12 h 15 i 18 j 18 k 21 l 23 m 26 n 28 o 28 p 30 q 32 r 33 s 33 t 34
------a
     |----f
     |---c
     b|||---h
      |dg  |
      e    |-j
           |---k
           i  |
              |---m
              l  |-o
                 |--p
                 n |--s
                   |-r
                   q|
                    t
Length: 45, Area: 345.

```

---

**Full output:** http://pastebin.com/raw.php?i=mgiqXCRK

---

For reference, here's a much simpler approach. It tries to connect fireworks to a single main fuse line, creating a "staircase" shape. If a firework can't connect to the main line directly (which happens when two or more fireworks light at the same time) it traces back the main line looking for a point where it can branch perpendicularly down or to the right (and fails if no such point exists.)

Unsurprisingly, it does worse than the brute-force solver, but not by a *huge* margin. Honestly, I expected the difference to be somewhat bigger.

Run with: `python fireworks.py`.

```
from __future__ import print_function
import sys

total_length = total_area = failures = 0

for line in sys.stdin:
    # Read input.
    line = line.strip()
    if line == "": continue
    fws = line.split(' ')
    # The fireworks are a list of pairs of the form (<letter>, <time>).
    fws = [(fws[i], int(fws[i + 1])) for i in xrange(0, len(fws), 2)]

    # The board is a dictionary of the form <coord>: <tile>.
    # The first tile marks the "starting point" and is out-of-bounds.
    board = {(-1, 0): '*'}
    # The tip of the main "staircase" fuse.
    tip_x, tip_y = -1, 0
    tip_time = 0
    # We didn't fail. Yet...
    failed = False

    for (fw, fw_time) in fws:
        dt = fw_time - tip_time
        # Can we add the firework to the main fuse line?
        if dt > 0:
            # We can. Alternate the direction to create a "staircase" pattern.
            if board[(tip_x, tip_y)] == '-':    dx, dy = 0, 1; fuse = '|'
            else:                               dx, dy = 1, 0; fuse = '-'
            x, y = tip_x, tip_y
            tip_x += dt * dx
            tip_y += dt * dy
            tip_time += dt
        else:
            # We can't. Trace the main fuse back until we find a point where we
            # can thread, or fail if we reach the starting point.
            x, y = tip_x, tip_y
            while board[(x, y)] != '*':
                horz = board[(x, y)] == '-'
                if horz:    dx, dy = 0, 1; fuse = '|'
                else:       dx, dy = 1, 0; fuse = '-'
                if dt > 0 and (x + dx, y + dy) not in board: break
                if horz:    x -= 1
                else:       y -= 1
                dt += 1
            if board[(x, y)] == '*':
                failed = True
                break
        # Add the fuse and firework.
        for i in xrange(dt):
            x += dx; y += dy
            board[(x, y)] = fuse
        board[(x + dx, y + dy)] = fw

    # Print output.
    print(line)
    if not failed:
        max_x, max_y = (max(board, key=lambda p: p[i])[i] + 1 for i in (0, 1))
        for y in xrange(max_y):
            for x in xrange(max_x):
                print(board.get((x, y), ' '), end = "")
            print()
        length = len(board) - len(fws) - 1
        area = max_x * max_y
    else:
        print("FAILED!")
        failures += 1
        length = sum(map(lambda fw: fw[1], fws))
        area = fws[-1][1] ** 2
    print("Length: %d, Area: %d.\n" % (length, area))
    total_length += length; total_area += area

print("Total Length: %d, Total Area: %d, Failures: %d." %
        (total_length, total_area, failures))

```
> 3 votes

# Answer
# Python3

## Total length: 8343; Failures: 4; Total time: ~140.34 seconds

```
import collections, re, time

def shadow(board):
    return [["#" if b not in ['|', '-', ' '] else b for b in i] for i in board]

def full_length(s):
    return len(re.findall('\-|\|', s))

def adjust_board_size(_x, _y, board, mappings, cells):
    if _y < 0:
        _y = 0
        board = [[' ']+i for i in board]
        mappings = {(x, y+1):b for (x, y), b in mappings.items()}
        cells = [(x, y + 1) for x, y in cells]

    if _x < 0:
        _x = 0
        board = [[' ' for _ in board[0]]] + board
        mappings = {(x + 1, y):b for (x, y), b in mappings.items()}
        cells = [(x + 1, y) for x, y in cells]

    if _x == len(board):
        board = board + [[' ' for _ in board[0]]]

    if _y == len(board[0]):
        board = [i + [' '] for i in board]

    return _x, _y, eval(str(board)), eval(str(mappings)), eval(str(cells))

def draw_path(f, x_y, dist, d, depth, board, mappings, cells) -> iter:
    q = [(*x_y, *i, 0, board, mappings, cells, None) for i in d[:depth]]
    o_dist = mappings[x_y]
    while q:
        x, y, X, Y, prog, board, mappings, cells, smb = q.pop(0)
        if prog == dist:
            _x, _y = x + X, y + Y
            _x, _y, board, mappings, cells = adjust_board_size(_x, _y, board, mappings, cells)
            if (_x, _y) not in cells:
                cells.append((_x, _y))
                board[_x][_y] = f
                yield board, mappings, cells

            continue

        if smb is None:
            q.append((x, y, X, Y, prog, board, mappings, cells, '|' if board[x][y] == '-' else '-'))
            continue

        if (x+X, y+Y) in cells:
            q.extend([(x, y, X, Y, prog, board, mappings, cells, None) for X, Y in [(0, 1), (0, -1), (1, 0), (-1, 0)] if (x + X, y + Y) not in cells and x + X >= 0])
            continue

        _x, _y = x + X, y + Y
        _x, _y, board, mappings, cells = adjust_board_size(_x, _y, board, mappings, cells)
        prog += 1
        board[_x][_y] = smb
        mappings[(_x, _y)] = o_dist + prog
        cells.append((_x, _y))
        q.append((_x, _y, X, Y, prog, board, mappings, cells, smb))

def solver(t, depth = 3, option_depth = 2, board_depth = 3, breadth = -1) -> None:
    t = t.split()
    t = {t[i]:int(t[i+1]) for i in range(0, len(t), 2)}
    u_t = {b:a for a, b in t.items()}
    q = collections.deque([([['-' for _ in range(a)]+[b]], (mp:={(0,i):i+1 for i in range(a)}), [*mp], {*t}-{b})for a, b in [*u_t.items()][:len(u_t) if breadth == -1 else breadth]])
    seen = []
    results = []
    best_score = None
    while q:
        board, mappings, cells, f_works = q.popleft()
        #print('\n'.join(map(''.join, board)))
        if not f_works:
            results.append((board, mappings))
            best_score = len(mappings) if best_score is None else min(len(mappings), best_score)
            #print('got solution!')
            continue

        options = collections.defaultdict(list)
        for f in f_works:
            for (x, y), v in mappings.items():
                if (d:=[(X, Y) for X, Y in [(0, 1), (0, -1), (1, 0), (-1, 0)] if (x+X, y+Y) not in cells and ((board[x][y] == '-' and X) or (board[x][y] == '|' and Y))]):
                    if v + 1 == t[f]:
                        options[f].append(((x, y), 1, d))

                    elif v < t[f]:
                        options[f].append(((x, y), t[f] - v, d))

        #print(sorted([(a, min(b, key=lambda x:x[1])) for a, b in options.items()], key=lambda x:x[1][1]))
        #TODO: group on ties for best performance (include a suboptimal?)
        for f, ((x, y), dist, d), B in sorted([(a, min(b, key=lambda x:x[1]), sum(j[1] == min(b, key=lambda x:x[1]) for j in b)) for a, b in options.items()], key=lambda x:x[1][1])[:option_depth]:
            #print(B)
            if best_score is None or len(mappings) + dist < best_score:
                all_boards = []
                for _board, _mappings, _cells in draw_path(f, (x, y), dist, d, depth, board, mappings, cells):
                    if (S:=shadow(_board)) not in seen:
                        all_boards.append((_board, _mappings, _cells, f_works - {f}, S))

                for _board, _mappings, _cells, _f_works, S in all_boards[:board_depth]:
                    seen.append(S)
                    q.appendleft((_board, _mappings, _cells, _f_works))

    return best_score, sum(t.values())

```

### Usage:

```
total_length, failed = 0, 0
full_failed = []
t = time.time()
c = 0
for i in filter(None, cases.split('\n')):
    c += 1
    print(c)
    result, f = solver(i.strip(), depth = 1, option_depth = 1, board_depth = 1, breadth = 1)
    if result is None:
        result, f = solver(i.strip(), depth = 1, option_depth = 2, board_depth = 1, breadth = 1)
    if result is None:
        failed += 1
        total_length += f
    else:
        total_length += result

print(total_length, failed, time.time() - t)

```
> 1 votes

---
Tags: code-challenge
---


title: Help develop Alphys' newest puzzle!

text:
# Question
Title: Help develop Alphys' newest puzzle!
Alphys, the Underground's Royal Scientist, has finished a prototype for a new puzzle. However, she can't seem to find anyone willing to test it.

### The rules of her puzzle are as follows:

The goal is to get to the right side, starting from the centermost tile on the left side. For puzzles with even-numbered heights, start on the lower of the two center tiles. (Examples: In a zero-indexed 4x4 array, the starting position would be \[2,0\] - row 2, column 0. In a zero-indexed 5x5 array the starting position would be \[2,0\] - row 2, column 0.)

Each colored tile has its own "sadistic" function:

* Pink and green tiles (represented as "P" and "G") do nothing
* Red and yellow tiles ("R", "Y") are impassable.
* Orange tiles ("O") make the player smell like oranges
* Purple tiles ("U") force the player to the next tile in the direction they are facing and make them smell like lemons
* Blue tiles ("B") are passable as long as the player does *not* smell like oranges.

To clarify the flavor mechanic, a player's smell will persist indefinitely or until overridden by a different-smelling tile, i.e. if a player steps on an orange tile they will smell like oranges until they step on a purple tile.

Additionally, a yellow tile placed vertically or horizontally adjacent to a blue tile will cause the blue tile to become impassable as well.

Your task is to write a program or function that accepts a 2-dimensional character array (or 1D string array, or some other valid format) representing the puzzle's layout as input and outputs both the original puzzle and the solved puzzle, with asterisks or some other character showing the correct path. Assume that the given puzzle is solveable.

Use this puzzle as an example:

```
BGYBG
PGPBG
PUBPB
OUGYB
PPOPP

```

Your program would output:

```
BGYBG
PGPBG
PUBPB
OUGYB
PPOPP

BGYBG
PGPBG
*****
OUGYB
PPOPP

```

Any puzzle used must be generated using this.

Standard code golf rules apply. Best answers will be the shortest for each language. Answers must contain the language, number of bytes, and three test cases. The first two can be any layout you choose, but the third must be:

```
RRRR
RPPR
PUOR
RPBP

```

# Answer
## C 529 bytes

```
#define M m[y][x]
char**m,*l,i;main(Y,X){for(;scanf("%ms",&l)>0;)(m=realloc(m,Y*8))[Y-1]=l,X=puts(m[Y++-1])-2;puts("");int s(x,y,c,d){(x<0|y<0|y/Y)?:({if(M^'R'&&M^'Y')if(M^'B'||c^2&&!((y&&m[y-1][x]=='Y')|(x&&m[y][x-1]=='Y')|(y<Y-1&&m[y+1][x]=='Y')|(x<X-1&&m[y][x+1]=='Y'))){x^X?:({M='#';return 1;});c=M^'O'?c:2;M^'U'?:({return s(x+(d<4?d-2:0),y+(d>3?d-5:0),1,d)?({M='#';1;}):0;});if(d^1&&s(x+1,y,c,3)||d^4&&s(x,y+1,c,6)||d^6&&s(x,y-1,c,4)||d^3&&s(x-1,y,c,1)){M='#';return 1;}}});return 0;}s(0,--Y/2,0,3);for(;i<Y;)puts(m[i++]);}

```

We approach the puzzle by stepping first to the right, provided we are not blocked, then trying up, then down and finally back to the left. The search is recursive and once we identify a successful path, we mark the spaces in our matrix and return.

## Try it Online

### Ungolfed

```
#include <stdio.h>
#include <malloc.h>
char**m,*l,i;
main(Y,X) {
  for(Y=1;scanf("%ms",&l)>0;Y++)
      m=realloc(m,Y*8),
      m[Y-1]=l,
      X=puts(m[Y-1])-2;
  puts("");
  int step(x,y,c,d,i){
    if(x<0||y<0||y>=Y)return 0;
      if(m[y][x]=='R'||m[y][x]=='Y')return 0;
      if(m[y][x]=='B'&&(c==2||(y&&m[y-1][x]=='Y')||(x&&m[y][x-1]=='Y')
               ||(y<Y-1&&m[y+1][x]=='Y')||(x<X-1&&m[y][x+1]=='Y')))return 0;
      if(x==X){m[y][x]='#';return 1;}
      if(m[y][x]=='O')c=2;
      if(m[y][x]=='U')return step(x+(d<4?d-2:0),y+(d>3?d-5:0),1,d,i+1)?({m[y][x]='#';1;}):0;
      else if((d!=1&&step(x+1,y,c,3,i+1)) ||
    (d!=4&&step(x,y+1,c,6,i+1)) || (d!=6&&step(x,y-1,c,4,i+1)) ||
    (d!=3&&step(x-1,y,c,1,i+1))) {m[y][x]='#';return 1;}
      return 0;
  }
  step(0,--Y/2,0,3,0);
  for(;i<Y;)puts(m[i++]);
}

```

---

### Example Output 1

```
PYYOPPPP
YRGGRYRG
PGPBYPUR
PYRBOYOG
OBPGYYPP
PRGPOYPO
YPYOUGPP
YGROBRYY
RGRYBBOG

PYY#####
YR##RYRG
###BYPUR
#YRBOYOG
#BPGYYPP
PRGPOYPO
YPYOUGPP
YGROBRYY
RGRYBBOG

```

### Example Output 2

```
PBYRYPGP
OBRGOOBG
PGPGUROO
PUGORBUG
PUPUUURO
BGGUYPRG
GBOPGGRG
PUPUBUYB
GYOPRPOG

PBYRYPGP
OBRGOOBG
PGPGUROO
PUGORBUG
###UUURO
BG#UYPRG
GB####RG
PUPUB#YB
GYOPR###

```

### Example Output 3

```
RRRR
RPPR
PUOR
RPBP

RRRR
R##R
###R
R###

```
> 2 votes

# Answer
# Python3, 640 bytes

```
M=[(1,0),(-1,0),(0,-1),(0,1)]
E=enumerate
def f(b):
 D=eval(str(b))
 C=[(j,k)for j,r in E(b)for k,_ in E(r)]
 q=[(len(b)//2,0,b,0,{})]
 while q:
  x,y,b,s,m=q.pop(0)
  b[x][y]='#'
  if y==len(b[0])-1:return b
  for X,Y in M:
   if(K:=(x+X,y+Y))in C and K not in m.get((x,y),[])and(B:=D[x+X][y+Y])not in['R','Y']and(B!='B'or(s!=1 and[]==[1 for Q,W in M if(x+X+Q,y+Y+W)in C and'Y'==D[x+X+Q][y+Y+W]])):
     I=eval(str(b));P={**m,(x,y):m.get((x,y),[])+[K]}
     if'U'==B:
      T=2;I[x+X][y+Y]='#';Z,G=x+X+X,y+Y+Y;J,K=[K,(Z,G)][(Z,G)in C]
      if D[J][K]not in['R','Y']:q+=[(J,K,I,[T,1]['O'==D[J][K]],P)]
     else:q+=[(*K,I,[s,1]['O'==B],P)]

```

Try it online!
> 0 votes

---
Tags: code-golf, game, path-finding
---


title: Construct this point

text:
# Question
Title: Construct this point
Given a constructible point \\$(x, y) \in \mathbb R^2\\$, output the steps required to construct \\$(x, y)\\$

### Constructing a point

Consider the following "construction" of a point \\$(\alpha, \beta)\\$ in the Cartesian plane:

Begin with the points \\$(0, 0)\\$ and \\$(1, 0)\\$. Then, more points can be added by performing a finite number of the following steps:

* Draw the unique infinitely long line between two existing points \\$(x, y)\\$ and \\$(x', y')\\$
* Draw the unique circle centered on an existing point \\$(x, y)\\$ that passes through a distinct existing point \\$(x', y')\\$
* Add a point \\$(x, y)\\$ where any two lines or circles intersect

For example, if we draw the line connecting \\$(0, 0)\\$ and \\$(1, 0)\\$, then the circle centered on \\$(1, 0)\\$ with radius \\$1\\$ (passes through \\$(0, 0)\\$), we can construct the point \\$(2, 0)\\$ where the circle and line intersect. Now, if we draw the circles centered on \\$(0, 0)\\$ and \\$(2, 0)\\$ that pass through \\$(2, 0)\\$ and \\$(0, 0)\\$ respectively, we construct the point \\$(1, \sqrt 3)\\$, and so on.

If both \\$x\\$ and \\$y\\$ are constructible numbers (i.e. there exists some closed form expression of \\$x\\$ and \\$y\\$ involving only integers, the 4 basic arithmetic operations and square roots), then \\$(x, y)\\$ can be constructed in a finite number of these steps.

---

This is a challenge, where you are provided, in exact form, two constructible numbers, \\$x\\$ and \\$y\\$, and should output the steps to construct the point \\$(x, y)\\$, beginning from the initial set of points \\$S = \\{(0, 0), (1, 0)\\}\\$.

As both \\$x\\$ and \\$y\\$ are constructible, they can be expressed as a finite combination of addition, multiplication, division, subtraction and square roots of integers - termed here as "closed form numbers". You may take input in any form that exactly represents any closed form number. This could be as an exact symbolic number (if your language has these), a string unambiguously representing the composition of the 5 operations (e.g. `7*sqrt(2)-sqrt(3)`, `7*s2-s3` or even `sub(times(7, sqrt(2)), sqrt(3)))`, and so on. **You may not input as floating point values.** Note that the format you choose should be unambiguous for all possible inputs.

In short, you may choose any input format - not limited to strings - so long as that input format can represent any closed form number exactly and unambiguously. Additionally, be mindful of this standard loophole about encoding extra information into the input format - this is fairly loose, but try not to use formats that contain more information than just the 5 standard operations.

As output, you should produce some list of operations that, if followed, add the point \\$(x, y)\\$ to the set of constructed points \\$S\\$. By default, we will assume that all new points after each step are automatically added to \\$S\\$, and so you only need to output two possible instructions at each step:

* Draw a circle centered at a point \\$(a, b)\\$ going through a point \\$(c, d)\\$
* Draw a line through the points \\$(a, b)\\$ and \\$(c, d)\\$

This can be in any format that clearly includes both points necessary for each instruction, and which instruction is used. At the most basic, the options of `[0, a, b, c, d]` and `[1, a, b, c, d]` for circle and line respectively are completely fine. In short, you must be able to unambiguously distinguish each instruction from the next, the circle instruction from the line, and the two points \\$(a, b)\\$ and \\$(c, d)\\$. However, the values of \\$a, b, c, d\\$ must be exact constructible numbers.

Note that you may output *any* finite valid list of steps, not just the shortest.

This is a challenge, so the shortest code in each language wins

---

## Worked example

Take the point \\$H = (\sqrt 3, \sqrt 3)\\$. This can be constructed in 8 steps, with the first point in the circle instruction being the center:

```
Line: (0, 0), (1, 0)
Circle: (1, 0), (0, 0)
Circle: (2, 0), (0, 0)
Circle: (0, 0), (2, 0)
Circle: (4, 0), (2, 0)
Line: (1, 0), (1, √3)
Line: (1, √3), (3, √3)
Line: (0, 0), (1, 1)

```

The construction lines from this can be seen as:

This can be extended with 5 more lines to construct the more complicated point \\$(\sqrt 3, \sqrt 2)\\$:

```
Line: (2, 0), (1, 1)
Line: (1, -√3), (3, -√3)
Line: (0, 0), (1, -1)
Line: (2-√2, √2), (√2, √2)
Line: (√3, √3), (√3, -√3)

```

## Test cases

*To be completed*

Here, we use `C (a, b), (x, y)` to represent a circle with center \\$(a, b)\\$ and `L (a, b), (x, y)` a line that passes through the two points.

```
(x, y) -> Steps
(0, 0) -> []
(6, 0) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (4, 0), (2, 0)"]
(1, √3) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (0, 0), (2, 0)", "C (2, 0), (0, 0)"]
(1, 1) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (0, 0), (2, 0)", "C (4, 0), (2, 0)", "L (1, 0), (1, √3)"]
(-1/2, √2) -> ["L (0, 0), (1, 0)", "C (0, 0), (1, 0)", "C (-1, 0), (0, 0)", "L (-1/2, √3/2), (-1/2, -√3/2)", "C (1, 0), (0, 0)", "C (0, 0), (2, 0)", "C (2, 0), (0, 0)", "L (1, 0), (1, √3)", "L (0, 0), (1, 1)", "L (0, 0), (1, -1)", "L (√2, √2), (-√2, √2)"]
(1+√3+√2/2, 0) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (0, 0), (2, 0)", "L (1, √3), (1, 0)", "C (4, 0), (2, 0)", "L (1, √3), (3, √3)", "L (0, 0), (1, 1)", "L (2, 0), (1, 1)", "L (1, -√3), (3, -√3)", "L (√2, √2), (2, 0)", "L (2-√2, √2), (0, 0)", "C (1, 0), (1, 1+√2)", "L ((1+√2)/√2, 1/√2), ((1+√2)/√2, -1/√2)", "C ((1+√2)/√2, 0), ((1+√2)/2, √3))"]
(√2+√3, √5) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (0, 0), (2, 0)", "L (1, √3), (1, 0)", "L (0, 0), (1, 1)", "L (0, 0), (1, -1)", "L (√2, √2), (√2, -√2)", "C (4, 0), (2, 0)", "L (1, √3), (3, √3)", "C (0, 0), (√2, √3)", "C (0, 0), (1, 0)", "C (√2, 0), (√2, √3)", "L (0, 1), (0, -1)", "C (0, √5), (0, 0)", "L (0, √5), (√5, √5)", "C (√2+√3, 0), (0, 0)", "L (√2+√3, 0), (√2+√3, √2+√3)"]

```

# Answer
> 11 votes
# Python, 511 bytes

```
l=[(1,0,0,1,0)]
z,o='01'
def a(b,c):e=f'da{b}{c}2';v='dtm%s%ss32';l.extend([(0,b,0,c,0),(0,c,0,b,0),(1,e,v%(b,c),e,v%(c,b)),(0,e,0,0,0)]);return'a'+b+c
def m(b,c):l.append((0,0,0,c,0));return a(b,'m0'+c)
def t(b,c):l.append((1,0,p(b),p(c),p(m(b,o))));return't'+b+c
def d(b,c):l.append((1,0,1,p(b),p(m(o,c))));return'd'+b+c
def s(b):v=d(m(b,o),a(o,o));l.append((0,0,v,0,'m01'));return's'+b
def p(b):a(a(b,b),z);l.extend((a,c,b,e,d) for a,b,c,d,e in l[:]);return b
m(o,o)
def e(b,c):p(eval(b));p(eval(c));return l

```

Attempt This Online!

If we can assume the user evaluated the functions (so we don't have to call `eval`), we can just do `e=lambda a,b:l`.

The function is `e`, it takes as input the two coordinates. `a` is addition, `m` subtraction, `t` multiplication, `d` division, and `s` square root. `o` has to be used in place of `1`, and `z` in place of 0.

Returns a list of objects to create, specifying coordinates in prefix notation, with single digits (so `a32 = 5`).

Here's how it works for \\$(\sqrt2, 3)\\$, for example:

The animation code:

```
import math
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Circle

def calc(s: str):
    if type(s) is int:
        return s, ''
    if s[0].isdigit():
        return int(s[0]), s[1:]
    v1, rem = calc(s[1:])
    if s[0] == 's':
        return v1**.5, rem
    v2, rem = calc(rem)
    return (v1+v2 if s[0]=='a' else v1-v2 if s[0]=='m' else v1*v2 if s[0]=='t' else v1/v2 if s[0]=='d' else None), rem

var = plt.subplots()
fig : plt.Subplot = var[0]
ax : plt.Axes = var[1]

artists = []

points = set()

dat = e('s(a(o,o))','s(a(o,a(o,o)))')
print(len(dat))
ax.axis('equal')
ax.plot(2**.5, 3**.5, 'bo')
objects = set()
for a, b, c, d, e in dat:
    b, c, d, e = (calc(x)[0] for x in (b, c, d, e))
    if (a,b,c,d,e) in objects:
        continue
    objects.add((a,b,c,d,e))
    if (b, c) not in points:
        artists.append(ax.plot(b, c, 'ro')[0])
        points.add((b, c))
    if (d, e) not in points:
        artists.append(ax.plot(d, e, 'ro')[0])
        points.add((d, e))
    if a == 1 and (b,c) != (d,e):
        artists.append(ax.axline((b,c),(d,e)))
    else:
        artists.append(ax.add_patch(Circle((b,c), math.hypot(b-d, c-e), fill=False)))

def update(frame):
    for i, art in enumerate(artists):
        art.set_visible(i < frame)

ani = animation.FuncAnimation(fig=fig, func=update, frames=len(artists)+20, interval=100)
plt.interactive(True)
plt.show(block=True)

```

# Answer
> 7 votes
# JavaScript (Node.js), 366 bytes

```
P=(a,b=0,c=0,d=0,e=0)=>console.log(a,b,c,d,e)
L=x=>P(0,x)|P(x)|P(y=x+'/2',z=x+'/2*s3')|P(y,z,0,0,1)|P(x,z+'*2',x,0,1)
S=(b,a)=>`(${P(0,0,1,0,1),P(0,0,b)|P(b)|P(b+'/2',b+'/2*s3',a),b}-${a})`
D=(a,b)=>S(1,`(1-${P(a,0,S(a,b))|L(a)|L(1)|P(1,0,1,z=`(${a}/${b})`),z})`)
s=a=>P(S(0,1),0,a)|P(a,0,-1)|P(z=`(${a}-1)/2`,y=`(${a}+1)/2*s3`,z,-1+y,1)|P(z,0,a)|P(0,0,0,z='s'+a)||z

```

Try it online!

-24 from emanresu A

0 a b c d mean circle (a,b) through (c,d)

1 a b c d mean line through (a,b) and (c,d)

Should be quite golfable

* `L` provides line \\$x=x\_0\\$, assuming \\$x\_0 \neq 0\\$
* `S` subtracts two values
* `D` divides two values while creating point with given coords
* `s` gives square root

## Notes

* Need confirm
* Some free points may sometimes give good: To draw \\$x=0\\$, a sequence `Line((0,0),(1,0)), Circle((a,b),(0,0)), Line((2a,0),(a,b)), Line((0,2b)-(0,0))` should be shorter than always based on existing points, but that'd be complex-expressed
* Since taking a sequence of operations also "can represent any closed form number exactly and unambiguously", I assume it be a subset of `+-*/sqrt`

---
Tags: code-golf, math, number-theory, geometry, abstract-algebra
---


# Question
Title: All you have to do is print the number 1! ...Twice
# Your task

In your language of choice: create a program that outputs `1`

This `1` may either be a string or value equivalent to the number one.

# The shifting catch

If you take the **unicode codepoint** (or whatever codepoint encoding your languages uses if not UTF) for each character in your program, and shift each of those values by the **same non-zero amount**, then the result will be another program (potentially executable in different language) that also outputs `1`.

**Find the unicode codepoint of a character:** here.

**E.g;**

If your program looked like: `X?$A`, and somehow output `1`, and it also miraculously outputs `1` after shifting all of it's Unicode indices up by, say, 10; then that process of shifting looks like this:

```
original program: X?$A

letter    codepoint  shift   new-codepoint   new-letter

X            88       +10        98          b
 ?           63                  73          I
  $          36                  46          .
   A         65                  75          K

new program: BI.K

```

**Note:** The Unicode codepoint will often be represented in the form similar to `U+0058`. `58` is the **hexadecimal** codepoint . In **decimal**, that's `88`. The link above will list `88` under the `UTF (decimal)` encoding section. That is the number you want to increment or decrement!

# Examples of valid outputs

```
1
"1"
'1'
[1]
(1)
1.0
00000001
one

```

**Note:** If your language only supports the output of `true` as an equivalent to `1`, that is acceptable. Exit-codes are also valid outputs.

# Scoring

* This is , so **lowest bytes wins**!
* Brownie points for creativity & if the two programs are in separate languages.

# Answer
> 35 votes
# Java, 62 bytes

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

```

Try it online.

# 05AB1E, 62 bytes

```
\agXeYTVXι@nfgTg\Vιib\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp

```

Uses the 05AB1E encoding, with the codepoints all decreased by 13:

* `interface M{static void main(String[]a){System.out.print(1);}}` has the codepoints `[105,110,116,101,114,102,97,99,101,32,77,123,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,49,41,59,125,125]`
* `\agXeYTVXι@nfgTg\Vιib\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp` has the codepoints `[92,97,103,88,101,89,84,86,88,19,64,110,102,103,84,103,92,86,19,105,98,92,87,19,96,84,92,97,27,70,103,101,92,97,90,78,80,84,28,110,70,108,102,103,88,96,33,98,104,103,33,99,101,92,97,103,27,36,28,46,112,112]`.

Try it online.

### Explanation:

**Java:**

```
interface M{                   // Full program:
  static void main(String[]a){ //  Mandatory main-method:
    System.out.print(          //   Print without trailing newline:
      1);}}                    //    Print 1

```

**05AB1E:**

```
\                  # Discard the top of the stack (no-op, since it's already empty)
                   #  STACK: []
 a                 # Check if it only consists of letters (resulting in falsey/0
                   # for an empty string "", which is used implicitly without input)
                   #  STACK: [0]
  g                # Push and push its length, which is 1
                   #  STACK: [1]
   X               # Push variable `X`, which is 1 by default
                   #  STACK: [1,1]
    e              # Push the number of permutations n!/(n-r)! with both 1s, which is 1
                   #  STACK: [1]
     Y             # Push variable `Y`, which is 2 by default
                   #  STACK: [1,2]
      T            # Push builtin 10
                   #  STACK: [1,2,10]
       V           # Pop and store it in variable `Y`
                   #  STACK: [1,2]
        X          # Push variable `X` again, which is 1 by default
                   #  STACK: [1,2,1]
         ι         # Uninterleave using the 2 and 1, resulting in ["2"]
                   #  STACK: [1,["2"]]
          @        # Check whether 1 is >= ["2"], resulting in [0]
                   #  STACK: [[0]]
           n       # Square it
                   #  STACK: [[0]]
            f      # Get a list of all prime factors (none for 0), which results in []
                   #  STACK: [[[]]]
             g     # Pop and push its length
                   #  STACK: [1]
              T    # Push builtin 10
                   #  STACK: [1,10]
               g   # Pop and push its length
                   #  STACK: [1,2]
                \  # Discard it
                   #  STACK: [1]
                 V # Pop and store it in variable `Y`
                   #  STACK: []

```

From here on out I can't really explain it anymore, since it does things I wasn't expecting:

```
ι                  # Uninterleave (would take either one or two arguments, but since the
                   # stack is empty, it somehow remembered the 1 that was previously on
                   # the stack and results in ["1"] -
                   # A program `ι` without input would result in an error instead..)
                   #  STACK: [["1"]]
 i                 # If-statement, which will be entered if the top is 1;
                   # since it's ["1"] instead of 1, it won't enter
                   #  STACK: []
  b\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp
                   #  No-ops within the if-statement
                   # It again somehow remembers the previous ["1"] that was on the stack,
                   # which is output implicitly as result

```

# Answer
> 32 votes
# 05AB1E, 3 bytes

```
1*1

```

(Works in Japt too.)

Try it online!

# Japt, 3 bytes

```
6/6

```

Try it online!

Derived from the 05AB1E program by shifting by 5 *Unicode* codepoints.

The Japt program performs division, but don't be fooled into thinking that the 05AB1E program is performing multiplication. The `*` (square) operator acts only on the first `1`; the output is actually just an implicit print of the second `1`.

The same idea works with the 05AB1E/Japt program pairs `1-1` and `3/3` (shift 2) and `1+1` and `5/5` (shift 4).

# Answer
> 19 votes
# Python 3, ~~19~~ 17 bytes

**-2 bytes thanks to Jonathan Allan**

```
#]pal )!␛
exit(1)

```

Try it online!

## Shifted +8

```
+exit(1)#␒m␣q|091

```

Try it online!

where ␛, ␒ and ␣ are literal `\x1b`, `\x12` and `\x80` bytes respectively.

Not much by the way of trickery going on here except prepending the print in the shift version with a `+` so that when we shift it the first character of the second program to the `#` character it doesn't send any characters into a negative codepoint (if we naïvely shifted `e` back to `#`, `(` would be sent to `\x-` which doesn't exist). Outputs by exit code.

# Answer
> 16 votes
# 05AB1E, 2x 1 byte

Without an input, any of these single characters will output `1`, so just pick two you like. :)

* `1` (self explanatory): Try it online.
* `X` (variable, which is 1 by default): Try it online.
* (`!= 1` check; without input it will do `"" != 1`, resulting in truthy/1): Try it online.
* `@` (`>=` check; without input it will do `"" >= ""`, resulting in truthy/1): Try it online.
* `Q` (`==` check; without input it will do `"" == ""`, resulting in truthy/1): Try it online.

# Answer
> 13 votes
# APL (Dyalog Unicode), 2x2 bytes

```
*0
+1

```

Try it online!

`*0` computes `e^0`, and `+1` computes complex conjugate of 1. `*0` has Unicode codepoint 42 and 48, and `+1` has 43 and 49, so the two are different by exactly one.

Also works in many different flavors of APL, including... (copied from Adám's APL bounty)

> Dyalog APL Classic/Unicode/Extended/Prime, APL2, APL+, APLSE, GNU/APL, Sharp APL, sAPL, SAX, NARS, APLX, A+, dzaima/APL, ngn/APL, APL\iv, Watcom APL, or APL\360.

... which makes this a polyglot of at least 19 languages!

# Answer
> 12 votes
# Unary, 84 bytes

```
000000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

Outputs the character with codepoint 1 (equivalent brainfuck: `+.`). Since Unary cares only about the length of the program, a shift of any number will not change the output.

# Answer
> 12 votes
# HTML, 8 bytes

```
<ol><li>
```

---

# 05AB1E, 8 bytes

```
!TQ#!QN#

```

Try it online!

---

# Jelly, 8 bytes

```
([X*(XU*

```

Try it online!

---

# Jelly, 8 bytes

```
5he75eb7

```

Try it online!

---

# Jelly, 8 bytes

```
;nk=;kh=

```

Try it online!

---

# 05AB1E, 8 bytes

```
@spB@pmB

```

Try it online!

---

# Jelly, 8 bytes

```
H{xJHxuJ

```

Try it online!

---

# 05AB1E, 8 bytes

Outputs `["1"]`.

```
Q„SQ~S

```

Try it online!

---

# 05AB1E, 8 bytes

```
V‰†XV†ƒX

```

Try it online!

---

# 05AB1E, 8 bytes

```
X‹ˆZXˆ…Z

```

Try it online!

---

# 05AB1E, 8 bytes

```
]_]Š_

```

Try it online!

---

# 05AB1E, 8 bytes

```
a”‘ca‘Žc

```

Try it online!

---

# 05AB1E, 8 bytes

```
e˜•ge•’g

```

Try it online!

---

# 05AB1E, 8 bytes

```
kž›mk›˜m

```

Try it online!

---

("Pffffft! Of *course* I know how 05AB1E and Jelly work! I *totally* didn't just brute-force a bunch of combinations on TIO. That would be crazy! It would *never* work!")

# Answer
> 9 votes
# CSS, 48 bytes

```
body:after{content:"1"}z|ancx9`esdqzbnmsdms9!0!|
```

```
cpez;bgufs|dpoufou;#2#~{}body:after{content:"1"}
```

# Answer
> 8 votes
# !@#$%^&\*()\_+, 4 bytes

```
1@/>

```

Try it online!

## Explanation

```
1    # Pushes 1
 @   # Prints top of the stack (1)
  /> # Pushes some meaningless stuff

```

# Shifted +2

```
3B1@

```

Try it online!

## Explanation

```
3B   # Pushes some meaningless stuff
  1  # Pushes 1
   @ # Prints top of the stack (1)

```

# Answer
> 7 votes
# Pyth, 2 bytes

```
s1

```

Try it online!

# Pyth, 2 bytes, Shifted +1

```
t2

```

Try it online!

---

First Program translates to `floor(1)`
Second Program translates to `2 - 1`

# Answer
> 7 votes
# Whitespace, 2 x 18 bytes

```
" " " ␋ ␌
␋   ␌
" ␋

```

Try it online..

All codepoints decreased by 2 will result in:

```
 ␟ ␟ ␟  ␇
␈   ␇
␈ ␟ ␇

```

Try it online.

Both programs contain unprintables. The first program contains characters with the codepoints: `[34,32,34,32,34,32,11,9,12,10,11,9,12,10,34,32,11,9]`. The second program with codepoints: `[32,30,32,30,32,30,9,7,10,8,9,7,10,8,32,30,9,7]`. In Whitespace, all characters except for spaces (codepoint 32), tabs (codepoint 9), and newlines (codepoint 10) are ignored, so both programs are actually the following:

```
SSSTN
TN
ST

```

Where `S`, `T`, and `N` are spaces, tabs, and newlines respectively.

This program will:

* `SSSTN`: Push 1
* `TNST`: Print it as integer to STDOUT

It's actually possible to create 3 x 27 bytes, 4 x 36 bytes, and even 5 x 45 bytes programs by having the codepoints apart by 2, still resulting in the same basic program above after all non-whitespace characters are ignored.

# Answer
> 7 votes
# J, ~~3~~ 2 bytes

```
=0

```

Monadic `=` means self-classify. It compares each item with each other item to see if it's the same. 0 is 0. It returns 1.

# Shifted +1

```
>1

```

Unboxes 1, which does nothing, because it wasn't in a box in the first place.

## Alternate 2-byters:

`!1` (1 factorial) shifted by 2 is `#3` (amount of items in 3)

`!0` (0 factorial) shifted by 2 is `#2` (amount of items in 2) shifted by 7 is `*9` (sign of 9)

# Answer
> 7 votes
# JavaScript (web), 19 bytes

## Form #1

```
`kdqs_0_:`;alert`1`

```

## Form #2 (#1 shifted by +1)

```
alert`1`;a<bmfsua2a

```

This took me longer than what I'd like to admit, but it was a fun challenge.

Form #2 throws a `ReferenceError`, but that seems to be allowed.

# Answer
> 6 votes
# brainfuck, 3 bytes

Outputs the character with the codepoint 1. This is allowed by default.

```
(+.

```

Try it online!

# Shifted +3

```
+.1

```

Try it online!

## Explanation

The `+` character increments the current item of the tape, and `.` outputs that value as a character. All other characters are ignored.

# Answer
> 6 votes
# Polyglot, 3 bytes

Shift of 2. Works in R, Octave, Japt, and probably others.

```
1+0
3-2

```

Try it online (Octave)

Try it online (R)

Try it online (Japt)

# Answer
> 5 votes
# Japt, 1 byte

Among many others:

```
1

```

Test it

```
Ä

```

Test it

```
l

```

Test it

# Answer
> 5 votes
# , 4 bytes

```
\061\043\030\077

```

(octal bytes, equivalent to: `'1' '#' CAN '?'`)

Shifted -14:

```
\043\025\012\061

```

(octal bytes, equivalent to `'#' NAK LF '1'`)

Unshifted program consists of number 1 (which is outputted unchanged), followed by `#` (comment character) and 'comments' of CAN (ASCII code \030) and '?'.

Shifted +14 program consists of `#` (comment character) and 'comment' of NAK (ASCII code \025), followed by a new line. On the next line is the number 1 (which is outputted unchanged).

Test at bash command-line using `echo` (or `gecho`):

```
echo -e '\061\043\030\077' >prog1.r
echo -e '\043\025\012\061' >prog2.r
Rscript prog1.r
# [1] 1
Rscript prog2.r
# [1] 1

```

# Answer
> 4 votes
# Io, 6 bytes

```
1print

```

Try it online!

# Commentator, (Shifted -17)

```
 _aX]c

```

Try it online!

# Answer
> 4 votes
# naz, 4 bytes

```
1a1o

```

**Explanation**

```
1a # Add 1 to the register
1o # Output once

```

# 05AB1E, 4 bytes

```
2b2p

```

A shift of 1 Unicode codepoint forward from the original.

**Explanation**

```
2    # Push 2
 b   # Convert to binary
  2  # Push 2
   p # Push isPrime(2)
# ...after which the result is output implicitly

```

# Answer
> 4 votes
# Jelly, 1 byte

`¬` (logical NOT) vs  (increment)

**Try `¬` online!** or **Try  online!**

This works because given no input a Jelly program has a default argument of `0`.

There are \\$\binom{21}{2}=210\\$ different pairs of single-byte programs to choose from since there are \\$21\\$ single bytes on Jelly's code-page which yield `1` with no input:

# Answer
> 3 votes
# Keg, 1 byte (SBCS)

```
1

```

Try it online!

Implicitly outputs 1

## Shifted +198

```

```

Try it online!

Uses the push'n'print to print 1

# Answer
> 3 votes
## Batch, ~~27~~ 17 bytes

```
:_]bi�+�4
@echo 1

```

The `:` introduces a label of unprintables, so the line is ignored, and the second line prints `1`. Shifted by 6:

```
@echo 1
:�Fkinu&7

```

Much the same, except this time the second line is ignored.

Unfortunately I've mangled the unprintables. Sorry about that. Feel free to fix it.

# Answer
> 3 votes
# ;#+, 4 bytes

```
9n;p

```

Try it online!

# ;#+, 4 bytes, Shift +2

```
;p=r

```

Try it online!

---

## Explanation

`;` \- increments the counter
`p` \- outputs the counter as a number

`9`, `n`, `=` and `r` are not commands in ;#+ so they can be ignored.

# Answer
> 2 votes
# V (vim), 6 bytes

```
i1<esc><nul>h0

```

# Answer
> 2 votes
# bc (?), 3 bytes

```
1+0

```

Shift 2:

```
3-2

```

Use as `echo 1+0 | bc` in bash.

# Answer
> 2 votes
# Hexagony, 5 bytes

```
=-1!@

```

Try it online!

# Hexagony, 5 bytes, Shifted -12

```
1!%4

```

**Hexdump:**

```
00000000  31 21 25 15 34     |1!%.4|

```

Try it online!

# Explanation

Because of the small size and lack of mirrors, the programs are mostly executed linearly.

### Non-shifted Program

```
=       Reverse direction of memory pointer
 -      Sets the current memory edge to the difference of the left and right neighbors (0 - 0 = 0)
  1     Multiply current memory edge by 10 then add 1 (0 * 10 + 1 = 1)
   !    Outputs the value of current memory edge to stdout as an integer
    @   Terminate the program

```

### Shifted Program

```
1       Multiply current memory edge by 10 then add 1 (0 * 10 + 1 = 1)
 !      Outputs the value of current memory edge to stdout as an integer
  %     Sets the current memory edge to the modulo of the left and right neighbours
        (1 % 0) causes program to exit because of division by 0
    4   Does not matter since the program as already exited

```

# Answer
> 2 votes
# `pdfTeX -halt-on-error`, 1 byte

```
_

```

and

```
^

```

Both versions will throw an error as `_` and `^` are only allowed in math-mode. Will return a 1 as exit code (due to the error).

# Answer
> 2 votes
# Perl 5 -p, 8 bytes + 1 byte/keypress input = 9 bytes

*Edit: -2 bytes and much nicer printable programs thanks to Dom Hastings*

Each program requires input of 1 byte, or a single carriage-return keypress. I've counted this as +1 byte, but I'm not terribly sure how valid this is...

```
$_++#^**

```

Try it online!

Shifted +1:

```
%`,,$_++

```

Try it online!

One might (validly) argue that since the extra input/keypress is part of the byte-count, it should also be shifted along with the codepoints of the program. Fortunately, there are inputs for which this works Ok:

```
echo 'a' | perl -pe '$_++#^**'
# 1
echo 'b' | perl -pe '%`,,$_++'
# 1

```

# Answer
> 2 votes
**JavaScript, 3**

`3-2` becomes `2,1` shifted by -1.
`1+0` becomes `2,1` shifted by +1.

Which is cool because `1+0` shifted by one becomes `2,1` shifted by one becomes `3-2` all three produce 1

---

```
let code = '1+0';
console.log (code, eval(code));
code = code.split('').map(c => String.fromCharCode(c.charCodeAt(0) + 1)).join('');
console.log (code, eval(code));
code = code.split('').map(c => String.fromCharCode(c.charCodeAt(0) + 1)).join('');
console.log (code, eval(code));
```

# Answer
> 2 votes
# CJam, 1 byte

```
1
```

```
X

```

For whatever reason, CJam has `X` as a builtin for 1, and since it outputs implicitly, you can just use those two. However, I thought it'd be more interesting to find a 2-byte solution.

```
XR

```

Try it online!

Offset by +38:

```
2,

```

Try it online!

Explanations:

```
X    Push 1 to the stack
 R   Push an empty array to the stack
     (implicit) Output the stack

```

```
2    Push 2 to the stack
 ,   Pop and push range from 0 to 1 less than the popped number
     (implicit) Output the stack

```

Note that this is not only my first time golfing, but also my first time coding a program (well, programs) in CJam, so let me know how I did!

# Answer
> 2 votes
# TI-BASIC, 2 bytes

```
not(0

```

```
iPart(1

```

Both display `1`. Using one-byte TI-BASIC tokens and their hexadecimal values. `not(` has a value of `0xB8`, `iPart(` has a value of `0xB9`, `0` has a value of `0x30`, and `1` has a value of `0x31`.

---

Alternatives (assuming fresh state on calculator):

* **2 bytes**: `not(A` and `e^(H`
* **2 bytes**: `e^(A` and `10^(C`
* **2 bytes**: `not(A` and `10^(J`
* **2 bytes**: `e^(A` and `cosh(L`
* **2 bytes**: `10^(A` and `cosh(J`
* **2 bytes**: `int(1` and `10^(A`
* **2 bytes**: `int(1` and `cosh(J`
* **2 bytes**: `abs(1` and `cosh(I`
* **2 bytes**: `iPart(1` and `cosh(B`
* **2 bytes**: `not(0` and `cosh(B`

# Answer
> 1 votes
# Brainetry, 23 bytes

Golfed version (both lines end with a space):

```
# # # #
# # # # # # #

```

We must shift the `#`s so they become spaces  for the program to work again, so the required shift is -3.

The base program from which I derived the above:

```
This Brainetry program takes
no input and prints the codepoint 1.

```

# Answer
> 1 votes
# Turing Machine Code, 19 bytes

```
0 _ 1 r 1
1!'!2!s!2

```

Try it online!

Nothing too fancy. If the code is shifted by -1, the second line transforms into the code of the first line. The first line transforms into an unexecutable bit of code. The interpreter can, and does, run just fine with unexecutable code dispersed here and there, and so it is just executing the same code either way.

# Answer
> 1 votes
# Perl -M5.010, 13 bytes

# Perl 5, 21 bytes

```
 say 1#BELp^vGS.

```

`BEL` = ASCII 'BEL' character, octal byte \0007 `GS` = ASCII 'GS' character, octal byte \0035

Shifted +3:

```
#vd|#4&
say 1

```

Same approach as my R answer, but with slightly (+4 characters) more verbose outputting in Perl -M5.010.
Equivalent Perl 5 program-pair (using `print` instead of `say`) is `print 1#BELmofkqGS.` and, shifted +3, `#sulqw#4&LFprint 1`.

Test at bash command-line using `echo` (or `gecho`):

```
echo -e ' say 1#\0007p^v\0035.' > prog1.pl
echo -e '#vd|#4&\0012say 1' > prog2.pl
perl -M5.010 prog1.pl
# 1
perl -M5.010 prog2.pl
# 1

```

# Answer
> 1 votes
# Perl 5 \+ `-M5.10.0`, 11 bytes

Uses a shift of `3`.

```
p^v,, say//

```

Try it online!

```
say//#vd|22

```

Try it online!

## Explanation

`p^v` computes the bitwise `XOR` of `p` and `v` then calls `say//`. `//` returns `1` because the empty string exists within `$_` (which is the empty string).

In the shifted program, `say//` is called immediately and the rest of the program is commented out.

# Answer
> 1 votes
# Retina, 1 byte

```
^

```

Try it online!

Shifted by `30`:

```
|

```

Try it online!

# Answer
> 1 votes
# PHP \+ `-d output_buffering=on`, 21 bytes

```
<?=1;#;><*na^bkd`m'(:

```

Try it online!

Shifted by `1`:

```
=@>2<$<?=+ob_clean();

```

Try it online!

Using the same technique as my `Shifting Oritented Programming` answer, it's possible to get all 256 shifts for 5,366 bytes:

Try it online!

# Answer
> 1 votes
# Befunge-93, 7 bytes

Original code:

```
>1.@B03

```

Try it online!

Shifted by `-2`:

```
</,>@.1

```

Try it online!

# Answer
> 1 votes
# Stax, 1 bytes

```
æ

```

Run and debug it

# Stax, 1 bytes

```
1

```

Run and debug it

I'm not sure what the offset is, but any two single-character programs can be shifted to each other.

# Answer
> 1 votes
# \>\<\> x2, 6 bytes

Uses a shift of 11.

```
1n;0c&

```

Puts 1 on the stack, outputs it as a number and stops.

```
<yF;n1

```

`<` makes the direction change and start executing code from the end of the line. Puts 1 on the stack, outputs it as a number and stops.

# Answer
> 1 votes
# Javastack , 1 byte

```
1

```

# Vyxal, 1 byte

Vyxal pads the stack with 0s when there's no input, so the list includes but is not limited to...

* \- 0 incremented
* `ċ` \- 0 != 1
* \- 0 \>= 0
* \- 0 \<= 0
* `=` \- 0 == 0
* `¬` \- !0
* \- 0 % 3 == 0
* \- 0 % 2 == 0
* \- 0 % 5 == 0
* `L` \- len(str(0))
* \- 1 - 0
* `e` \- 0 \** 0
* `ż`, if I can output in a singleton list

# Answer
> 1 votes
# TypeScript's type system, 8 bytes

```
type F=1

```

# Vyxal 2, 8 bytes

```
‹←↓u0VMA

```

Try it Online!

Each character is offset by +16 in Vyxal 2's codepage.

The TypeScript program actually outputs `1` in Vyxal as well, but the shift must be nonzero.

The TypeScript type system program was very easy to write. I found the Vyxal program using this code, changing the offset by 1 and rerunning until I found a working program.

The first 6 characters of the Vyxal program do nothing particularly logical, but end up with `0` on the stack (which is quite common for random characters with no particular meaning). `M` tries to map over a list by a function, but with no list or function given, it just outputs an empty list. `A` checks if all items in the list are truthy, which for an empty list returns `1`.

# Answer
> 0 votes
Same code for javascript and brainfuck (shifted 0)

# JavaScript (V8), 152 bytes

```
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[1.>>0]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

```

Try it online!

# brainfuck, 152 bytes

```
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[1.>>0]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

```

Try it online!

# Answer
> 0 votes
# Text, 1 byte

```
1

①

Ⅰ

```

If `one` is valid then there's no reason  and  aren't

---
Tags: code-golf, unicode
---


title: Construct the Constructability sequence

text:
# Question
Title: Construct the Constructability sequence
Consider compass-and-straightedge construction, where you can construct new points from existing ones by examining intersections of straight lines and circles constructed with one of the following two options:

* Draw the unique infinitely long straight line passing through points \\$(x, y)\\$ and \\$(x', y')\\$
* Draw the unique circle centered on \\$(x, y)\\$ that passes through the distinct point \\$(x', y')\\$

We begin with two points, typically \\$(0, 0)\\$ and \\$(1, 0)\\$, but any two distinct points suffice. If we draw all possible lines and circles using these two points, how many total points do we end up with?

Spoiler: 6, shown below.

If we now repeat this procedure - drawing every line between two points and every circle determined by two existing points - and then add the newly constructed points to our set, we end up with 203 total points. We can then do this again, and again, and so on to form a sequence that begins $$2, 6, 203, 1723816861$$

This is A333944, added to OEIS after this Math.SE question was asked about the 4th term in the sequence. Note that, as of writing, only \\$4\\$ terms exist in the sequence on OEIS.

---

Unsurprisingly, your task is to output this sequence. This is a standard challenge, meaning that you may complete one of the following options, using \\$0\\$ or \\$1\\$ indexing of your choice (if applicable):

* Take an integer \\$n\\$ and output the \\$n\\$th term in the sequence
* Take an integer \\$n\\$ and output the first \\$n\\$ terms in the sequence
* Output the sequence indefinitely, in ascending order

This is , so the shortest code in bytes in each language wins.

---

In the linked Math.SE question, the answer provides some Haskell code which completes this task. Unsurpsingly, it is highly ungolfed, and very slow, taking approximately \\$6\\$ days to find the fourth term in the sequence. I offer a 1000 rep bounty (\\$2 \times 500\\$ rep bounties) for the first answer which can find and verify the 5th term in the sequence. The rough upper bound given in the linked question suggests that it is no larger than \\$10^{314}\\$.

# Answer
# Python+`sympy`, 247 bytes

```
from sympy import*
from itertools import*
c,C,p=combinations,Circle,{a:=Point(0,1),a*2}
while[l:=set()]:
 print(len(p))
 for a,b in c(p,2):l|={Line(a,b),C(a,d:=abs(a-b)),C(b,d)}
 for a in c(l,2):p|={i for i in intersection(*a)if type(i)is Point2D}

```

Unfortunately, the challenge is quite trivial with sympy. I do have another solution without using modules, which should theoretically work, but doesn't due to rounding errors. Might post that later when fixed.
Extremely slow ofc.

Attempt This Online! (modified code to work on ATO)
> 5 votes

---
Tags: code-golf, sequence, geometry, abstract-algebra
---


title: Capture the Flag... with a twist

text:
# Question
Title: Capture the Flag... with a twist
Inspired by a challenge from the OUCC 2022 Seniors competition.

### Background

Two teams are playing "capture the flag". They take turns invading each other's base and capturing their opposing team's flag in the shortest amount of time. The attacking players each have one soft ball they can throw at the defenders. Teams get to reduce the time they took to capture the flag by 3 seconds for each of the defenders team that gets hit with a ball.

### Your Task

Write a program that calculates which team won based on who had the smallest accumulated time.

### Clarifications

* There are two teams.
* There will be an even number of rounds played.
* Both teams will attack an equal number of times but it could be in any order.

### Example

Let's say we have the input `[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]`. We go through each inner list:

* `['A', 20, 0]`: The `A` tells us we need to add to team A. To get the number we need to add, we use `time - 3*hits`. In this case, it is `20-3*0` = 20.
* `['A', 30, 1]`: We again need to add to team A. This time it's `30-3*1` = 27. Team A is now on 47.
* `['B', 40, 6]`: This time it's 22
* `['B', 20, 2]`: 14. B is now at 36.

Now we get the team with the lower score, in this case B, and output.

### Test cases

```
Input -> Output
[['A', 100, 5], ['B', 95, 2]] -> A
[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] -> B
['A', 50, 3], ['A', 70, 5], ['B', 35, 0], ['A', 25, 1], ['B', 60, 2], ['B', 40, 4] -> B
[] -> Draw

```

### Input / Output formats

* You must take an arbitrary even number of inputs (these can all be in a list, or taken separately).
* Each input must be a list of three items (in whatever order you prefer):

+ The team. You must choose two distinct values for this, e.g. `0` and `1`, `'A'` and `'B'`, etc.
    + The time taken for the team to get the flag (a positive integer of seconds)
    + The number of hits they got (a positive integer)

Note: The number of hits will never exceed the time taken / 5, so the score will never be negative.
* You must have three distinct output possibilities:

+ One for the first team winning
    + One for the second team winning
    + One for a draw
* **This is , so shortest answer in bytes wins!**

# Answer
> 6 votes
# Vyxal, ~~12~~ ~~10~~ 8 bytes

```
ƛ÷T-*;∑±

```

Try it Online!

Inspired by Arnaulds answer. Expects `-1` for 'A' and `1` for 'B'. Returns `1`, `-1` or `0` for A wins, B wins and draw respectively.

```
ƛ    ;   # map:
 ÷       #   push each on stack
  T      #   triple
   -     #   subtract
    *    #   multiply
      ∑  # sum
       ± # sign

```

# Answer
> 7 votes
# JavaScript (ES6), 43 bytes

*-2 thanks to @l4m2*

Expects `1` for `'A'` and `-1` for `'B'`. Returns `false`, `true` or `0` for *A wins*, *B wins* and *draw* respectively.

```
a=>a.map(([i,t,n])=>s+=i*=t-n*3,s=0)|s&&s>0

```

Try it online!

### Commented

```
a =>                 // a[] = input array
a.map(([i, t, n]) => // for each entry (i = team, t = time, n = hits):
  s +=               //   update the sum s:
    i *=             //     either add or subtract:
      t - n * 3,     //       t - 3n
  s = 0              //   start with s = 0
)                    // end of map()
| s                  // return 0 if s = 0
&& s > 0             // return true if s is positive, false otherwise

```

# Answer
> 4 votes
# Charcoal, ~~28~~ 21 bytes

```
≔↨¹Ｅθ×⊟ι↨±³ιθＩ∧θ÷θ±↔θ

```

Try it online! Link is to verbose version of code. Takes input as a list of `[hits, time, team]` where `-1` is `A` and `1` is `B` and outputs the winning team or `0` for a tie. Explanation:

```
≔↨¹Ｅθ×⊟ι↨±³ιθ

```

Calculate sum of the accumulated times for each round with `A`s times being negative and `B`'s times being positive.

```
Ｉ∧θ÷θ±↔θ

```

Output the negated sign of the result.

No actual "base conversion" going on here - base `-3` is used to calculate accumulated time and base `1` is used to take the sum of a list in case it's empty.

# Answer
> 3 votes
# Japt `-g`, 14 bytes

```
x_Ì*3)nZg1)*ZÎ

```

Try it or verify all test cases.

Port of @AndrovT's Vyxal answer. Takes -1 for A and 1 for B. Outputs 1 for A, -1 for B, and 0 for draw.

```
x_Ì*3)nZg1)*ZÎ  implicit input array
x_              sum after mapping each to:
  Ì*3)            the last item (hits) * 3
      nZg1)       subtracted from the second item (time)
           *ZÎ    multiplied by first item
                  (A or B, -1 for A and 1 for B)
      -g flag:  output sign of the number

```

# Answer
> 3 votes
# Nibbles, ~~6~~ 5.5 bytes

```
`$+.$*-@*3

```

Attempt This Online!

Takes a list of tuples `(hits,time,team)` with `1` and `-1` as the team names. Outputs the team with a bigger score, or `0` for a draw.

## Explanation

```
`$ Sign of
+   sum of
.    map
$     input
      (x,y,z) =>
*     multiply
-      subtract
@       y
*3      multiply by 3
         x
       z

```

Nibbles' implicit tuple unpacking came in really handy here.

-0.5 by using my freedom to choose the order of the tuple.

# Answer
> 2 votes
# Wolfram Language, ~~39~~ 35 bytes

**Solution 2.** Thanks to these tips, we can remove 4 bytes:

```
Sign@Tr[#&@@#(#[[2]]-3#[[3]])&/@#]&

```
* `Tr` is the same as `Total` for 1-dimensional lists (-3 bytes)
* `a[[1]]` is the same as `#&@@a` (-1 byte).

Note that we now have three anonymous functions stacked within each other like matryoshka dolls!

**Solution 1.** We encode 'A' as 1 and 'B' as -1.

```
Sign@Total[#[[1]](#[[2]]-3#[[3]])&/@#]&

```

The solution converts each list element {a,b,c} into an expression a(b-3c), using an anonymous function. We then calculate the sum (total) of this list and compute its arithmetic sign. It returns 1 if 'A' wins, 0 if there is a tie, and -1 if 'B' wins (for obvious reasons).

Some comments about the notation:

* `@` is function application: `f[x]` is the same as `f@x`.
* `Sign` and `Total` does what they say on the tin (`Total` accepts a list argument).
* `#` and `&` define an anonymous function: `#+1&` is a function that adds 1 to its argument.
* `a[[i]]` is the $i$-th element of list `a`, and list elements are enumerated starting from 1.
* `/@` is `Map`, which applies a function on the left to list on the right.
* Finally, Wolfram Language does not require explicit multiplication signs in obvious cases like `a(b+c)` or `2x`.

One final comment: the solution is 39 bytes but 33 *glyphs*, as Wolfram allows using `U+301A`〚 and `U+301B` 〛instead of double brackets.

# Answer
> 2 votes
# Factor \+ `math.unicode`, 33 bytes

```
[ [ first3 3 * - * ] map Σ sgn ]

```

Try it online!

This answer uses the following values:

* `-1` for Team A
* `1` for Team B
* `1` for Team A victory
* `-1` for Team B victory
* `0` for draw

### How?

For each triplet,

* Multiply the last number by three
* Subtract this value from the second number
* Multiply this by the first number (the team value \[-1 or 1\])

Then,

* Sum the results
* Get the sign (returning -1, 0 or 1 for negative, zero, and positive)

# Answer
> 2 votes
# Jelly, 8 bytes

Employs the team identification trick from Arnauld's JavaScript ES6 answer.

```
Ḣ×)ḅ-3SṠ

```

A monadic Link that accepts a list of triples, `[team, hits, time]` with teams represented as `-1` and `1`, and yields the losing team or `0` for a draw (i.e. `-1` if `1` won and vice versa).

**Try it online!** Or see the test-suite.

### How?

```
Ḣ×)ḅ-3SṠ - Link: list of [team, hits, time] triples
  )      - for each triple:
Ḣ        -   head -> removes team and yields it
 ×       -   multiply by ([hits, time]) -> [team * hits, team * time]
   ḅ-3   - convert (each) from base -3  -> -3 ** 1 * team * hits + -3 ** 0 * team * time
                                           = team * (time - 3 * hits)
      S  - sum
       Ṡ - sign

```

---

Equivalently, `Ḣ×ḅ-3)SṠ`.

Similarly, `Ḣ)ḋḅ-3$Ṡ` (using a dot-product).

# Answer
> 2 votes
# Japt `-g`, 10 bytes

Port of Jonathan's Jelly solution.

```
xÈm*Xv)ì3n

```

Try it

```
xÈm*Xv)ì3n     :Implicit input of 2D array
x              :Reduce by addition after
 È             :Passing each X through the following function
  m*           :  Map & multiply by
    Xv         :    Remove & return the first element, mutating the original array
      )        :  End map
       ì       :  Convert from base
        3n     :    -3
               :Implicit output of sign of result

```

# Answer
> 1 votes
# Arturo, 52 bytes

```
$[a][n:sum map a't->t\0*t\1-t\2*3(0=n)?->0->n/abs n]

```

Try it

A port of my Factor answer, though it suffers from a lack of sign function.

```
$[a][               ; a function taking an argument a
  n:                ; assign n to
  sum               ; sum
  map a 't ->       ; map over a and assign current element to t
    t\2 * 3         ; last number in triplet times three
    t\1 -           ; subtracted from second number in triplet
    t\0 *           ; times first number in triplet
  (0=n)?            ; is n zero?
  -> 0              ; zero if so
  -> n / abs n      ; n divided by the absolute value of n if not
]                   ; end function

```

# Answer
> 1 votes
# C (clang), <sup>~~59~~</sup> 58 bytes

```
s;f(*p){for(s=0;*p;)s+=*p++*(*p++-*p++*3);*p=(s>0)-(s<0);}

```

Try it online!

*Saved a byte thanks to ceilingcat!!!*

Inputs a pointer to a \\$0\\$ terminated (because pointers in C don't carry any length info) array of integer triplets of the side (\\$1\\$ for the first team and \\$-1\\$ for the second), the time, and the number of hits.
Returns (at the end of the input array) \\$-1\\$ for a win by the first team, \\$1\\$ for a win by the second, and \\$0\\$ for a draw.

# Answer
> 1 votes
# Julia,44 bytes

```
a->sign(mapfoldl(i->i[1]*(i[2]-3*i[3]),+,a))

```

I'm taking the strategy everyone else is using by using -1 for A and 1 for B, then multiplying that by the number of seconds after deductions. Outputting the sign of the output is the team who wins, and zero is a draw.

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
ε`3*-*}O.±

```

Port of almost any other answer, with input-triplets in the order `[team, time, hits]` and using `1` and `-1` for teams \\$A\\$ and \\$B\\$ respectively, with an output of `-1`, `1`, or `0` for Team \\$B\\$ wins; Team \\$A\\$ wins; and draw respectively.

Try it online or verify all test cases.

A port of *@JonathanAllan*'s Jelly's answer is 10 bytes as well:

```
εć*3(β}O.±

```

Takes the inputs in the order `[team, hits, time]` instead. The other I/O is the same.

Try it online or verify all test cases.

**Explanation:**

```
ε      # Map over the (implicit) input-list of triplets:
 `     #  Pop and push all three values separately to the stack
  3*   #  Multiply the top `hits` by 3
    -  #  Subtract it from the `time`
     * #  Multiply it to the `team`
}O     # After the map: sum the list together
  .±   # Pop and output its sign
       # (which is output implicitly as result)

ε      # Map over the (implicit) input-list of triplets:
 ć     #  Extract head; pop and push remainder-list [hits,time] & head `team` separately
  *    #  Multiply `team` to the values in the pair: [hits*team,time*team]
   3(β #  Convert it from a base-(-3) list to an integer: team*(time-3*hits)
}O.±   # After the map: same as above (and also output implicitly)

```

# Answer
> 1 votes
# Nim, 77 bytes

```
import math,sequtils
proc c[S](s:S):int=sgn sum s.mapIt it[0]*(it[1]-3*it[2])

```

Attempt This Online!

Takes `1` and `-1` as the team names. Outputs the team with a bigger score, or `0` for a draw.

# Answer
> 1 votes
# awk, ~~78~~ ~~76~~ ~~71~~ 69 bytes

In the following, remove newline (that's only for readability) and save one byte.

1. 79 bytes
```
{s[$1]=s[$1]+$2-(3*$3)}
END{print (s["A"]>s["B"])?"A":(s["A"]<s["B"])?"B":"="}

```
2. 77 bytes
```
{s[$1]=s[$1]+$2-(3*$3)}
END{a=s["A"];b=s["B"];print (a>b)?"A":(a<b)?"B":"="}

```
3. 72 bytes
```
{s[$1]+=$2-(3*$3)}
END{a=s["A"];b=s["B"];print (a>b)?"A":(a<b)?"B":"="}

```
4. 70 bytes
```
{s[$1]+=$2-3*$3}
END{a=s["A"];b=s["B"];print (a>b)?"A":(a<b)?"B":"="}

```

There must be some tricks, I dunno, to make it shorter.

## Usage and notes

Use of AWK require some adaptation of the input.

* The outer list is a file to pass to the script.
* The inner lists are lines of the input file.
* Items in sub lists are separated by blanks only.

The example given (1 line for 57 bytes)

```
[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]

```

becomes then (4 lines for 28 bytes)

```
A 20 0
A 30 1
B 40 6
B 20 2

```

Once the data file created, let's say `match.list`, call the script, let's say `twist.awk`, by issuing the command line

```
awk -f twist.awk match.list

```

You can also replace `-f twist.awk` with the script directly.

## Ungolfed/explanation

For golfing purposes I've used `s` instead of a more useful variable name.

```
{                       # This is the main block, executed for each line
  s[$1]=s[$1]+$2-(3*$3) # Update Score table indexed by first field (team)
                        # precisely, creation then update next iterations
}
END{                    # This block is executed once after main processing
  print "A=" s["A"],    # add this for debug purpose
        "B=" s["B"], "" ;
  (s["A"]>s["B"])       # if team A scores more than team B
    ?                   # then
    print "A"           # says that A wins
    :                   # else
    (s["A"]<s["B"])     # if team A scores less than team B
      ?                 # then
      print "B"         # says that B wins
      :                 # else
      print "="         # says it's a drawn
}

```

For golfing purpose, we use ternary operator in place of the if-then statement, and replace the `if (cond) {foo} else {bar}` becomes `(cond)?{foo}:{bar}` By the same way, `if (cond) {foo} else if (alt) {baz} else {bar}` becomes `(cond)?{foo}:(alt)?{baz}:{bar}` and here we can factorise `print`.

# Answer
> 1 votes
# BQN, 42 bytes

Anonymous tacit prefix function.

```
((2⊸=≠)+(⊢⊐⌊˝))(({-3×}´+˝)¨(⊐⊏˘)⊔(1⊸↓˘))

```

Try it online!

### Explanation

```
((2⊸=≠)+(⊢⊐⌊˝))(({-3×}´+˝)¨(⊐⊏˘)⊔(1⊸↓˘))
                                   ⊔        Partition...
                                    (1⊸↓˘)  the input with the first column dropped
                              (⊐⊏˘)         by the first column.
                (           )¨              Then for each partition (team)...
                          +˝                sum-reduce it...
                 {-3×}´                   and calculate its score.
(      +       )                            Then sum...
         (⊢⊐⌊˝)                             the index with the minimum value...
 (2⊸=≠)                                     to whether the length is 2

```

Some positives include that the code works on the original input *as is* (i.e.

```
[['A', 100, 5], ['B', 95, 2]]

```

is a valid input), and that it accepts any labelling of the teams (A/B, -1/1).

Some negatives include that it doesn't apply the neat sign trick that everyone else is using and that it's (albeit lightly) hardcoded the number of teams to 2.

Oh and that it's so damn long. Any help translating the regular strategy to an array language (APL, J, K etc.)?

# Answer
> 1 votes
# Perl 5 `-pa`, 35 bytes

```
${$F[0]}+=$F[1]-$F[2]*3}{$\=$A<=>$B

```

Try it online!

Teams are A & B. Input is one turn per line with numbers space separated from the team name. Output is -1 for team A, 0 for draw, 1 for team B.

# Answer
> 0 votes
# Thunno, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
eAu3*-*ESza

```

Attempt This Online! or verify all test cases.

Port of AndrovT's Vyxal answer

#### Explanation

```
eAu3*-*ESza  # Implicit input
e      E     # Map over the input:
 Au          #  Dump the contents onto the stack
   3*        #  Triple (the hits)
     -       #  Subtract (from the time)
      *      #  Multiply (by the team)
        S    # Sum
         za  # Sign
             # Implicit output

```

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