title: Classify a region by its slope

text:
# Question
Title: Classify a region by its slope
## Definitions

The **kth** ring of a square matrix of size **N**, where **1 ≤ k ≤ ceiling(N/2)** is the list formed by the elements of the **kth** and **(N-k+1)th** rows and columns, but without the first and last **k-1** elements.

Example:

```
Matrix:

1 2 3 4 5
6 7 8 9 1
8 7 6 5 4
3 2 1 9 8
7 6 5 4 3

Delimited in rings:

+-------------------+
| 1   2   3   4   5 |
|   +-----------+   |
| 6 | 7   8   9 | 1 |
|   |   +---+   |   |
| 8 | 7 | 6 | 5 | 4 |
|   |   +---+   |   |
| 3 | 2   1   9 | 8 |
|   +-----------+   |
| 7   6   5   4   3 |
+-------------------+

```

The first ring of the above is `1,2,3,4,5,1,4,8,3,4,5,6,7,3,8,6`, the second is `7,8,9,5,9,1,2,7` and the third is `6`.

An **N** by **N** matrix of positive integers is (for the purposes of this challenge):

* *concave* if all the integers on the **kth** ring are strictly greater than those on the **(k+1)th** ring, where **k** is any integer between **1** and **N** (those on the first ring are greater than those on the second, which are in turn greater than those on the third etc.). Example:

```
4 5 6 4 7   -> because 4,5,6,4,7,4,8,5,5,4,6,5,9,5,5,4 are all higher than
4 3 2 2 4      any of 3,2,2,3,2,3,3,2, which are all higher than 1
5 2 1 3 8
5 3 3 2 5
9 5 6 4 5

```
* *flat* if all the integers in the matrix are equal. Another example (perhaps redundant):

```
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2

```
* *convex* if all the integers on the **kth** ring are strictly lower than those on the **(k+1)th** ring, where **k** is any integer between **1** and **N** (those on the first ring are lower than those on the second, which are in turn lower than those on the third etc.). Example:

```
1 2 1   -> because 1 and 2 are both lower than 6
2 6 2
1 2 1

```
* *mixed* if the matrix doesn't satisfy any of the above criteria. Example:

```
3 3 3 3 3
3 2 2 2 3
3 2 3 2 3
3 2 2 2 3
3 3 3 3 3

```

## Challenge

Given **a square matrix** of positive integers of **size at least 3**, classify it according to the definitions above. That is, output one of four different *consistent* values based on whether the matrix is concave, flat, convex or mixed.

You can compete in any programming language and can take input and provide output through any standard method and in any reasonable format, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for *every language* wins.

## Test cases

Here's a bunch of examples for you to choose from – I selected 6 from each category.

**Concave**

```
[[3, 3, 3], [3, 1, 3], [3, 3, 3]]
[[2, 3, 4], [5, 1, 6], [7, 8, 9]]
[[19, 34, 45], [34, 12, 14], [13, 13, 13]]
[[3, 4, 3, 4], [4, 2, 1, 3], [3, 1, 2, 4], [4, 3, 4, 3]]
[[4, 5, 6, 4, 7], [4, 3, 2, 2, 4], [5, 2, 1, 3, 8], [5, 3, 3, 2, 5], [9, 5, 6, 4, 5]]
[[7, 7, 7, 7, 7], [7, 6, 6, 6, 7], [7, 6, 5, 6, 7], [7, 6, 6, 6, 7], [7, 7, 7, 7, 7]]

```

**Flat**

```
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
[[8, 8, 8], [8, 8, 8], [8, 8, 8]]
[[120, 120, 120], [120, 120, 120], [120, 120, 120]]
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]
[[5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5]]

```

**Convex**

```
[[1, 2, 1], [2, 6, 2], [1, 2, 1]]
[[1, 1, 1], [1, 2, 1], [1, 1, 1]]
[[19, 34, 45], [34, 76, 14], [13, 6, 13]]
[[3, 3, 3, 3], [3, 4, 4, 3], [3, 4, 4, 3], [3, 3, 3, 3]]
[[192, 19, 8, 6], [48, 324, 434, 29], [56, 292, 334, 8], [3, 4, 23, 23]]
[[291, 48, 7, 5], [47, 324, 454, 30], [58, 292, 374, 4], [9, 2, 53, 291]]

```

**Mixed**

```
[[1, 2, 3], [4, 5, 9], [6, 7, 8]]
[[10, 14, 21], [100, 8, 3], [29, 2, 19]]
[[5, 5, 5, 5], [5, 4, 4, 5], [5, 4, 6, 5], [5, 5, 5, 5]]
[[3, 3, 3, 3], [3, 1, 2, 3], [3, 3, 2, 3], [3, 3, 3, 3]]
[[12, 14, 15, 16], [12, 18, 18, 16], [12, 11, 11, 16], [12, 14, 15, 16]]
[[5, 5, 5, 5, 5], [5, 4, 4, 4, 5], [5, 4, 6, 4, 5], [5, 4, 4, 4, 5], [5, 5, 5, 5, 5]]

```

# Answer
# Jelly,  ~~18 17~~  16 bytes

I believe there is a lot of potential for this effort to be out-golfed

```
L‘HạŒỤṀ€IṠQṢ«FE$

```

A monadic link accepting a list of lists of numbers which returns a list of integers:

```
Concave ->  [0, 0]
Flat    ->  [-1, 0, 1]
Convex  ->  [-1, 0]
Mixed   ->  [-1, 0, 0]

```

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

`L‘H` could be replaced with the less efficient but *atomically* shorter `JÆm`.

### How?

```
L‘HạŒỤṀ€IṠQṢ«FE$ - Link: list of (equal length) lists of numbers
L                - length
 ‘               - increment
  H              - halve
                 -   = middle 1-based index (in both dimensions as the input is square)
    ŒỤ           - sort multi-dimensional indices by their corresponding values
                 -   = a list of pairs of 1-based indexes
   ạ             - absolute difference (vectorises)
                 -   = list of [verticalDistanceToMiddle, horizontalDistanceToMiddle] pairs
      Ṁ€         - maximum of €ach
                 -   each = N/2-k (i.e. 0 as middle ring and N/2 as outermost)
        I        - incremental deltas (e.g. [3,2,2,3,1]->[3-2,2-2,3-2,1-3]=[-1,0,1,-2])
         Ṡ       - sign (mapping -n:-1; 0:0; and +n:1)
          Q      - de-duplicate
           Ṣ     - sort
                 -   = concave:[0, 1]; convex:[-1, 0]; flatOrMixed:[-1, 0, 1]
               $ - last two links as a monad
             F   -   flatten
              E  -   all equal? (1 if flat otherwise 0)
            «    - minimum (vectorises)
                 -   = concave:[0, 0]; convex:[-1, 0]; mixed:[-1, 0, 0]; flat:[-1, 0, 1]

```
> 5 votes

# Answer
# Python 2, ~~219~~ ~~216~~ ~~189~~ 176 bytes

```
def g(M):A=[sorted((M[1:]and M.pop(0))+M.pop()+[i.pop(j)for j in[0,-1]for i in M])for k in M[::2]];S={cmp(x[j],y[~j])for x,y in zip(A,A[1:])for j in[0,-1]};return len(S)<2and S

```

Try it online!

Outputs `set([1]), set([0]), set([-1]),` or `False` for concave, flat, convex, or mixed, respectively.

Thx for: A whopping 27 bytes from a few optimizations by ovs. And then *another* 13 bytes afterwards.

The list comprehension `A` (due to ovs) creates a list of the elements of each ring, sorted.

Next, we compare the `max` and `min` values between adjacent rings by looking at the `0`th and `-1`th elements of each sorted list in A. Note that if, for example, `M` is concave, `min` of each outer ring must be greater than `max` of the next inner-most ring; and it then follows that `max` of each outer ring will also be greater than `min` of the next inner-most ring.

If `M` is concave, flat, or convex, the set of these `min/max` comparisons will have only 1 element from `{-1, 0, 1}`; if it is mixed, there will be two or more elements.
> 5 votes

# Answer
# Java (JDK 10), ~~247~~ ~~232~~ 220 bytes

```
x->{int i=0,j=x.length,k,m,M,p=0,P=0,r=0;for(;i<j;){for(M=m=x[k=i][--j];k<=j;)for(int q:new int[]{x[i][k],x[j][k],x[k][i],x[k++][j]}){m=m<q?m:q;M=M<q?q:M;}r=i++>0?(k=P<m?3:p>M?1:P==m?2:4)*r!=r*r?4:k:0;p=m;P=M;}return r;}

```

Try it online!

Outputs:

* `1` for "concave"
* `2` for "flat"
* `3` for "convex"
* `4` for "mixed"

Ungolfed:

```
x -> { // lambda that takes in the input int[][]
  int i = 0, // index of right bound of ring
      j = x.length, // index of left bound of ring
      k, // index of row-column-pair in ring
      m, // minimum of ring
      M, // maximum of ring
      p = 0, // minimum of previous ring
      P = 0, // maximum of previous ring
      r = 0; // result
  for (; i < j; ) { // iterate the rings from outside inwards
    // set both min and max to be to top right corner of the ring (and sneakily set some loop variables to save space)
    for (M = m = x[k = i][--j]; k <= j; ) // iterate the row-column pairs of the ring from top-right to bottom-left
      for (int q : new int[] {x[i][k], x[j][k], x[k][i], x[k++][j]}) { // iterate all of the cells at this row-column pair (and sneakily increment the loop variable k)
        // find new minimum and maximum
        m = m < q ? m : q;
        M = M < q ? q : M;
      }
    r = // set the result to be...
      i++ > 0 ? // if this is not the first ring... (and sneakily increment the loop variable i)
              // if the new result does not match the old result...
              (k = P < m ? // recycling k here as a temp variable to store the new result, computing the result by comparing the old and new mins/maxes
                         3
                         : p > M ?
                                 1
                                 : P == m ?
                                          2
                                          : 4) * r != r * r ? // multiplying by r here when comparing because we want to avoid treating the case where r = 0 (unset) as if r is different from k
                                                            4 // set the result to "mixed"
                                                            : k // otherwise set the result to the new result
              : 0; // if this is the first ring just set the result to 0
    // set the old ring mins/maxes to be the current ones
    p = m;
    P = M;
  }
  return r; // return the result
}

```
> 5 votes

# Answer
# K (ngn/k), ~~100~~ ~~71~~ 69 bytes

```
{$[1=#?,/a:(,/x)@.=i&|i:&/!2##x;;(&/m>1_M,0)-&/(m:&/'a)>-1_0,M:|/'a]}

```

Try it online!

returns `1`=concave, `::`=flat, `-1`=convex, `0`=mixed

(`::` is used as a placeholder for missing values in k)
> 4 votes

# Answer
# JavaScript (ES6), 168 bytes

Returns:

* `-1` for flat
* `0` for mixed
* `1` for convex
* `2` for concave

```
f=(a,k=w=~-a.length/2,p,P,i,m,M,y=w)=>k<0?i%4%3-!i:a.map(r=>r.map(v=>Y|(X=k*k-x*x--)<0&&X|Y<0||(m=v>m?m:v,M=v<M?M:v),x=w,Y=k*k-y*y--))|f(a,k-1,m,M,i|M-m<<2|2*(M<p)|m>P)

```

Try it online!

## How?

### Minimum and maximum on each ring

We compute the minimum **m** and the maximum **M** on each ring.

We test whether a cell is located on a given ring by computing the squared distance from the center of the matrix on each axis. Taking the absolute value would work just as well, but squaring is shorter.

A cell at **(x, y)** is located on the **n**-th ring (0-indexed, starting from the outermost one) if the following formula is *false*:

```
((Y != 0) or (X < 0)) and ((X != 0) or (Y < 0))

```

where:

* **X = k² - (x - w)²**
* **Y = k² - (y - w)²**
* **w = (a.length - 1) / 2**
* **k = w - n**

**Example:** is the cell **(1, 2)** on the 2nd ring of a 6x6 matrix?

```
  | 0 1 2 3 4 5   w = (6 - 1) / 2 = 2.5
--+------------   (x, y) --> ( x-w,  y-w) --> ((x-w)²,(y-w)²)
0 | 0 0 0 0 0 0   (1, 2) --> (-1.5, -0.5) --> (  2.25,   0.5)
1 | 0 1 1 1 1 0
2 | 0[1]0 0 1 0   k = w - 1 = 1.5
3 | 0 1 0 0 1 0   k² = 2.25
4 | 0 1 1 1 1 0   X = 2.25 - 2.25 = 0 / Y = 2.25 - 0.5 = 1.75
5 | 0 0 0 0 0 0   ((X != 0) or (Y < 0)) is false, so (1,2) is on the ring

```

### Flags

At the end of each iteration, we compare **m** and **M** against the minimum **p** and the maximum **P** of the previous ring and update the flag variable **i** accordingly:

* `i |= 1` if **m \> P**
* `i |= 2` if **M \< p**
* we set higher bits of **i** if **M != m**

At the end of the process, we convert the final value of **i** as follows:

```
i % 4  // isolate the 2 least significant bits (for convex and concave)
% 3    // convert 3 to 0 (for mixed)
- !i   // subtract 1 if i = 0 (for flat)

```
> 4 votes

# Answer
# Jelly, 17 bytes

```
ŒDŒH€ẎUÐeZ_þƝṠFf/

```

Returns **1** for *concave*, **0** for *flat*, **-1** for *convex*, and nothing for *mixed*.

Try it online!
> 4 votes

# Answer
# oK, 56 bytes

```
&/1_`{&/+(y>|/x;y<&/x;,/x=/:y)}':{(,/x)@.=i&|i:&/!2##x}@

```

Based off of ngn's answer.

Try it online!

```
concave:1 0 0
   flat:0 0 1
 convex:0 1 0
  mixed:0 0 0

```
> 2 votes

# Answer
# C++17 (gcc), 411 bytes

```
#import<map>
#define R return
#define T(f,s)X p,c;for(auto&e:r){c=e.second;if(p.a&&!p.f(c)){s;}p=c;}R
using I=int;struct X{I a=0;I z=0;I f(I n){R!a||n<a?a=n:0,n>z?z=n:0;}I
l(X x){R z<x.a;}I g(X x){R a>x.z;}I e(X x){R a==z&a==x.a&z==x.z;}};I
N(I i,I j,I s){i*=s-i;j*=s-j;R i<j?i:j;}auto C=[](auto&&m){I
s=size(m),i=-1,j;std::map<I,X>r;for(;++i<s;)for(j=-1;++j<s;)r[N(i,j,s-1)].f(m[i][j]);T(g,T(l,T(e,R 0)3)2)1;};

```

A new high score! (at the time of posting, at least) Oh well, it's a bit nifty, but still C++.

Try it online!

Lambda `C` takes a `std::vector<std::vector<int>>` and returns 1 for concave, 2 for convex, 3 for flat, or 0 for mixed.

A more legible version of the code, with descriptive identifiers, comments, `R`-\>`return` and `I`-\>`int` written out, etc.:

```
#include <map>

// Abbreviation for golfing. Spelled out below.
#define R return

// Macro to test whether all pairs of consecutive Ranges in `rings`
// satisfy a condition.
// func: a member function of Range taking a second Range.
// stmts: a sequence of statements to execute if the condition is
//        not satisfied. The statements should always return.
//        May be missing the final semicolon.
// Expands to a statement, then the return keyword.
// The value after the macro will be returned if all pairs of Ranges
// satisfy the test.
#define TEST(func, stmts)                                     \
    Range prev, curr;                                         \
    for (auto& elem : rings) {                                \
        curr = elem.second;                                   \
        // The first time through, prev.a==0; skip the test.  \
        if (prev.a && !prev.func(curr))                       \
        { stmts; }                                            \
        prev = curr;                                          \
    }                                                         \
    return

// Abbreviation for golfing. Spelled out below.
using I = int;

// A range of positive integers.
// A default-constructed Range is "invalid" and has a==0 && z==0.
struct Range
{
    int a = 0;
    int z = 0;
    // Add a number to the range, initializing or expanding.
    // The return value is meaningless (but I is shorter than void for golfing).
    int add(int n) {
        return !a||n<a ? a=n : 0, n>z ? z=n : 0;
        /* That is:
        // If invalid or n less than previous min, set a.
        if (a==0 || n<a)
            a = n;
        // If invalid (z==0) or n greater than previous max, set z.
        if (n>z)
            z = n;
        return dummy_value;
        */
    }

    // Test if all numbers in this Range are strictly less than
    // all numbers in Range x.
    int less(Range x)
    { return z < x.a; }

    // Test if all numbers in this Range are strictly greater than
    // all numbers in Range x.
    int greater(Range x)
    { return a > x.z; }

    // Test if both this Range and x represent the same single number.
    int equal(Range x)
    { return a==z && a==x.a && z==x.z; }
};

// Given indices into a square matrix, returns a value which is
// constant on each ring and increases from the first ring toward the
// center.
// i, j: matrix indices
// max: maximum matrix index, so that 0<=i && i<=max && 0<=j && j<=max
int RingIndex(int i, int j, int max)
{
    // i*(max-i) is zero at the edges and increases toward max/2.0.
    i *= max - i;
    j *= max - j;
    // The minimum of these values determines the ring.
    return i < j ? i : j;
}

// Takes a container of containers of elements convertible to int.
// Must represent a square matrix with positive integer values.
// Argument-dependent lookup on the outer container must include
// namespace std, and both container types must have operator[] to
// get an element.  (So std::vector or std::array would work.)
// Returns:
//   1 for a concave matrix
//   2 for a convex matrix
//   3 for a flat matrix
//   0 for a mixed matrix
auto C /*Classify*/ = [](auto&& mat)
{
    int mat_size=size(mat), i=-1, j;
    std::map<int, Range> rings;

    // Populate rings with the range of values in each ring.
    for (; ++i<mat_size;)
        for (j=-1; ++j<mat_size;)
            rings[RingIndex(i, j, mat_size-1)].add(mat[i][j]);

    // Nested macros expand to
    // Range prev, curr; for ... if (...) {
    //   Range prev, curr; for ... if (...) {
    //     Range prev, curr; for ... if (...) {
    //       return 0;
    //     } return 3;
    //   } return 2;
    // } return 1
    // Note each scope declares its own prev and curr which hide
    // outer declarations.
    TEST(greater, TEST(less, TEST(equal, return 0) 3) 2) 1;
};

```
> 1 votes

---
Tags: code-golf, array, integer, matrix, classification
---


# Question
Title: Network Transparent Boolean Logic Evaluator
Write an expression evaluator for boolean expressions encoded as JSON. Read on for explanation and rules.

**Motivation:**

Consider a scenario where two agents (Alice and Bob) are communicating with each other under the following constraints:

* All communication must be done as valid JSON strings (no JSONP or extensions), because Bob and Alice ***love*** JSON. They have had problems with character encoding in the past, so they have decided to restrict themselves to ASCII.
* Alice needs Bob to notify her in case a certain condition is met, **but**:
    + Bob doesn't know what the condition is in advance.
    + Alice can't evaluate the condition herself because it requires information that only Bob has.
    + The status of the variables can change rapidly enough (and the network is slow enough) that it would be infeasible for Bob to continuously transmit the data to Alice.
* Neither knows anything about the implementation of the other agent (for example, they can't make assumptions about the implementation language of the other agent).

Alice and Bob have worked out a protocol to help them complete their task.

**Representing Conditional Expressions:**

1. They have agreed to represent Boolean literals by strings, for example `"foo"` or `"!bar"`, where `!` represents the negation of a literal, and valid names contain only letters and numbers (case sensitive, any strictly positive length; `""` and `"!"` are not valid; i.e. a literal is a string whose contents match the regex `/^!?[a-zA-Z0-9]+$/`).
2. Expressions are only transmitted in negation normal form. This means that only literals can be negated, not subexpressions.
3. Expressions are normalized as a conjunction of disjunctions of conjunctions of disjunctions ... etc encoded as nested arrays of strings. This needs a bit more explanation, so...

**Expression Syntax:**

Consider the following boolean expression:

```
(¬a ∧ b ∧ (c ∨ ¬d ∨ e ∨ ¬f) ∧ (c ∨ (d ∧ (f ∨ ¬e))))

```

Notice that the entire expression is contained in parentheses. Also notice that the first level(and all odd levels) contains only conjunctions(∧), the second level(and all even levels) contains only disjunctions(∨). Also notice that no subexpression is negated. Anyway meat and potatoes... This would be represented by Alice in JSON as:

```
["!a","b",["c","!d","e","!f"],["c",["d",["f","!e"]]]]

```

Another example:

```
((a ∨ b ∨ c))

```

Becomes:

```
[["a","b","c"]]

```

In summary: `[]` are interpreted as parentheses, literals are wrapped in `""`,`!` means negation, and `,` means `AND` or `OR` depending on nesting depth.

**NB: the empty conjunction (the result of `AND`ing no variables) is `true`, and the empty disjunction (the result of `OR`ing no variables) is `false`. They are both valid boolean expressions.**

**Bob's data:**

Bob's data is emitted by a program on his computer as a simple JSON object as key-value pairs, where the key is the name of the variable, and the value is either `true` or `false`. For example:

```
{"a":false,"b":true,"c":false}

```

## Bob needs our help!

Bob has little programming experience, and he's in over his head. He has handed you the task.

You need to write a program that accepts the JSON text that Alice sent along with the JSON text for Bob's data, and evaluates the expression with those values, returning true or false (**the actual strings `true` and `false`**; Bob and Alice love JSON, remember?)

* Bob says less is more, so he wants you to make your source code as short as possible (this is a code-golf)
* You are allowed to use an external library to parse the JSON text, but this is the only exception. Only standard library functionality is allowed.
* Note that the JSON is accepted and returned as a **string**. There is no requirement to explicitly parse it though, if you can get it to always work without doing so.
* If Alice uses a variable that Bob doesn't know, assume it is false. Bob's data may contain variables that Alice doesn't use.
* If Alice's or Bob's JSON Object contains an invalid literal, or the JSON is invalid, or it contains a non ASCII character, then your program **must** return `null`

**Some test cases(in JSON):**

```
[
 {"alice":"[\"\"]","bob":"{}","result":"null"},
 {"alice":"[\"!\"]","bob":"{}","result":"null"},
 {"alice":"[\"0\"]","bob":"{\"0\":true}","result":"true"},
 {"alice":"[]","bob":"{}","result":"true"},
 {"alice":"[[]]","bob":"{}","result":"false"},
 {"alice":"[\"a>\"]","bob":"{\"a\":true}","result":"null"},
 {"alice":"[\"0\"]","bob":"{}","result":"false"},
 {"alice":"[\"0\"]","bob":"","result":"null"},
 {"alice":"[\"1\"]","bob":"{\"1\":false}","result":"false"},
 {"alice":"[\"true\"]","bob":"{\"true\":false}","result":"false"},
 {"alice":"[\"foo\",\"bar\",\"baz\"]","bob":"{\"foo\":true,\"bar\":true,\"biz\":true}","result":"false"},
 {"alice":"[[[\"a\",[\"!b\",\"c\"],\"!c\"],\"d\"]]","bob":"{\"a\":true,\"b\":false,\"c\":true,\"d\":false}","result":"false"},
 {"alice":"[\"!a\",\"b\",[\"c\",\"!d\",\"e\",\"!f\"],[\"c\",[\"d\",[\"f\",\"!e\"]]]]","bob":"{\"a\":false,\"b\":true,\"c\":true,\"e\":true,\"f\":false}","result":"true"}
]

```

As can be seen from the test cases, input and output are **strings** that are correctly parseable JSON. The empty string test case for `bob` was originally in error, the correct value to return is `null`, but if it saves you characters to return `false`, then that is also acceptable. I added cases for the empty clauses to make that explicit. I added another 2 test cases in response to a bug I found in someone's implementation

# Answer
> 5 votes
## ECMASCript 6 variation, ~~213 194 190 189 192~~ 166 chars

```
try{P=_=>JSON.parse(prompt())
B=P()
f=(a,c)=>a[c?'some':'every'](v=>v.big?[B][+/\W|_/.test(s=v.slice(C=v[0]=='!'))-!s][s]^C:f(v,!c))
q=f(P())}catch(_){q=null}alert(q)

```

Note: takes Bob's input *first*, and *then* Alice's input. This saves us four bytes.

* Checks for syntactically valid JSON since `JSON.parse` throws if it isn't.
* Since we're already relying on the try-catch for the above, we (ab)use out-of-bounds access to trigger our "failed validation" path when validating the (possibly negated) literals
    + This is accomplished with the `[B][...][s]` part (thanks, @l4m2! used to use a slightly more verbose construction)
    + The `-!s` is to catch `""` and `"!"` as invalid literals
    + The `C` variable holds the "should negate" state, which is accomplished with a "bitwise" XOR (and relies on implicit type coercion)

---

ES5 solution: https://codegolf.stackexchange.com/revisions/19863/8

# Answer
> 3 votes
# Ruby, 335 (327?) characters

```
begin;a,b=*$<;require'json';b=JSON[b];q if a=~/{|}/||!a[?[]||b.any?{|v,x|v=~/[\W_]/||x!=!!x}
l=0;a.gsub!(/\[|\]/){"[{}]"[($&==?]?2:0)+l=1-l]};a.gsub!(/"(!)?([a-z\d]+)"/i){b[$2]^$1}
0 while [[/\[[#{f=!1},\s]*\]/,f],[/{[#{t=!f},\s]*?}/,t],[/\[[\w,\s]*\]/,t],[/{[\w,\s]*}/,f]].any?{|k,v|a.sub!(k){v}}
rescue a=??;end;puts a=~/\W/?"null":a

```

I've heard you can't parse HTML with Regex, but I've never been told you cannot parse JSON this way, so I tried.

Alice's input is separated from Bob's input by a newline; also, it's assumed that neither input contains newlines itself. This assumption is for I/O purposes only, and is not used later. If I can make an extra assumption that Alice's input contains *no* whitespace, we can drop **8 characters** by removing all `\s`'s on line #3. If we can only assume it contains no whitespace but spaces, we can still replace `\s`'s with the space characters to save 4 characters.

# Answer
> 3 votes
**Python 3 (429)**

Longer than the other answers, but arguably the most readable so far... :)

```
import json,sys,re
r,p,m='^!?[a-zA-Z\d]+$',print,re.match
def g(a,b,s):
 if type(a)is str:
  if m(r,a):
   try:return('not '+str(b[a[1:]]))if a[0]=='!'else str(b[a])
   except:return'False'
  raise Exception
 return'('+((' and 'if s else' or ').join(g(x,b,not s)for x in a))+')'
s,j=sys.argv,json.loads
try:
 a,b = j(s[1]),j(s[2]or'{}');
 if all(m(r,x)and x[0]!='!'for x in b):p(str(eval(g(a,b,1))).lower())
except:
 p('null')

```

# Answer
> 2 votes
**Node.JS (~~331 335 310~~ 296)**

As a starting point, manually minified, could definitely be improved a bit; it basically just "brute force" evaluates the expression;

As a golf hack restriction, the variable `y` can not be defined or it won't work :)

```
r=/^[a-z\d]+$/i;function g(a,b,s,c){c=s;for(k in a){if((k=a[k]).trim){k=k.slice(i=k[0]=='!');
if(!k.match(r))y;k=i?!b[k]:b[k]}else{k=g(k,b,!s)}c=s?c&k:c|k}return!!c;}z=process.argv;a=z[2]
;b=z[3];try{p=JSON.parse;l=console.log;a=p(a);b=p(b);for(k in b)if(!k.match(r))y;l(g(a,b,1))}
catch(e){l(null)}

```

Called with `alice` as first argument, `bob` as second argument, outputs result to stdout.

EDIT: Shrunk the code a little with the help of @FireFly and by removing support for "empty bob".

# Answer
> 1 votes
# JavaScript, 178 bytes

Optimized from Tim Seguine's answer

```
try{P=JSON.parse,p=prompt;A=P(p());B=P(p());f=(a,c)=>a.map(v=>v.big?[B][/\W|_/.test(s=v.replace(/^!/,''))-!s][s]^s>v:f(v,!c))[c?'some':'every'](P);q=f(A)}catch(_){q=null}alert(q)

```

Try it online!

---
Tags: code-golf, json
---


title: Alice and Bob have a fight

text:
# Question
Title: Alice and Bob have a fight
* Alice (A) and Bob (B) decided to have a battle.
* Each combatant has 10 health.
* They take turns to roll a 6 sided die for damage.
* That damage is removed from their opponent's health.
* In the end either Alice or Bob, will vanquish their foe.

---

Show me how the battle went. Outputting these codes for the actions which have taken place.

Attack

```
B a A
^ Combatant
  ^ Action (attack)
    ^ Target

```

Roll

```
B r 4
^ Combatant
  ^ Action (roll)
    ^ Value

```

Health change

```
A h 6
^ Combatant
  ^ Attribute (health)
    ^ Value

```

Win

```
A w
^ Combatant
  ^ Action (win)

```

---

Example output:

```
A a B
A r 4
B h 6
B a A
B r 6
A h 4
A a B
A r 6
B h 0
A w

```

---

Here are the rules:

* Write in any language.
* A single roll of the die should have an equal chance of resulting in any one of the numbers 1, 2, 3, 4, 5, or 6.
* Alice always starts (Bob is chivalrous, in an old-fashioned way).
* Output an action for each turn.
* You must report the attack, roll, damage and win actions.
* Combatants are upper case, actions are lower case.
* It must not consistently produce the same result.
* There must be at least one whitespace character between an output combatant, action and value.
* The win action takes place when the opponent has zero or less health.
* All parts of an action must be on the same line.
* There should be one action per line.
* Fewest bytes wins.

Have at it!

# Answer
# 05AB1E, 49 bytes

```
"BaABr0Aha"S3ô»D„ABÂ‡[6LΩ©Tǝ¤H®-©16ǝ=®0‹#s]н…ÿ w?

```

Try it online!

**Explanation**

```
"BaABr0Aha"                                        # push the initial state of B
           S                                       # split to list of characters
            3ô                                     # divide into 3 parts
              »                                    # join each part on space and all on nl
               D„ABÂ‡                              # make a copy with A and B inverted
                     [                             # start a loop
                      6LΩ©                         # pick a random number in [1 ... 6]
                          Tǝ                       # insert at position 10 of the string
                            ¤H                     # get the last char of the string and
                                                   # convert from hex
                              ®-©                  # subtract the random number
                                 16ǝ=              # insert at position 16 and print
                                     ®0‹#          # if the hp is less than 0, break
                                         s         # swap the other string to the stack top
                                          ]        # end loop
                                           н…ÿ w?  # print the winner

```
> 5 votes

# Answer
# Python 3, 131 bytes

```
x,y="AB"
from random import*
X=Y=10
p=print
while X>0:p(x,"a",y);d=randint(1,6);p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X
p(y,"w")

```

Try it online!

-8 bytes thanks to officialaimm
-2 bytes thanks to ChooJeremy
> 13 votes

# Answer
# Python 3, 127 bytes

*This is an improvement on @HyperNeutrino answer that wouldn't fit in a comment. See the explanation below.*

```
x,y="AB"
s=id(0)
X=Y=10
p=print
while X>0:p(x,"a",y);s=s**7%~-2**67;d=s%6+1;p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X
p(y,"w")

```

Try it online!

---

## An epic quest for a shorter python dice roll

**TL;DR: It's possible to shave 4 bytes off the standard python dice roll by using RSA encryption.**

I wanted to see if the standard python dice roll (**32 bytes**) could be shortened a bit:

```
from random import*;randint(1,6)

```

In particular, `id(x)` is quite convenient to bring some non-deterministic value into the program. My idea then was to somehow hash this value to create some actual randomness. I tried a few approaches, and one of them paid off: RSA encryption.

RSA encryption, due to its simplicity, only requires a few bytes: `m**e%n`. The next random value can then be created by encrypting the previous one. Assuming the `(e,n)` key is available, the dice roll can be written with **22 bytes**:

```
s=id(0);s=s**e%n;s%6+1

```

That means we have about 10 bytes to define a valid RSA key. Here I got lucky. During my experiments, I started to use the Mersenne prime **M67** only to realize later on that Mersenne made a mistake including **M67** in his list. It turns out to be the product of `p=193707721` and `q=761838257287`. I had found my modulus:

```
n=~-2**67

```

Now, the exponent and the Charmichael totient `lcm(p-1,q-1)` need to be coprime. Luckily again, the first prime number that do not divide the totient of n is only one digit long: 7. The dice roll can then be written using **28 bytes** (4 bytes less than the standard approach):

```
s=id(0);s=s**7%~-2**67;s%6+1

```

One good thing with **M67** is that the random value generated has 66 bits, which is more than the usual 64 bits RNG. Also, the use of RSA makes it possible to go back in time by decrypting the current value multiple times. Here are the encrypting and decrypting keys:

```
Encryption: (7,                    147573952589676412927)
Decryption: (42163986236469842263, 147573952589676412927)

```

I'm definitely not an expert in statistics or cryptography, so I can't really tell whether or not this RNG checks the criteria for "good randomness". I did write a small benchmark that compares the standard deviation of the occurrences of the 1 to 6 dice rolls using different RNGs. It seems like the proposed solution works just like other ones.
> 9 votes

# Answer
# C (gcc), ~~146~~ 141 bytes

```
f(A,B,r,t,a,b){for(A=B=10;r=1+clock()%6,A*B>0;t=!t)printf("%c a %c\n%c r %u\n%c h %i\n",a=65+t,b=66-t,a,r,b,t?A-=r:(B-=r));printf("%c w",a);}

```

Try it online!

De-golf:

```
f(A,B,r,t,a,b){
    for(A=B=10; //Initialize HP
        r=1+clock()%6, // Get the number of processor cycles the program has consumed. This is relatively random, so I call it good enough.
        A*B>0;t=!t) // Flip t for change of turns
        printf("%c a %c\n%c r %u\n%c h %i\n", // Print the turn
            a=65+t,b=65+!t,a,r,b, // 65 is ASCII for 'A', 66 for 'B'
            t?A-=r:(B-=r)); // Deduct the damage.
    printf("%c w",a); // Print the winner
}

```
> 7 votes

# Answer
# Perl 5, ~~93~~ ~~88~~ 87 bytes

```
$A=$B=10;$_=B;${$_^=v3}-=$%=1+rand 6,say"$_ a $'
$_ r $%
$' h $$_"until//>$$_;say"$_ w"

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 122 bytes

```
f=(h=[10,10,p=0])=>`${x='AB'[p]} a ${y='BA'[p]}
${x} r ${d=Math.random()*6+1|0}
${y} h ${H=h[p^=1]-=d}
${H<1?x+' w':f(h)}`

```

Try it online!
> 4 votes

# Answer
# Java (JDK 10), 180 bytes

```
v->{var r="";int p=0,H[]={10,10},h=0;for(;H[0]*H[1]>0;)r+=r.format("%3$c a %4$c%n%3$c r %d%n%4$c h %d%n",h+=Math.random()*6-h+1,H[p]-=h,p+65,(p^=1)+65);return r+(char)(66-p)+" w";}

```

Try it online!

## Credits
> 4 votes

# Answer
# Ruby, ~~122 120 96 92~~ 91 bytes

```
f=->x=?A,y=?B,m=10,n=m{p [x,?a,y],[x,?r,r=1+rand(6)],[y,?h,t=n-r]
t<1?p([x,?w]):f[y,x,t,m]}

```

Saved 1 byte thanks to Asone Tuhid.

Try it online!
> 3 votes

# Answer
# Java 8, ~~230~~ ~~229~~ 228 bytes

```
v->{for(int h=104,a=h,x=0,y=1,A=10,B=A,r=0,t=0,T;a<119;System.out.printf("%c %3$c %c%n",x+65,y=(a<98?t=r+=Math.random()*6-r+1:a>h?(T=x<1?A-=t:(B-=t))<0?0:T:A*B<1?-16:(x^1)+17)+48,a=a<98?114:a>h?h:A*B<1?119:97))x^=a>h|A*B<1?1:0;}

```

-2 bytes thanks to *@ceilingcat*.

Note: there is already a much shorter Java answer, so make sure to upvote his! I use a completely different approach however, so figured it was worth posting as well.

**Explanation:**

Try it online.

```
v->{                     // Method with empty unused parameter and no return-type
  for(int h=104,         //  Temp integer with unicode for 'h' to save bytes
          a=h,           //  Second part (Action)
          x=0,           //  First part
          y=1,           //  Third part
          A=10,          //  Score player A, starting at 10
          B=A,           //  Score player B, starting at 10
          r=0,           //  Random dice-roll
          t=0,           //  Previous dice-roll
          T;             //  Temp integer
      a<119              //  Loop until there is a winner:
      ;                  //    After every iteration:
       System.out.printf(//     Print:
        "%c %3$c %c,%n", //      The three parts with spaces, and a new-line
                         //      First part:
        x+65,            //       Add 65 to `x` to convert 0/1 to 65/66
                         //       (unicode values of A/B)
        (y=              //      Third part (after set-up):
           (a<98?        //       If the previous action was 'a'
             t=r+=Math.random()*6-r+1
                         //        Roll the dice, and save it in `t`
            :a>h?        //       Else-if the previous action was 'r':
             (T=x<1?     //        If the first part changed to player A:
              A-=t       //         Subtract the previous dice-roll from A
             :           //        Else:
              (B-=t))    //         Subtract the previous dice-roll from B
             <0?         //        If this score is below 0:
              0          //         Use 0
             :           //        Else:
              T          //         Use this score
           :             //       Else (the previous action was 'h'):
            A*B<1?       //        Is there a winner:
             -16         //         Change the third part to a space
            :            //        Else:
             (x^1)+17)   //         Change the third part to the other player
         +48,            //       Add 48 to convert it to unicode
         a=              //      Second part:
           a<98?         //       If the previous action was 'a':
            114          //        Change it to 'r'
           :a>h?         //       Else-if the previous action was 'r':
            h            //        Change it to 'h'
           :             //       Else (the previous action was 'h'):
            A*B<1?       //        If either score is 0:
             119         //         Use 'w'
            :            //        Else:
             97))        //         Use 'a'
    x^=                  //   First part set-up:
       a>h               //    If the previous action is 'r',
       |A*B<1?           //    or there is a winner:
         1               //     Change A→B or B→A
       :                 //    Else:
         0;}             //     A/B remains unchanged

```
> 3 votes

# Answer
# C (gcc), 142 bytes

```
#define R(c,t)r=rand()%6+1,c&&printf(#c" a "#t"\n"#c" r %d\n"#t" h %d\n",r,t-=t<r?t:r),t||puts(#c" w")
f(A,B,r){for(A=B=10;A*B;R(B,A))R(A,B);}

```

Try it online!
> 3 votes

# Answer
## Batch, 174 bytes

```
@set/aA=B=10
@set c=A
@set d=B
:g
@set/ar=%random%%%6+1,h=%d%-=r
@echo %c% a %d%
@echo %c% r %r%
@echo %d% h %h%
@if %h% gtr 0 set c=%d%&set d=%c%&goto g
@echo %c% w

```

Explanation: `%` variable references are substituted at parse time. This has two useful benefits:

* `%d%-=r` subtracts `r` from the variable named by `d` (i.e. indirect reference)
* `set c=%d%&set d=%c%` is simply a straight swap.
> 2 votes

# Answer
# PHP 7.1: 159 bytes

```
<?php $A=$B=10;$t='AB';while($A>0&&$B>0){$a=$t[0];$b=$t[1];$d=rand(1,6);$$b-=$d;echo"$a a $b\n$a r $d\n$b h {$$b}\n";$t=strrev($t);}echo($A>0?'A':'B')." w\n";

```

Run it in the browser here!

# PHP 5.6: 156 bytes

```
<?php $A=$B=10;$t='AB';while($A>0&&$B>0){list($a,$b)=$t;$d=rand(1,6);$$b-=$d;echo"$a a $b\n$a r $d\n$b h {$$b}\n";$t=strrev($t);}echo($A>0?'A':'B')." w\n";

```

Run it in the browser here!

Here's what the PHP 5.6 solution looks like with formatting and comments:

```
<?php
// Initialize both HP counters
$A = $B = 10;

// Set the turn order as a string (which 5.6 allows to be unpacked into a list)
$t = 'AB';

// Run this loop as long as both players have HP
while ($A > 0 && $B > 0) {
    // Unpack the turn string into $a and $b variables; on the first run, $a = 'A'
    // and $b = 'B'. This is no longer possible in PHP 7.0, so the PHP 7.0
    // solution needed to use an array instead.
    list($a, $b) = $t;

    // Set damage to a random number between 1 and 6
    $d = rand(1, 6);

    // Subtract the damage from the referenced value $b. On the first turn, this
    // is 'B', so this ends up subtracting $d from $B. Next turn, $b will be 'A',
    // so it'll subtract $d from $A
    $$b -= $d;

    // Echo the string (interpolated values)
    echo "$a a $b\n$a r $d\n$b h {$$b}\n";

    // Reverse the turn order string ('AB' becomes 'BA', which will affect the
    // call to list in the first line of the while-loop)
    $t = strrev($t);
}

// Someone's run out of HP; figure out whom by figuring out who still has HP
echo ($A > 0 ? 'A' : 'B') . " w\n";

```
> 2 votes

# Answer
# F#, 238 235 bytes

I thought I was doing well, but you've all far outclassed me!

```
let p=printfn
let mutable A=10
let mutable B=A
let x h a d=
 p"%s a %s"a d
 let i=(new System.Random()).Next(1,7)
 let j=h-i
 p"%s r %i"a i
 p"%s h %i"d j
 if j<=0 then p"%s w"a
 j
while A*B>0 do
 B<-x B"A""B"
 if B>0 then A<-x A"B""A"

```

Try it online!

Thanks to Rogem for the brilliant advice to use A\*B\>0 instead of A\>0&&B\>0 (takes off 3 bytes).

Thank you also to officialaimm, whose hint about predefining printf in the Python answer helped me shave a few bytes off too.
> 1 votes

# Answer
# Haskell, 204 bytes

My attempt with Haskell, I wasn't able to get it more competitive unfortunately

```
import System.Random
main=getStdGen>>= \g->putStr$q(randomRs(1,6)g)10(10::Int)"A ""B "
(!)=(++)
l="\n"
q(x:z)a b p o=p!"a "!o!l!p!"r "!show x!l!o!"h "!show n!l!if n<1then p!"w"else q z n a o p where n=b-x

```

Try it online!

Explanations:

```
import System.Random  --import random module
main=                        --main function, program entry point
 getStdGen                   -- get the global random number generator
   >>= \g->                  --using the random generator g
       putStr $ q            --print the result of function q, passing in ..
          (randomRs (1,6) g) --an infinite list of random numbers, 1 to 6 generated by g
           10 (10::Int)      --the starting health of both players,
                             --type annotation sadly seems to be required
           "A " "B "         --The names of the players,
                             --with an extra space for formatting
(!)=(++) --define the operator ! for list (String) concatenation,
         -- we do this a lot so we save a bit by having a one byte operator
l="\n"   -- define l as the newline character

q      --define function q
 (x:z) --our list of random numbers, split into the next number (x) and the rest (z)
 a     -- the health of the active player
 b     -- the health of the player getting attacked
 p     -- the name of the active player
 o     -- the name of the player getting attacked
=
  p!"a "!o!l --create the attack action string with a newline
 !p!"r "!show x!l -- append the roll action
 !o!"h "!show n!l -- append the health remaining
 !           -- append the result of the following if
  if n<1     -- if the player being attacked has been defeated
  then p!"w" -- append the win string for the active player
  else q z n a o p  --otherwise append the result of calling q again with
                    --rest of the random numbers, and the active players swapped
  where n=b-x -- define the attacked player's new health n
              -- their current health b - the random roll x

```
> 1 votes

# Answer
# Julia 0.6, 175 bytes

```
p=println()
f(l="AB",h=[10,10],a=1)=(while min(h...)>0;d=3-a;p(l[a]," a ",l[d]);r=rand(1:6);h[d]-=r;p(l[a]," r ",r);p(l[d]," h ",max(h[d],0));a=d;end;p(l[findmax(h)[2]]," w"))

```

Try it online!

Long, ungolfed version:

```
function status(player, health)
    println("$player h $(max(0,health))")
end

function roll(player)
    x = rand(1:6)
    println("$player r $x")
    x
end

function play()
    players = ["A","B"]
    healths = [10, 10]
    attacker = 1

    while min(healths...) > 0
        println("$(players[attacker]) a $(players[3-attacker])")
        healths[3-attacker]-=roll(players[attacker])
        status(players[3-attacker], healths[3-attacker])

        attacker = 3 - attacker
    end

    winner = findmax(healths)[2]
    println("$(players[winner]) w")
end

```
> 1 votes

# Answer
## VBA, ~~222~~ ~~185~~ 179 Bytes

This recursive solution involves 3 subs

1. g is the *game start* that kicks off the first turn
2. t is called for each *turn*. It uses recursion.
3. ~~p is shorter than Debug.Print when used more than 3 times (only 4 in this solution)~~ *Edit:* Now that I learned that `Debug.?` is an acceptable alternative to `Debug.Print`, `Debug.?x` is shorter than calling a Sub to print.

```
Sub g()
t "A",10,"B",10
End Sub
Sub t(i,j,x,h)
d=Int(Rnd()*6)+1
Debug.?i &" a "&x
Debug.?i &" r "&d
h=h-d
If h<1Then
Debug.?i &" w"
Else
Debug.?x &" h "&h
t x,h,i,j
End If
End Sub

```

This was a fun challenge. If you know of an online interpreter like TIO for VB6/VBScript/VBA please leave a comment. Then I can post a link to a working solution.

If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out Option Explicit. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).

*Edit 1:* Removed whitespace that the VBA editor will automatically add back in. Reduced by 37 bytes
*Edit 2:* Removed Sub p()\* to save 6 bytes after learning `Debug.?` is an acceptable alternative to `Debug.Print`. Calling a Sub to handle `Debug.?` only saves bytes after more than six calls.
> 1 votes

---
Tags: code-golf, game
---


title: Evaluate polynomial expression string

text:
# Question
Title: Evaluate polynomial expression string
Create a function which takes a polynomial equation, a value for `x` and returns the result of the operation.

Example: given `4x^2+2x-5` and `x=3` output `37`. This is the result of `4(3)^2+2(3)-5`

* Assume all polynomials are valid
* Polynomial format will always be `coefficient(variable)^exponent => 4x^2` except :
    + When exponent is `1` it will be `coefficient(variable) => 4x`
    + When coefficient is `1` it will be `(variable)^exponent => x^2`
* Polynomials are one variable only
* Use of external libraries are forbidden
* The coefficient and variable input can be positive and negative numbers.

Test cases

* `("3x^3-5x^2+2x-10", 5) => 250`
* `("10x^4-5x^3-10x^2+3x+50", 3) => 644`
* `("10x+20", 10) => 120`
* `("-20x^2+20x-50", -8) => -1490`
* `("9", 5) => 9`
* `("8x^2+5", 0) => 5`

---

**Update**

* Polynomial format will always be `coefficient(variable)^exponent => 4x^2` except :
    + When exponent is `1` it will be `coefficient(variable) => 4x`
    + When coefficient is `1` it will be `(variable)^exponent => x^2`
* Removed the rule of negative exponent. My mistake. A valid polynomial does not contain negative exponent
* An exponent of `0` would be just `coefficient`
* Added test case for `input 0`

---

This is , so the shortest answer in bytes win.

# Answer
# JavaScript (ES7), 48 bytes

*Based upon a suggestion from @RickHitchcock*

Expects `X` in uppercase. Takes input in currying syntax `(p)(X)`.

```
p=>X=>eval(p.replace(/[X^]/g,c=>c<{}?'*X':'**'))

```

Try it online!

---

# JavaScript (ES7), 49 bytes

Same approach as @DeadPossum. Takes input in currying syntax `(p)(x)`.

```
p=>x=>eval(p.split`x`.join`*x`.split`^`.join`**`)

```

Try it online!
> 12 votes

# Answer
# Python 2, 54 bytes

-2 bytes thanks to Jo King

-5 bytes thanks to Arnauld

```
lambda p,x:eval(p.replace('^','**').replace('x','*x'))

```

Try it online!
> 8 votes

# Answer
# Python 3, 53 50 48 bytes

**edit**: -5 bytes thanks to Dennis !

```
lambda p,x:eval(p.translate({94:"**",120:"*x"}))

```

Try it online!

Used `translate` to avoid chaining `replace` calls; Python 3's version of `translate` is less awkward than its predecessor's.
> 8 votes

# Answer
# , 44 bytes

```
function(f,x)eval(parse(t=gsub("x","*x",f)))

```

Try it online!

Fairly straightforward with R. Replace `nx` with `n*x` and then `eval` the `parse`d string. `x` is used as this is how we name the second argument.

The eval function could even be used more directly with a properly formatted first argument, and other formal arguments (`y`, `z`, etc.) could be easily added:

### , 20 bytes (non-competing)

```
function(f,x)eval(f)

```

Try it online!
> 5 votes

# Answer
# JavaScript (Node.js), ~~113~~ 108 bytes

```
_=>x=>_.match(/-?(?:[x\d]+|\^?)+/g).reduce((a,b)=>b.split`x`[0]*(~b.indexOf`x`?x**(b.split`^`[1]||1):1)+a,0)

```

Try it online!

Thanks to @Arnauld

---

Since the best JS solution so far by @Arnauld (49 bytes) has already been posted and it uses `eval`, I decided to use Regex and reduce instead of that.

Pretty lengthy compared to his though.

# Explanation :

```
A =>                            // lambda function accepting argument 1
    x =>                        // argument number 2 (currying syntax used)
        A.match(                // this matches all instance of what comes next
                                // and converts to array
       /[-]?(?:[x\d]+|\^?)+/g)  // regexp for -ve sign , variable number and ^ sign
            .reduce((a, b) =>   // reduce the array to single (take 2 params a,b)
                b.split `x`     // split b at instances of `x`
                        [0]     // and select the first instance
                * (b.indexOf`x` // multiply that by value of index of x in b
                    > 0 ?       // if it is greater than 0 then
                x **            // multiplication will be with x raised to power
               (l = b.split `^` // set variable split b at every `x`
                   [1]||1       // choose first index otherwise set to one
                )               // this is what x is raised to the power
                : 1)            // in the case x is not present multiply by 1
                + a,            //  add value of `a` to that value
        0)                      // in case no reduce is possible set value to 0

```

---
> 4 votes

# Answer
# Japt 2.0, 13 bytes

```
OvUd^'*²'x"*V

```

Try it.

## Explanation:

```
OvUd^'*²'x"*V
              U = Implicit first input
              V = Implicit second input

Ov            Eval:
  Ud            In U, replace:
    ^             "^" with:
     '*²            "**"
        'x        "x" with:
          "*V       "*V"

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 22 bytes

```
ToExpression@#/.x->#2&

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~16~~ 19 bytes

```
„*(I')J'xs:'^„**:.E

```

+3 bytes as bug-fix for negative input `x`.

`.E` (*Run as Batch code*) has been replaced with *Run as Python `eval`* in this latest commit of *@Adnan*, but this version isn't on TIO yet. *@Mr.Xcoder* tested it on his local (latest version) 05AB1E to verify it's working.
See this version without `.E` to see how it converted the expression string.

**Explanation:**

```
„*I')J'xs:    # Replace all "x" with "*(n)" (where `n` is the input-integer)
              #  i.e. 5 and 3x^3-5x^2+2x-10 → 3*(5)^3-5*(5)^2-2*(5)-10
'^„**:        # Replace all "^" with "**"
              #  i.e. 3*(5)^3-5*(5)^2-2*(5)-10 → 3*(5)**3-5*(5)**2-2*(5)-10
.E            # Evaluate as Python-eval
              #  i.e. 3*(5)**3-5*(5)**2-2*(5)-10 → 250

```

---

Alternative **~~25~~ 28 bytes** program that works on the current version of TIO:

```
„*(I')J'xs:'^„**:“…¢(“s')J.e

```

Try it online.

**Explanation:**

```
„*(I')J'xs:'^„**:    # Same as explained above
“…¢(“                # Literal string "print("
     s               # Swap both
      ')             # Literal character ")"
        J            # Join everything together
                     #  i.e. 3*(5)**3-5*(5)**2-2*(5)-10 → print(3*(5)**3-5*(5)**2-2*(5)-10)
.e                   # Run as Python code
                     #  i.e. print(3*(5)**3-5*(5)**2-2*(5)-10) → 250

```

`“…¢(“` is the string `print(`, because:

* and  starts and ends the compressed string
* `…¢` is equal to `0426` because it looks at the indices in the info.txt file, where  has index 4, and `¢` has index 26.
* This index `0426` is then used in the dictionary-file, where line 427 (index 426) is the word it fetches, which is `print` in this case.
* The `(` doesn't have an index in the info.txt file, so it is interpret as is.
> 3 votes

# Answer
# TI-Basic, 6 bytes

```
Prompt X:expr(Ans

```

Expression is taken as argument and X is entered during runtime. Alternatively 8 bytes without `expr`:

```
Prompt X,u:u

```

Here both arguments are entered at runtime.
> 3 votes

# Answer
# JavaScript (Node.js), 143 bytes

I know there are better answers but I wanted to do it without using eval

```
(_,x)=>_.match(/[+-]?(?:[a-z0-9.]+|\^-?)+/gi).reduce((a,b)=>~~(b.split('x')[0])*(b.indexOf('x')>0?Math.pow(x,(l=(b.split('^')[1]))?l:1):1)+a,0)

```

Try it online!
> 2 votes

# Answer
# Physica, 35 bytes

```
->e;x:Eval@Replace[e;"x";f"*({x})"]

```

Try it online!
> 2 votes

# Answer
# Octave, ~~47~~ ~~38~~ 37 bytes

Saved a lot of bytes by taking the second input as a string instead of a number.

```
@(x,c)eval(strrep(x,'x',['*(',c,41]))

```

Try it online!

### Explanation:

Fairly straight forward: Replace `x` by `(c)` , where `c` is the second input, and evaluate. The paretheses are necessary because in Octave `-8^2 == -64`.
> 2 votes

# Answer
# Java 8, ~~150~~ ~~149~~ 148 bytes

```
n->s->new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s.replace("x","*"+n).replaceAll((s="(\\-?\\d+)")+"\\^"+s,"Math.pow($1,$2)"))

```

~~Not sure if it's possible to have a currying lambda function that throws an Exception. If it is, 1 byte can be saved changing `(s,n)->` to `n->s->`.~~ -1 byte thanks to *@OlivierGrégoire* for showing me how to do this.

Try it online.

**Explanation:**

```
n->s->     // Method with integer and String parameters and Object return-type
  new javax.script.ScriptEngineManager().getEngineByName("JS")
            //  Use a JavaScript engine
   .eval(s  //  And eval the input
      .replace("x","*"+n)
            //   After all 'x' has been replaced with '*n'
            //   (where `n` is the input-integer)
      .replaceAll((s="(\\-?\\d+)")+"\\^"+s,"Math.pow($1,$2)"))
            //   And all `A^B` have have been replaced with `Math.pow(A,B)`
            //   (where both `A` and `B` are integers)

```

Unfortunately the JavaScript eval doesn't support `**`, so I have to use a longer replace to convert it to `Math.pow` instead..
> 2 votes

# Answer
# Ruby, ~~43~~ 41 bytes

```
->p,x{eval p.gsub('^','**').gsub'x','*x'}

```

Try it online!

Saved two bytes thanks to @Mr.Xcoder

---

~~Since there isn't a Ruby answer yet I added one.~~  Nvm there was one that used a different approach

# Explanation :

```
->p,x{                    # lambda function that takes two arguments p and x
    eval(                 # eval
        p.gsub(           # replace all instance of
            '^' , '**'    # `^` with `**` (use for raised to power of)
        )                 # end gsub
        .gsub(            # start another replace all
            'x' , '*x'    # replace all instances of `x` with `*x`
        )                 # end the replace function
    )                     # end eval function
}                         # end lambda function

```
> 2 votes

# Answer
# Jelly, 21 bytes

```
ṣ”^j⁾**ṣ”xjØ(j”*;Ʋ}ŒV

```

Try it online!
> 2 votes

# Answer
# Excel, 36+2 bytes, Non-competing

Evaluating a Text field as a formula is not straight forward in Excel. There is a hidden `=EVALUATE()` function, that can be called by defining a Name.

In Excel 2007, Formulas \> Define Name. Define a Name called `E`, with Refers to:

```
=EVALUATE(SUBSTITUTE(A1,"x","*"&B1))

```

Then, with Formula input in `A1`, `x` value in `B1`, entering `=E` in `C1` returns expected result.
> 2 votes

# Answer
# Ruby, 43 bytes

```
->s,x{eval s.gsub /[x^]/,?x=>"*x",?^=>"**"}

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-pl`, 35 bytes

```
s/\^/**/g;$q=<>;s/x/*($q)/g;$_=eval

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
(x=#;ToExpression)&

```

Try it online!

Take input by currying: `f[x][expr]`.
> 1 votes

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


title: Sigmafy the expression

text:
# Question
Title: Sigmafy the expression
For those who didn't know, **Sigma** is a Greek letter which is heavily used in mathematics as the summation sign. Given a string representing an expression depending on \\$k\\$ that we will denote \\$E(k)\\$, compute the sum of the results for \\$E(k)\\$, for each \\$k\in\\{1,2,3,4,5\\}\\$. Concisely, you should find \\$S\\$ such that:

$$S=\sum^5\_{k=1}E(k)$$

An example of an expression: \\$E(k)=\frac k 2 + k^2\\$

---

### Specs

* You are guaranteed:
    + that the expression is valid, so it contains no errors, and that it's dependent of the syntax chosen (e.g: if you only support `2*k`, there will be no `2k`)
    + to only have defined values amongst your results, so no values like `1/0`, `inf` or `nan` will appear
* You can assume that the expression above is fitting the limits of the programming language of your choice, so it won't result in overflows or any other limit-related errors
* Any other non-whitespace ASCII Character instead of `k` can be chosen
* Your program **must** support the following operations:
    + addition (`+`, `plus()`,`add()`,`sum()`)
    + subtraction (`-`, `minus()`, `subtract()`)
    + exponentiation (`**`,`^`,`pow()` or others, should be specified), with support to negative bases and exponents
    + square root in the form of `sqrt(k)`, `k^0.5`, `k**0.5`, or however else you wish
    + multiplication and division
* The submission can either be a full program or a function, while mentioning its usage
* Any trailing / leading whitespace is allowed when outputting
* Minimum precision: 2 decimal places

### Test Cases (with `k`)

```
+---------------+--------------+
|  Input = E(k) |    Output    |
|---------------+--------------|
|2*k            | 30           |
|---------------+--------------|
|sqrt(k)        | 8.38         | (* with minimum decimal precision)
|---------------+--------------|
|k+k/2+k**2     | 77.5         |
|---------------+--------------|
|k**2           | 55           |
+---------------+--------------+

```

The score will be the number of bytes (of the source + compiler flags). The lowest scoring valid submission wins, while taking note that these loopholes are strictly forbidden. **Here** is a Python pseudo-code, to make things clearer.

# Answer
> 3 votes
# Jelly, 5 bytes

```
vÐ€5S

```

Try it online!

Input a valid Jelly monadic chain (I golfed them down in my link).

## How it works

```
vÐ€5S
 Ð€     for each of ...
   5        5 (implicitly converted to [1,2,3,4,5]), ...
v           evaluate the input with the above as argument
    S   and find the sum

```

# Answer
> 9 votes
## Mathematica, ~~17~~ ~~14~~ 13 bytes

*Thanks to Ian Miller for saving 3 bytes.*

*Thanks to LegionMammal978 for saving 1 byte.*

```
#~NSum~{k,5}&

```

The input should be an actual expression containing `k`, e.g.:

```
#~NSum~{k,5}&[Sqrt[k]^3+4]

```

# Answer
> 8 votes
# Python 3, ~~40~~ 37 bytes

3 bytes thanks to Arnauld.

Eval scope tricks \o/

```
f=lambda s,k=5:k and eval(s)+f(s,k-1)

```

Try it online!

Uses `k**0.5` instead of `sqrt(k)`.

# Answer
> 7 votes
## JavaScript (ES7), ~~31~~ 30 bytes

Uses `k**0.5` for `sqrt(k)`.

```
f=(e,k=6)=>--k&&f(e,k)+eval(e)

console.log(f("2*k"))
console.log(f("k**0.5"))
console.log(f("k+k/2+k**2"))
console.log(f("k**2"))
```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~8~~ ~~7~~ 6 bytes

```
6G¹.VO

```

Try it online!

Input is in postfix notation, and **uses the variable N**. 05AB1E is a stack-based language, so only postfix notation works.

Format of `E(N)`: write the number(s) you want to do the operation with, and then write the sign of the operation. For example, `3+4` would be `3 4+`, `3*4+2*3` would be `3 4* 2 3* +`. Also note that this uses `t` instead of `sqrt`, and `m` instead of `**`, so `sqrt(N)` would be `Nt`.

**Explanation:**

```
6G¹.VO
6G     For N in range(1,6). This includes [1,2,3,4,5].
  ¹.V  Read and eval input.
     O Sum results.

```

# Answer
> 3 votes
# Octave, ~~50~~ ~~46~~ ~~31~~ 29 bytes

```
@(d)eval(["k=1:5;sum(" d 41])

```

Try it online!

Exponentiation is denoted with the caret `.^` and multiplication is denoted with `.*`.

This declares an anonymous function that takes in argument `d`. It sets `k` to be equal to the range `1:5` and sums the evaluated `d` and returns it.

# Answer
> 3 votes
# Japt, 10 bytes

```
6ÆK=XOxUÃx

```

Input string should have variable as an uppercase `K`. `sqrt(K)` should be inputted as `K**0.5`.

Try it online!

## Explanation

`eval` scope didn't work in my favor; had to redefine the counting variable `X` as a global `K`.

```
6ÆK=XOxUÃx      // implicit: U = input string
6oXYZ{K=XOxU} x // expanded

6oXYZ{      }   // create array [0, 6) and map to function:
      K=X       //   redefine the array value to global K
         OxU    //   eval the input string
              x // sum the resulting array

```

# Answer
> 2 votes
# Octave, ~~25~~ 23 bytes

```
@(f)sum(inline(f)(1:5))

```

Try it online!

Exponentiation is denoted as `.^`

# Answer
> 2 votes
# APL (Dyalog), 9 bytes

```
+/⍎⎕⊣k←⍳5

```

Try it online!

Addition is `+`, subtraction is `-`, multiplication is `×`, division is `÷` exponentiation is `*` and execution is right to left, so use `()` to group expressions.

Input is in terms of `k`.

### Explanation

```
k←⍳5                    Set k to be equal to the vector 1 2 3 4 5
⊣                       The left argument:
+/                      Sum of
⍎⎕                      The evaluated input (the eval returns an array because k is an array)

```

---

And here's a solution that takes trains as input (like the Jelly answer): `+/(⍎⎕)¨⍳5`.

# Answer
> 2 votes
# Common Lisp, 55 bytes

```
(defun f(x)#.(read))(print(+(f 1)(f 2)(f 3)(f 4)(f 5)))

```

Try it online

```
Example input - output:
(* x 2) - 30
(sqrt x) - 8.382333
(+ (/ x 2) x (expt x 2)) - 155/2
(expt x 2) - 55

```

different, longer (58 bytes) version - starts getting shorter if you do sumation from 1 to 7.

```
(print #.`(+,@(mapcar #'(lambda(x)#.(read))'(1 2 3 4 5))))

```

yet another and longer method (~~65~~ 64 bytes) - doesn't define function - just inserts your expression into a loop. Should get shorter for bigger sums.

```
(setf a(read)b 0)(loop as x from 1 to 5 do(incf b #.a))(print b)

```

# Answer
> 2 votes
# Swift, ~~202~~ 184 bytes

```
import Foundation;func s(i:String){print([1,2,3,4,5].map{NSExpression(format:i.replacingOccurrences(of:"k",with:"\($0).0")).expressionValue(with:nil,context:nil)as!Float}.reduce(0,+))}

```

For some reason this will only run locally :(.

Here is an explanation of what I am doing:

```
import Foundation // Import the Foundation module

func s(i:String){ // Create a function that takes in a String and returns a Float

    print( // Print the result of the follow algorithm to strdout

        [1,2,3,4,5].map{ //Conduct the follow code on numbers 1 - 5

            NSExpression(format: // Create an expression with the following String and return it

            i.replacingOccurrences(of:"k",with:"\($0).0")) // Create a string replacing all ocurrances of 'k' in `i` with the current Float from the map

           .expressionValue(with:nil,context:nil)as!Float // Get the resulting value of the expression

       }.reduce(0,+) // Add the result of all the expressions together
    )
}

```

Thanks to @Mr. Xcoder for saving 15 bytes!

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

```
Σ(expr(Ans),K,1,5

```

Call with `"string":prgmNAME`, where `string` is any valid TI-Basic expression of `K`.

# Answer
> 1 votes
# Stacked, 16 bytes

```
5~>[@k#~]2/"!sum

```

Try it online!

`5~>` is a range from 1 to 5 incluive. `2/` makes a func dyadic, `"` is pair-wise, and `!` is execute. This thus maps the range `[1, 5]` with the input, which is then evaluated after defining the range member to be `k`. Then, the results are summed.

# Answer
> 1 votes
# dc, ~~31~~ 24 bytes

```
?sa1k[lax+Kd1+k5>p]dspxp

```

The input must be given in reverse-Polish notation (also known as postfix notation) and enclosed in square brackets (`[]`) with:

* `K` replacing `k` as the parameter;
* `+` representing addition;
* `-` representing subtraction and `_` followed by any number representing a negative number;
* `*` representing multiplication;
* `/` representing division;
* `^` representing exponentiation;
* `v` representing the square-root.

For example, `-2*k+k+3*k**2+k**0.5-k/2` would be input as `[_2K*K+K2^3*+Kv+K2/-]`. This takes due advantage of the fact that `K` is a `dc` command which returns the current precision (initially set to `1`). Therefore, by the end, this returns the output with a precision of `6`.

Try it online!

# Answer
> 1 votes
# Tcl, 58 bytes

```
proc S {f s\ 0} {time {incr k
set s [expr $s+$f]} 5
set s}

```

Try it online!

If it only worked with integers, I could golf it more!

# Answer
> 1 votes
# , 35 bytes

```
k=1:5;sum(eval(parse(t=scan(,""))))

```

Try it online!

TIO link includes a function solution as well (38 bytes)

---
Tags: code-golf, math, number, arithmetic
---


# Question
Title: Left Hand vs. Right Hand — Typists Challenge
Your task is to pit each side of the keyboard against each other and build two programs, in the same language, one using only keys on the left-hand side of a standard keyboard that outputs `Pollinium milk; plump pumpkin; lollipop?`, and one using the keys on the right that outputs `Weatherheaded sweetheart haberdasheress!`.

## Rules

The exact keys allowed for the left-hand program are:

```
123456!@#$%^QWERTYqwertyasdfghASDFGH`zxcvb~ZXCVB

```

and for the right-hand program:

```
7890-=&*()_+uiop[]UIOP{}jkl;'\JKL:"|nm,./NM<>?

```

There are four free keys `Esc` (`\x1b`), `Tab` (`\x09`), `Space` (`\x20`) and `Enter`(`\x0a` and/or `\x0d`) which can be used in either, neither, or both solutions.

Your score will be the total byte count for both programs. Whilst I've used the term `program`, your submissions can either be full programs, or functions as usual, and both can be different types (eg. one full program, and one function).

Your result must include the desired text, any amount of leading and trailing whitespace is fine, as long as the exact text appears within it.

Standard loopholes are forbidden.

The shortest solutions in each language win.

# Answer
> 12 votes
# Perl 5, 261 = 88 + 173 bytes

This is an example where "language options don't count" is a problem. The rigt side solution uses `-p`, the left side doesn't. So does it count as the same language or not? And should the options come from the left/right character set ?

# Left 88

use `-M5.10.0` (or `-E` from the commandline) to activate `say` Again arguable if this option should count as code and should come from the left side or if it falls under "options to set language version don't count"

```
say eYYYYZYEYWYYYYYWQYEYQWQEYQYYZYWYYYYYQYQW^q%565504004w4052bw!504!w!04!204bw56550!6!h%

```

Try it online!

# Right 173

Run with the `-p` option (which also consists of right characters)

```
}{*_=\(uuuuuuuuuuuuuiuuuuuuuuuuiuuuuuuuuuuuuuui&Uiipjipjiijij0puiipjiipp0jijipjipjipipp7|Ouiujujjuiuuu0kouuujuiju0jijujuikjujukk7&"7oulio7iouloli77ooliou7liiu7o7lu7io7o77i")

```

This can almost certainly be improved, but for now it was hard enough to get something working. Not having access to `print`, `say`, `$_` and `sub{}` makes output tricky

Try it online!

# Answer
> 12 votes
# Whitespace, ~~1175~~ ~~1143~~ ~~655~~ ~~645~~ ~~638~~ ~~632~~ ~~639~~ 578 (293 + 285) bytes

It had to be done.. ;p
~~Can definitely be golfed by filling the stack reversed and printing it all at the end in some kind of loop, but this is only my second Whitespace program ever, so I've yet to figure it out..~~ EDIT: Golfed.

+7 bytes because I misspelled `pumpkin` as `pumkin`.. (Thanks for noticing, *@fəˈnɛtɪk*.)

Letters `S` (space), `T` (tab) and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Left-sided `Pollinium milk; plump pumpkin; lollipop?`:

```
[S S T  T   S T T   T   T   N
_Push_-47_?][S S S T    S N
_Push_2_p][S S S T  N
_Push_1_o][S T  S S T   N
_Copy_1st_p][S S T  T   S T N
_Push_-5_i][S S T   T   S N
_Push_-2_l][S N
S _Duplicate_-2_l][S S S T  N
_Push_1_o][S T  S S T   N
_Copy_1st_l][S S T  T   S S T   T   T   S N
_Push_-78_space][S S T  T   T   S S T   T   N
_Push_-51_;][S S S N
_Push_0_n][S S T    T   S T N
_Push_-5_i][S S T   T   T   N
_Push_-3_k][S S S T S N
_Push_2_p][S S T    T   N
_Push_-1_m][S S S T T   T   N
_Push_7_u][S S S T  S N
_Push_2_p][S S T    T   S S T   T   T   S N
_Push_-78_space][S S S T    S N
_Push_2_p][S S T    T   N
_Push_-1_m][S S S T T   T   N
_Push_7_u][S S T    T   S N
_Push_-2_l][S S S T S N
_Push_2_p][S S T    T   S S T   T   T   S N
_Push_-78_space][S S T  T   T   S S T   T   N
_Push_-51_;][S S T  T   T   N
_Push_-3_k][S S T   T   S N
_Push_-2_l][S S T   T   S T N
_Push_-5_i][S S T   T   N
_Push_-1_m][S S T   T   S S T   T   T   S N
_Push_-78_space][S S T  T   N
_Push_-1_m][S S S T T   T   N
_Push_7_u][S S T    T   S T N
_Push_-5_i][S S S N
_Push_0_n][S S T    T   S T N
_Push_-5_i][S S T   T   S N
_Push_-2_l][S N
S _Duplicate_-2_l][S S S T  N
_Push_1_o][S S T    T   T   T   T   S N
_Push_-30_P][N
S S N
_Create_Label_LOOP][S S S T T   S T T   T   S N
_Push_110][T    S S S _Add][T   N
S S _Print_as_char][N
S N
N
_Jump_to_Label_LOOP]

```

Try it online (with raw spaces, tabs and new-lines only).

Right-sided `Weatherheaded sweetheart haberdasheress!`:

```
[S S T  T   S S S T S S N
_Push_-68_!][S S S T    T   T   S N
_Push_14_s][S N
S _Duplicate_14_s][S S S N
_Push_0_e][S S S T  T   S T N
_Push_13_r][S S S N
_Push_0_e][S S S T  T   N
_Push_3_h][S S S T  T   T   S N
_Push_14_s][S S T   T   S S N
_Push_-4_a][S S T   T   N
_Push_-1_d][S S S T T   S T N
_Push_13_r][S S S N
_Push_0_e][S S T    T   T   N
_Push_-3_b][S S T   T   S S N
_Push_-4_a][S S S T T   N
_Push_3_h][S S T    T   S S S T S T N
_Push_-69_space][S S S T    T   T   T   N
_Push_15_t][S S S T T   S T N
_Push_13_r][S S T   T   S S N
_Push_-4_a][S S S N
_Push_0_e][S S S T  T   N
_Push_3_h][S S S T  T   T   T   N
_Push_15_t][S S S N
_Push_0_e][S N
S _Duplicate_0_e][S S S T   S S T   S N
_Push_18_w][S S S T T   T   S N
_Push_14_s][S S T   T   S S S T S T N
_Push_-69_space][S S T  T   N
_Push_-1_d][S S S N
_Push_0_e][S S T    T   N
_Push_-1_d][S S T   T   S S N
_Push_-4_a][S S S N
_Push_0_e][S S S T  T   N
_Push_3_h][S S S T  T   S T N
_Push_13_r][S S S N
_Push_0_e][S S S T  T   N
_Push_3_h][S S S T  T   T   T   N
_Push_15_t][S S T   T   S S N
_Push_-4_a][S S S N
_Push_0_e][S S T    T   T   T   S N
_Push_-14_W][N
S S N
_Create_Label_LOOP][S S S T T   S S T   S T N
_Push_101][T    S S S _Add][T   N
S S _Print_as_char][N
S N
N
_Jump_to_Label_LOOP]

```

Try it online (with raw spaces, tabs and new-lines only).

---

**Explanation:**

It first build the stack reversed. Pushing a number is done as follows:

* `S` at the start: Enable Stack Manipulation
* `S`: Push what follows as number to the stack
* `S`/`T`: Sign bit where `S` is positive and `T` is negative
* Some `T` and `S` followed by an `N`: Put number as binary to the stack (`T=1` and `S=0`).

---

Then it will loop over the stack reversed and print everything as characters. It does this as follows:

1. Push 0 (`SSSN`)
2. Push all numbers indicating the characters reversed as explained above
3. Create a `Label_0` (`NSSN`)
    1. Duplicate the top of the stack (`SNS`)
    2. If this value is 0: Jump to `Label_1` (`NTSTN`)
    3. Else: Pop and print the top of the stack as character (`TNSS`)
    4. Jump to `Label_0` (`NSNN`)
4. Create `Label_1` (`NSSTN`)

This above is the default layout for both programs. Here is the change-log for this default layout which lowered the byte-count even further:

1. All numbers are lowered by the same amount (~~`100`~~ `110` in the first program, and ~~`102`~~ `101` in the second) to decrease the binary digits used for the now lower numbers, and between step 3.2 and 3.3 the following two sub-steps are added:

* Push 110 (`SSSTTSTTTSN`) in program 1, or 101 (`SSSTTSSTSTN`) in program 2
    * Pop and add the top two values of the stack with each other, and the result is the new top of the stack (`TSSS`)
2. I've also used `SNS` in some cases to duplicate the top of the stack, which is used to golf the `ll`, `ll`, `ee` and `ss`.
3. In addition, step 4 (create `Label_1`) was removed completely. It will exit with an error, but will still output everything correctly (which is allowed according to the meta).
4. It's possible to copy an `n`'th value from the top of the stack (with `STS` \+ 0-indexed `n`), which is shorter than creating a new number in some cases.
In the first program I've done this for: the second `p` in `pop` (`STSSTN` (copy 1st) is shorter than `SSSTTSSN` (create number for 'p')), the second `l` in `lol` (`STSSTN` (copy 1st) is shorter than `SSSTSSSN` (create number for 'l')), the second `p` in `p p` (`STSSTN` (copy 1st) is shorter than `SSSTTSSN` (create number for 'p')), the second `p` in `pumlp` (`STSSTTN` (copy 3rd) is shorter than `SSSTTSSN` (create number for 'p')), the second `p` in `pmup` (`STSSTSN` (copy 2nd) is shorter than `SSSTTSSN` (create number for 'p')), the second `m` in `m m` (`STSSTN` (copy 1st) is shorter than `SSSTSSTN` (create number for 'm')), the second `i` in `ini` (`STSSTN` (copy 1st) is shorter than `SSSTSTN` (create number for 'i')).
In the second program this isn't done for any. The distance between some is pretty short, like `ere` or `ded`, but creating the number for 'e' (`SSTTN`) or 'd' (`SSTTSN`) are both shorter or of equal length as copy 1st (`STSSTN`), so I couldn't apply this trick in the second program to save bytes. ***NOTE: After golf-step 7, not all of these apply anymore.***
5. In both programs I've changed step 1 of the loop from `SSSN` (Push 0) to `SSN` (Push error\_value), and removed the steps 3.1 (`SNS` Duplicate) and 3.2 (`NTSTN` If 0: Exit). Now it will simply exit with an error that `SSN` is an unknown value as soon as it's tries to access it.
6. Removed the `SSN`(error\_value) completely in both programs. It will now stop with the error "*Can't do Infix Plus*" when it tries to do the Add-function with nothing left on the stack.
7. Changed the constant values of `100` and `102` to `110` and `101` respectively. Here the Java program used to generate the `110` constant; and here the Java program used to generate the `101` constant. Note that there are now less *Copy* used than described at point 4 above, because the new values are in many cases shorter than the copies, so re-pushing them is shorter.

# Answer
> 5 votes
# Lenguage, this many bytes

The left-hand side is 65721878296123796350462639500449228197646164622176218219262161264085219054330862921130017235140285847450697804123168755463678390611789188813352602373675420824698785508893489685489807676509031860196742608788337382365939621331808044899882497347443262020486908162559376082705672994569868 repetitions of the `a` character, which is equivalent to the following Brainfuck program:

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

```

Try it online!

The right-hand side is 636605880289050800007960838028215177632402180834140124157618258152393860687206680356620669530585999501769442445842690365640523699585001167392310123764258380235064746704898152544431842440556280249638840374132783257375880144623575829131522611446544303839106505176776161206935275549421170646618266717893044911373119804737614528140 repetitions of the `p` character, which is equivalent to the following Brainfuck program:

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

```

Try it online!

# Answer
> 3 votes
# CJam, 128 + 192 = 320 bytes

```
64G^c111c111Z^cT$111c6^111X^c1$116X^c111Y^c32c1$6$Y3#$111c4^56Z^c32c112c13$A$A$3$5$1$4$4$4$12$22$22$14$32c13$111c1$T$7$A$4$1$63c

```

Try it online!

```
'U))'i(((('_))'u('i('i(((('p))'i('i(((('_))'_)))))'i(((('_)))))'&(((((('u(('u))'i(((('i(((('u('i('i(((('_))'p))'u('&(((((('i('_))'_)))'i(((('p))'_)))))'_))'u(('i('i(((('p))'i(((('u(('u(('&(((((

```

Try it online!

# Answer
> 3 votes
# Fission, 958 + 752 = 1710 bytes

.\_.

### Left

```
D
z
^@$$$$$$$$$$$$$$$$$$$@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@~~~@!!@~~~@!@$$$$$@!@~~~~~@!@$$$$$$$$$$$$@!@~~~~~~~~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@~~~~@!@$$$@!@~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@~~~~@!@$$$$$$$$$@!@~~~~~~~~@!@$$$@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@$$$$$@!@~~~~~~~~@!@$$$@!@~~~~~@!@~~@!@$$$$$@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@$$$@!@~~~@!!@~~~@!@$$$$$$$@!@~@!@$@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!V

```

Try it online!

### Right

```
                                           } \} \    } \      } \    } \   } \   } \    } \   } \       } \    } \   } \ } \       } \   } \                                           } \   } \    } \    } \   } \   } \   } \} \      } \    } \    } \                                           } \ } \ } \   } \    } \   } \   } \    } \   } \   } \   } \    } \      } \
O________________________________________I'/O\/O\__u'/O\____i'/O\++p'/O\___/O\_i'/O\__u'/O\___/O\_____i'/O\++p'/O\+++/O\+/O\_______/O\_i'/O\_________________________________________I'/O\_u'/O\++p'/O\____/O\___/O\_i'/O\_u'/O\/O\____i'/O\++u'/O\__u'/O\_________________________________________I'/O\_/O\+/O\+++/O\____/O\___/O\_i'/O\++p'/O\___/O\_i'/O\_u'/O\____/O\____i'/O\+++++++P'L

```

Try it online!

OK, here we are with plain luck, actually .\_.
First cool feature of Fission is that it has 4 commands to create command pointers, AKA atoms: `RLDU`, so I have two commands for left and right groups.
Second lucky charm is 2 commands for output `!` and `O`, which occurs in different groups.
Third time the charm. Both outputting comands output ASCII equivalent of atoms' mass. So I need to change it some how. Lucky me! Both `+ (+1 mass)` and `_ (-1 mass)` are in one group and all needed three `$ (+1 energy)`, `~ (-1 energy)`, `@ (swap mass and energy)` are in other group.

> Also there are mirrors to control atoms in both groups! But I didn't use them in first program

So there is nothing to stop me, but it can't be compact, setting masses step-by-step.

### First program

First program consists of only `Dz^@$~!V`

```
D   create atom, going down
z   set its mass to ASCII code of 'z'
^   split atom in 2, dividing their mass. One goes left, second - right

```

Start can be simplier (just `R`), but using divide saves some bytes for first letter.
Atom, that goes left wraps around and encounters `V`, which makes him going down and wrapping indefinitely, doing nothing.
Second atom goes rigth and will encounter bunch of repeated patterns `@...@!` for each letter to output.

```
@   swap atom's mass and energy
... increament or decrement energy until it would match desired ASCII code
@   swap again
!   print character by atoms mass

```

Eventually it will encounter `V` and share fate of first atom. There is no way to destroy them or halt with left part of keyboard.

### Second program

Second comes with its ups and downs. I've got comands to change mass directly, but output command `O` destroys atoms, so I need to preserve them somehow.
Program starts on the right from `L` with atom going left.

Repeated pattern:

```
} \
/O\...X'

```

`'` puts next encoutered char's ASCII code in atoms' mass, so code of some `X` is stored first, than mass is changed by `_` and `+` to exact value.
Sometimes `X'` is skipped, if it is shorter to use just `_` and `+`.

Atom comes from the left, mirrors two times and hits `}` from left. In this case `}` works like cloner, sending two identical atoms up and down. Down atom reflects by mirror and goes left. Up atom wraps, hits same mirror but from below and so reflects right, encountering `O` and printing.
At the end last atom meets final `O` to be destructed.

---
Tags: code-golf, kolmogorov-complexity, restricted-source
---