# Question
Title: Imaginary Parts of Non-Trivial Riemann Zeroes
## Introduction

According to the Riemann Hypothesis, all zeroes of the Riemann zeta function are either negative even integers (called *trivial zeroes*) or complex numbers of the form `1/2 ± i*t` for some real `t` value (called *non-trivial zeroes*). For this challenge, we will be considering only the non-trivial zeroes whose imaginary part is positive, and we will be assuming the Riemann Hypothesis is true. These non-trivial zeroes can be ordered by the magnitude of their imaginary parts. The first few are approximately `0.5 + 14.1347251i, 0.5 + 21.0220396i, 0.5 + 25.0108576i, 0.5 + 30.4248761i, 0.5 + 32.9350616i`.

## The Challenge

Given an integer `N`, output the imaginary part of the `N`th non-trivial zero of the Riemann zeta function, rounded to the nearest integer (rounded half-up, so `13.5` would round to `14`).

## Rules

* The input and output will be within the representable range of integers for your language.
* As previously stated, for the purposes of this challenge, the Riemann Hypothesis is assumed to be true.
* You may choose whether the input is zero-indexed or one-indexed.

## Test Cases

The following test cases are one-indexed.

```
1       14
2       21
3       25
4       30
5       33
6       38
7       41
8       43
9       48
10      50
50      143
100     237

```

## OEIS Entry

This is OEIS sequence A002410.

# Answer
## Mathematica, 23 bytes

```
⌊Im@ZetaZero@#+.5⌋&

```

Unfortunately, `Round` rounds `.5` to the nearest even number, so we have to implement rounding by adding `.5` and flooring.
> 5 votes

# Answer
# PARI/GP, 25 bytes

There's not much support in GP for analytic number theory (it's mostly algebraic), but just enough for this challenge.

```
n->lfunzeros(1,15*n)[n]\/1

```
> 1 votes

# Answer
## Sage, 34 bytes

```
lambda n:round(lcalc.zeros(n)[-1])

```

Try it online

This solution is a golfed form of the program found on the OEIS page.

`lcalc.zeros` is a function (which is thankfully spelled the shorter way, rather than `zeroes` for an extra byte) that returns the imaginary parts of the first `n` non-trivial Riemann zeta zeros. Taking the `-1`st index returns the `n`th zero (1-indexed), and `round` rounds it to the nearest integer. In Python 3, `round` uses banker's rounding (half-to-nearest-even), but thankfully Sage runs on Python 2, where `round` uses half-up rounding.
> 1 votes

---
Tags: code-golf, math, number-theory, complex-numbers
---


title: Rotate a camera; save an Astronaut

text:
# Question
Title: Rotate a camera; save an Astronaut
Note: *Minor* spoilers for *The Martian* are in this challenge. Read ahead with caution

---

The Martian is a Science Fiction novel about astronaut and botanist extraordinaire, *Mark Watney*, who has been accidentally stranded on Mars. At one point in the book, Mark tries communicating with NASA, but the only means of communication they have is a camera. Mark sends messages by writing on index cards, and, since NASA can rotate the camera 360 degrees, NASA sends replies back by pointing the camera at cards labeled "Yes" or "No".

Since the only data NASA can send is the direction the camera is facing, Mark comes up with a system where they can point at cards with alphabet characters on them to type messages. But using the letters 'a-z' would be impractical. To quote the book (from this answer, over on scifi.se):

> We’ll need to talk faster than yes/no questions every half hour. The camera can rotate 360 degrees, and I have plenty of antenna parts. Time to make an alphabet. But I can’t just use the letters A through Z. Twenty-six letters plus my question card would be twenty-seven cards around the lander. Each one would only get 13 degrees of arc. Even if JPL points the camera perfectly, there’s a good chance I won’t know which letter they meant.
>
> So I’ll have to use ASCII. That’s how computers manage characters. Each character has a numerical code between 0 and 255. Values between 0 and 255 can be expressed as 2 hexadecimal digits. By giving me pairs of hex digits, they can send any character they like, including numbers, punctuation, etc.
>
> ...
>
> So I’ll make cards for 0 through 9, and A through F. That makes 16 cards to place around the camera, plus the question card. Seventeen cards means over 21 degrees each. Much easier to deal with.

Your goal today, as one of the top software engineers at NASA, is to write a program to encode the various angles of the camera. The seventeen cards Mark has for you to point at are (in order):

```
?0123456789ABCDEF

```

and each of these cards is 21 degrees apart, so to rotate the camera from `?` to `0`, you should rotate the camera 21 degrees, and `2` to `1` is -21 degrees. (It's not *exactly* 21, but we'll round to keep it simpler) This wraps, so to go from `F` to `3` is 105 degrees (5 turns, 5 * 21 = 105). This is more efficient than going -252, since the camera won't have to move as far.

Here's what your program or function must do.

1. Take a string as input. We'll call this string *s*. To keep it simple, we'll say that the input will only ever be printable ASCII. For our example, let's say that the input was `STATUS`
2. Convert each character to its hexadecimal representation. This would convert `STATUS` to `53 54 41 54 55 53`.
3. Print out or return the consecutive degree turns the camera will need to make in order to point at each card and return to the "Question Card". For our example, this would be:

```
6  * 21 = 126   (?-5)
-2 * 21 = -42   (5-3)
2  * 21 = 42    (3-5)
-1 * 21 = -21   (5-4)
0  * 21 = 0     (4-4)
-3 * 21 = -63   (4-1)
4  * 21 = 84    (1-5)
-1 * 21 = -21   (5-4)
1  * 21 = 21    (4-4)
0  * 21 = 0     (5-5)
0  * 21 = 0     (5-5)
-2 * 21 = -42   (5-3)
-4 * 21 = -84   (3-?)

```

Or, in array format:

```
[126, -42, 42, -21, 0, -63, 84, -21, 21, 0, 0, -42, -84]

```

Note that you must always take the smallest of the possible rotations. So if the input was `NO`, which is `4E 4F`, you should output:

```
5    * 21 = 105
-7   * 21 = -147
7    * 21 = 147
-6   * 21 = -126
1    * 21 = 21

```

Rather than:

```
 5   * 21 = 105
 10  * 21 = 210
 -10 * 21 = -210
 11  * 21 = 231
 -16 * 21 = -336

```

Here are some more worked examples:

```
Input: CROPS?
ASCII: 43 52 4F 50 53 3F
Worked Example:

5  * 21 = 105
-1 * 21 = -21
2  * 21 = 42
-3 * 21 = -63
2  * 21 = 42
-6 * 21 = -126
7  * 21 = 147
-5 * 21 = -105
5  * 21 = 105
-2 * 21 = -42
0  * 21 = 0
-5  * 21 = -105
1 * 21 = 21

Result: [105 -21 42 -63 42 -126 147 -105 105 -42 0 -105 21]

Input: DDD
ASCII: 44 44 44
Worked Example:

5   * 21 = 105
0   * 21 = 0
0   * 21 = 0
0   * 21 = 0
0   * 21 = 0
0   * 21 = 0
-5  * 21 = -105

Result: [105, 0, 0, 0, 0, 0, -105]

Input: Hello world!
ASCII: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21
Worked example:

5   * 21 = 105
4   * 21 = 84
-2  * 21 = -42
-1  * 21 = -21
1   * 21 = 21
6   * 21 = 126
-6  * 21 = -126
6   * 21 = 126
-6  * 21 = -126
-8  * 21 = -168
4   * 21 = 84
-2  * 21 = -42
7   * 21 = 147
0   * 21 = 0
-1  * 21 = -21
-8  * 21 = -168
-8  * 21 = -168
-5  * 21 = -105
4   * 21 = 84
6   * 21 = 126
-6  * 21 = -126
-2  * 21 = -42
-2  * 21 = -42
-1  * 21 = -21
-2  * 21 = -42

Result: [105 84 -42 -21 21 126 -126 126 -126 -168 84 -42 147 0 -21 -168 -168 -105 84 126 -126 -42 -42 -21 -42]

```

Since NASA prides itself on efficiency, your goal is to write the shortest code possible. Standard loopholes apply. Now bring him home!

# Answer
> 5 votes
# JavaScript (ES6), ~~103~~ 99 bytes

```
s=>[...s.replace(/./g,c=>c.charCodeAt().toString(16)),10].map(n=>((24-p-~(p='0x'+n))%17-8)*21,p=-1)

```

### Test cases

```
let f =
s=>[...s.replace(/./g,c=>c.charCodeAt().toString(16)),10].map(n=>((24-p-~(p='0x'+n))%17-8)*21,p=-1)

let g = s => console.log(`f('${s}'): [${f(s)}]`)
g('STATUS')
g('NO')
g('CROPS?')
g('DDD')
g('Hello world!')
```

# Answer
> 4 votes
# C, ~~212~~ ~~202~~ ~~199~~ 187 bytes

*3 bytes saved thanks to @KritixiLithos!*

```
i;f(a,b){i=abs(a-b);i=8>i?i:17-i;i=a<b&a>b-8?i:a<b&a<b-8?-i:b<a&b>a-8?-i:i;i*=21;}v;g(char*s){for(v=0;*s;s+=v++%2)printf("%d ",v?v%2?f(*s%16,s[1]?s[1]/16:-1):f(*s/16,*s%16):f(-1,*s/16));}

```

Try it online!

# Answer
> 3 votes
# Python, ~~187~~ 178 bytes

```
def g(x):w,z=map('?0123456789abcdef'.index,x);d=w-z;return min(d,d+17*(d<=0 or -1),key=abs)*21
def f(s):s=''.join(map('{:2x}'.format,s.encode()));return[*map(g,zip(s+'?','?'+s))]

```

### Test cases

```
for k in ['STATUS', 'NO', 'CROPS?', 'DDD', 'Hello world!']:
    print('Input:  {}\nOutput: {}'.format(k, f(k)))

```

# Answer
> 2 votes
# Python 2, ~~135~~ 112 bytes

```
h=reduce(lambda l,r:l+(r/16,r%16),map(ord,input()),())
print[(((r-l+8)%17)-8)*21for l,r in zip((-1,)+h,h+(-1,))]

```

**Try it online!**

# Answer
> 1 votes
# Jelly, ~~21~~ 19 bytes

```
Ob⁴F-;;-I+8%17_8×21

```

**Try it online!**

### How?

```
Ob⁴F-;;-I+8%17_8×21 - Main link: string s        e.g. 'e.g.'
O                   - cast to ordinals            [101,     46,       103,      46]
 b                  - convert to base
  ⁴                 -     16                   [[6,   5], [2,  14], [6,   7], [2,  14]]
   F                - flatten                   [6,   5,   2,  14,   6,   7,   2,  14]
    -;              - -1 concatenate      [-1,   6,   5,   2,  14,   6,   7,   2,  14]
      ;-            - concatenate -1      [-1,   6,   5,   2,  14,   6,   7,   2,  14,  -1]
        I           - increments            [  7,  -1,  -3,  12,  -8,   1,  -5,  12, -15]
         +8         - add 8                 [ 15,   7,   5,  20,   0,   9,   3,  20,  -7]
           %17      - mod 17                [ 15,   7,   5,   3,   0,   9,   3,   3,  10]
              _8    - subtract 8            [  7,  -1,  -3,  -5,  -8,   1,  -5,  -5,   2]
                ×21 - multiply by 21        [147, -21, -63,-105,-168,  21,-105,-105,  42]

```

# Answer
> 1 votes
# Ohm, ~~20~~ 19 bytes (CP437)

**EDIT**: Saved 1 byte by changing a map block to repeated single-component maps.

Would probably be quite a bit shorter if I had implicit vectorization.

```
`»x»}{»úΓXΓHδ▓_~21*

```

Explanation:

```
`»x»}{»úΓXΓHδ▓_~21*    Main wire, arguments: s

`»x                    Convert char codes of s to hex
   »}                  Split digit pairs
     {                 Flatten
      »ú               Convert digits back to base 10
        ΓXΓH           Append and prepend with -1
            δ          Get deltas between each element of array
             ▓         Map array over...
              _~21*      Negate, multiply by 21

```

# Answer
> 0 votes
# PHP, ~~125~~ 116 bytes:

```
function m($i){static$a;$a+=$d=($i-$a+10)%17-9;echo$d*21,"
";}for(;$c=ord($argv[1][$i++]);m($c%16))m($c/16|0);m(-1);

```

**breakdown**

```
function m($i)              // function to turn camera:
{
    static$a;                   // remember angle
    $a+=                        // add delta to angle
    $d=($i-$a+10)%17-9;         // delta: target=nibble value+1-current angle
                                // add 9, modulo 17, -9 -> shortest movement
    echo$d*21,"\n";                 // print delta * 21 and a linebreak
}
for(;$c=ord($argv[1][$i++]);// loop through input characters
    m($c%16))                   // 2. move to low nibble value
    m($c/16|0)                  // 1. move to high nibble value
;
m(-1);                      // move back to "?"

```

---

Of course, `21` is pretty inaccurate and may fail for strings longer than 14 characters; but then ... `360/17` would be four bytes longer.

> An alternative solution would have been to attach a laser pointer to the camera;
> we could use all printable ascii chars and a "question" card at 3.75 degrees each with that.
>
> Another alternative: Use 16 cards (at 22.5 degrees) with 6 characters each:
> implement some sort of T9 and we can omit the high nibble. ;)

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


title: Terra Mystica: Cycling Power

text:
# Question
Title: Terra Mystica: Cycling Power
The boardgame Terra Mystica has some very interesting mechanics for one of the primary resources, power. Instead of gaining and spending units of power from a bank, each player starts the game with exactly 12 units of power which are distributed over three "bowls", which are labelled I, II and III. Gaining and spending power then simply shifts power between these bowls:

* To spend a unit of power, move it from bowl III to bowl I (provided you have a unit in bowl III).
* When you gain a unit of power, if there is a unit in bowl I, move it to bowl II. If there are no units in bowl I, but there is a unit in bowl II, move it to bowl III. If all units are already in bowl III, nothing happens.
* When you gain or spend multiple units at once, they are processed one unit at a time.

Here is an example. Say, a player starts with the following power distribution (given in order `I | II | III`):

```
5 | 7 | 0

```

Their power changes as follows if they gain and spend power a few times:

```
               5 |  7 |  0
Gain  3  ==>   2 | 10 |  0
Gain  6  ==>   0 |  8 |  4   (move 2 power from I to II,
                              then the remaining 4 from II to III)
Gain  7  ==>   0 |  1 | 11
Spend 4  ==>   4 |  1 |  7
Gain  1  ==>   3 |  2 |  7
Spend 7  ==>  10 |  2 |  0
Gain 12  ==>   0 | 10 |  2   (move 10 power from I to II,
                              then the remaining 2 from II to III)
Gain 12  ==>   0 |  0 | 12   (the two excess units go to waste)

```

Your task is to compute the result of one such gaining or spending event.

## The Challenge

You are given four integers as input. The first three, `I`, `II`, `III`, represent the amount of power in each of the three bowls. They will be non-negative, and they will sum to 12. The fourth number, `P`, is the amount of power gained or spent, and will be in the inclusive range `[-III, 24]` (so you may assume that the player will never try to spend more power than they currently can, but they might be gaining more power than they need to move all power into bowl III).

You may take these numbers in any consistent order, as separate arguments, as a list of integers, or as a string containing these integers. You can also take `P` as one argument, as `I`, `II`, `III` as a separate list argument.

You should output three integers `I'`, `II'`, `III'` which represent the amount of power in each bowl *after* `P` units were gained or spent, following the rules explained above.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

```
I II III P => I' II' III'
5 7 0 3    => 2 10 0
2 10 0 6   => 0 8 4
0 8 4 7    => 0 1 11
0 1 11 -4  => 4 1 7
4 1 7 0    => 4 1 7
4 1 7 1    => 3 2 7
3 2 7 -7   => 10 2 0
10 2 0 12  => 0 10 2
0 10 2 12  => 0 0 12

```

# Answer
> 6 votes
# C, ~~97~~ 94 bytes

```
f(i,j,k,n){for(;n;n-=n/abs(n))n<0?k?++i+--k:0:i?++j+--i:j?++k+--j:0;printf("%d %d %d",i,j,k);}

```

In ungolfed form:

```
f(i, j, k, n) {
    while (n) {
        if (n < 0) {
            if (k) {
                ++i; --k;
            }
            ++n;
        } else {
            if (i) {
                ++j; --i;
            }
            else if (j) {
                ++k; --j;
            }
            --n;
        }
    }
    printf("%d %d %d", i, j, k);
}

```

# Answer
> 6 votes
## Mathematica, 52 bytes

```
{x=#-#4~Min~#,y=Max[#2+#-Abs[#4~Max~0-#],0],12-x-y}&

```

This is an unnamed function that takes a list `{I, II, III, P}` as input and returns a list `{I', II', III'}`.

A closed-form solution. It doesn't really feel optimal yet...

# Answer
> 5 votes
# Python 2, 104 bytes

```
def f(i,d,t,g):
 x=min(i,g);i-=x;q=g>0;g-=x
 if q:d+=x;x=min(d,g);g-=x;d-=x;t+=x
 else:t+=x
 print i,d,t

```

**Try it online**

**Ungolfed:**

```
def f(i,d,t,g):
 if g>0:
    x=min(i,g)
    g-=x
    i-=x
    d+=x
    x=min(d,g)
    g-=x
    d-=x
    t+=x
 else:
    x=min(i,g)
    g-=x
    i-=x
    t+=x
 print(i,d,t)

```

# Answer
> 5 votes
# Röda, ~~100~~ 94 bytes

```
f a,b,c,p{{c+=p;a-=p}if[p<0]else{{a--;b++;p--}while[p*a>0];{b--;c++;p--}while[p*b>0]};[a,b,c]}

```

Ungolfed:

```
f a,b,c,p {
    if [ p < 0 ] do
        c += p
        a -= p
    else
        { a-=1; b+=1; p-=1 } while [ p > 0 and a > 0 ]
        { b-=1; c+=1; p-=1 } while [ p > 0 and b > 0 ]
    done
    return a, b, c
}

```

# Answer
> 5 votes
## Haskell, 58 bytes

```
f(a,b,c)d|m<-min a d,z<-min(c+d-max 0 m)12=(a-m,b+c+m-z,z)

```

The intermediate value `m` denotes the amount of power going from (or to, if negative) the first bowl, `z` denotes the amount of power in the third bowl after the action. A last minute one byte optimization changed the old expression for the second bowl from `12-a+m-z` using the identity `a+b+c=12`.

The natural result type is a triple for the bowls, so the input also takes the bowls as a triple and the power change as a second argument. This allows to handle all test cases with one application of `scanl`:

```
*Main> scanl f (5,7,0) [3,6,7,-4,0,1,-7,12,12]
[(5,7,0),(2,10,0),(0,8,4),(0,1,11),(4,1,7),(4,1,7),(3,2,7),(10,2,0),(0,10,2),(0,0,12)]

```

# Answer
> 4 votes
# JavaScript, ~~61~~ 59 bytes

```
(a,b,c,d)=>[r=a-d>0?a-d:0,s=r?b:b-d+2*a>0?b-d+2*a:0,12-r-s]

```

Try it online!

# Answer
> 3 votes
# GNU sed, 66 bytes

Includes +1 for `-r`

```
/-/!{:
s/1,(.* )1/,1\1/
t}
s/(.*)(1+) -\2/\2\1/
s/(,,1{12}).*/\1/

```

Uses unary (see this consensus).

Try it online!

```
/-/!{                  # If there is not a '-'
  :                    # start loop
  s/1,(.* )1/,1\1/     # move a 1 from before a ',' to after the ',' for every 1 after the space
                       # sed reads left to right, so this takes everything from the first bowl before starting on the second
  t                    # loop if something changed
}                      # end if
s/(.*)(1+) -\2/\2\1/   # take all of the 1s from after a '-' and move them to the begining.
                       # at the same time, remove that many 1s from the 3rd bowl
s/(,,1{12}).*/\1/      # remove everything after 12 1s in the third bowl

```

# Answer
> 3 votes
# Retina,  46  41 39 38 bytes

*Thanks to* Martin Ender *for multiple helpful suggestions!*

```
+`1,(.*¶)1
,1$1
(.*)(1+)¶-\2$
$2$1
G`,

```

Takes input in unary. The first line contains the amounts of power in the three bowls, comma separated, the second line the amount of power to cycle.

Test suite \- Takes all inputs on a single line and converts from decimal to unary and vice-versa for convenience of use.

### Explanation

```
+`1,(.*¶)1
,1$1

```

Positive case: we repeatedly remove the leading `1` from the second line, and move a `1` from the first non-empty bowl to the following one, as long as this operation is possible (i.e. the number of power to cycle is non-zero and not all power is in the third bowl). The `s` modifier means `single-line`, allowing `.` to match also the newline.

```
(.*)(1+)¶-\2$
$2$1

```

Negative case: done all in one step, moving the amount of power indicated by the last input from the third to the first bowl. This will also remove the line containing the negative amount of power to move.

```
G`,

```

Keep (grep) only lines containing a comma. This will get rid of the eventual remains of the first line.

# Answer
> 3 votes
# Python 2, 91 bytes

Based on this answer

```
def f(i,d,t,g):
 x=min(i,g);i-=x
 if g>0:y=min(d+x,g-x);d+=x-y;t+=y
 else:t+=x
 print i,d,t

```

**Try it online**

**Ungolfed:**

```
def f(i,d,t,g):
 if g>0:
    x=min(i,g)
    y=min(d+x,g-x)
    i-=x
    d+=x-y
    t+=y
 else:
    x=min(i,g)
    i-=x
    t+=x
 print(i,d,t)

```

# Answer
> 2 votes
## Batch, 87 bytes

```
@set/a"i=%4-%1,j=%4*(-%4>>5)-%2-2*i*(-i>>5),i*=i>>5,j*=j>>5,k=12-i-j
@echo %i% %j% %k%

```

Use the following formulae:

```
I' = min(I - P, 0)
II' = min(II + min(P, 0) - 2 * min(P - I, 0), 0)
III' = 12 - I' - II'

```

Since Batch doesn't have a less than operator, I calculate `i = min(-i, 0)` using `i*=i>>5`.

# Answer
> 2 votes
# Perl 6, 99 bytes

```
->\a,\b,\c,\d{d>0??[»+»] (a,b,c),|(|((-1,1,0)xx a),|((0,-1,1)xx a+b),|(0 xx*))[^d]!!(a- d,b,c+d)}

```

Let `a`, `b`, and `c` be the number of starting tokens in bowls I, II, and III respectively. Then, for the adding power case, a list is created that contains `a` copies of the triplet `(-1, 1, 0)`, followed by `a + b` copies of the triplet `(0, -1, 1)`, followed by infinite copies of `0`. The first `d` elements of this list, `d` being the amount of power to add, are added elementwise to the starting power distribution.

For subtracting power (negative `d`), a simple closed form is used: `(a - d, b, c + d)`.

# Answer
> 2 votes
# tinylisp, 134 bytes

```
(d f(q((x y z p)(i p(i(l p 0)(f(s x p)y(a z p)0)(i x(f(s x 1)(a y 1)z(s p 1))(i y(f x(s y 1)(a z 1)(s p 1))(f x y z 0))))(c x(c y(c z(

```

Defines a function `f` that takes four arguments, the three bowls (`x y z`) and the amount of power transacted (`p`), and returns a list of the three bowls after the transaction. Here's a properly spaced version with all test cases: Try it online!

```
(d f                         Define f to be
 (q(                          a quoted two-item list (which acts as a function):
  (x y z p)                    Arglist: the three bowls x y z and power p
  (i p                         If p is nonzero
   (i (l p 0)                   then if p is negative (spending power)
    (f(s x p)y(a z p)0)          then take -p from z, add -p to x, and recurse with p=0
    (i x                         else (gaining power), if x is nonzero
     (f(s x 1)(a y 1)z(s p 1))    then take 1 from x, add to y, decrement p and recurse
     (i y                         else if y is nonzero
      (f x(s y 1)(a z 1)(s p 1))   then take 1 from y, add to z, decrement p and recurse
      (f x y z 0))))               else no moves possible; recurse with p=0
   (c x(c y(c z())))))))        else (p=0), cons x y z into a list and return it

```

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


title: What's my question record?

text:
# Question
Title: What's my question record?
There's a confusing factor in the 'Curious' badge. The "Positive question record".

`(total questions - negative questions - closed - deleted)/total questions` is the formula of the question record. (negative, closed and deleted 'stack' with each other. that means if a question is negative and closed, it counts as two minus.)

Luckily, you know a list of your questions. Make a program that calculates your question record.

# The Input

You will be given an array of question datas. A question data is made of 2 datas.

* The votes (integer)
* The state (`o`(open), `c`(closed), `d`(deleted), `b` (closed *and* deleted) is the default, You may change the type and the characters for each states.)

# Examples

* `[[-1,'o'],[1,'o']]` =\> `0.5` (2 total, 1 minus points)
* `[[-1,'d'],[2,'c']]` =\> `-0.5` (2 total, 3 minus points)
* `[[-1,'b']]` =\> `-2` (1 total, 3 minus points)
* `[[23,'o'],[7,'c'],[7,'c'],[-1,'o'],[-5,'b'],[-11,'d'],[-3,'d'],[-3,'b'],[-15,'b']]` =\> `-0.77778`(The precision is 5 digits past decimal point, rounded half-up. fractions are acceptable) (Oh my, my question record is horrible.)
* \` ('Minus points' is the sum of negative, closed and deleted.)

# Rules

* Format of input is your choice. You don't necessarily need to use the format in the Examples.

Reference

# Answer
# dc, 8 bytes

I've been waiting to use dc's feature, that the input is both data and code, for quite some time.

```
0d?n47Pp

```

The idea behind the script is that all of the number crunching will be done by the question's state representation, a valid input string. The main script's task is then to initialize the counters, read the input (and execute it as code at the same time), and print the result when done, as a fraction.

Here are the strings I use to represent the state. The OP allows non-char types!

* '`o`' -\> "1r\[1-\]sX0\>X**0-**+r1+r"
* '`c`' -\> "1r\[1-\]sX0\>X**1-**+r1+r"
* '`d`' -\> "1r\[1-\]sX0\>X**1-**+r1+r**rr**"

The extra "**rr**" part at the end changes nothing, it is there to differentiate the `d` state from `c`.

* '`b`' -\> "1r\[1-\]sX0\>X**2-**+r1+r"

**Try it online!** The default input there is the last example.

**Test run:** from the 2nd example. Negative numbers in dc are given with `_` as the minus sign. This is allowed by this meta consensus.

```
dc -f question_record.dc <<< "_1 1r[1-]sX0>X1-+r1+rrr 2 1r[1-]sX0>X1-+r1+r"
-1/2

```

---

**Explanation of the script:**

```
0d
# push 0 twice. The bottom cell will keep track of the number of questions, and the
#top cell of the sum part of the score.
?
# read input, which in this case is actually pairs of (data, code), that do all the
#number crunching
n47Pp
# print the 2 cells as a fraction: print top, print '/' (ASCII 47), print bottom

```

**Explanation of the state's representation:** I take the `c` state as example code

The stack at the start of this snippet is composed of the two bottom counters, plus the integer data (the votes) that was pushed on top before this. The snippet contains both the integer value of the state (minus points) and the dc code needed to apply it.

```
1r[1-]sX0>X1-+r1+r

```

I work with the following iterative algorithm (pseudo-code) to calculate the "positive question record":

```
result = 0
# main script: `0`
sum = 0
# main script: `d`
for each input question; do
# main script:`?`
    sum += 1
    # snippet: `1`
    sum -= v (0 if total votes are positive, 1 if negative)
    # snippet: `r[1-]sX0>X`
    sum -= minus_points (based on state)
    # snippet: `1-`, or `0-`, or `2-`
    result++
    # snippet: `r1+`
done
result = sum / result
# main script:`n47Pp`

```
> 8 votes

# Answer
# Jelly, 7 bytes

```
F<0S÷LC

```

**Try it online!**

Each entry in the input is a list of the vote count (an integer) and the status (a list). The status is a list of two integers, effectively a negated bit-flag:

```
open:             [ 0, 0]
closed:           [-1, 0]
deleted:          [ 0,-1]
closed & deleted: [-1,-1]

```

The tally of **(negativeQuestions + closed + deleted)** is then just the number of negative numbers and the final formula is then rearranged as **1-((negativeQuestions + closed + deleted)/totalQuestions)**:

```
F<0S÷LC - Main link: list as described above, d
F       - flatten d into a single list
 <0     - less than 0 (vectorises)
   S    - sum
     L  - length of d
    ÷   - divide
      C - complement (1 minus that)

```
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
˜0‹O¹g/(>

```

Try it online!

Uses Jonathan Allan's algorithm, so the inputs for the state are as follows:

```
open:             [ 0, 0]
closed:           [-1, 0]
deleted:          [ 0,-1]
closed & deleted: [-1,-1]
```
Explanation:
```
˜0‹O¹g/(> "The program."\
˜         "Deep-flatten the list."\
 0‹O      "Check how many numbers are negative."\
    ¹g    "Push the original list's length."\
      /   "Float-divide top two stack items."\
       (> "Push the complement of ToS."\
```
> 2 votes

# Answer
# Haskell, 70 57 bytes

13 bytes saved thanks to @Laikoni!

```
f=fromIntegral.length
v#s=(f v-(f.filter(<0))v+sum s)/f v

```

## Input format

2 lists of same length, the first containing the vote counts, the second containing the question statuses where open is 0, closed/deleted is -1 and closed+deleted ist -2.

## Readable

```
record :: [Int] -> [Int] -> Float
record v s = fromIntegral (length v - (length.filter(<0)) v + sum s)
           / (fromIntegral.length) v

```

## Explanation

Nothing special. Number of votes minus the number of negative questions plus the sum of the statuses, using the input format.

This solution gets inflated quite a bit because Haskell requires the arguments of a real divison to both be real numbers. In this case, they are Integers instead, so we have to call `fromIntegral` on them.
> 2 votes

# Answer
# Python 3, 42 bytes

```
lambda d:sum(1-s-(v<0)for v,s in d)/len(d)

```

Try it online!

---

**Input**: `[[votes, status],[votes, status],...]`

* open : 0
* closed : 1
* deleted : 1
* closed and deleted : 2

Example : `[[-1,0],[1,1],[0,2]]`
> 1 votes

# Answer
# Python 3, 35 bytes

```
lambda d:1-str(d).count('-')/len(d)

```

Unnamed function taking a list, `d`.

**Try it online!**

Each entry in `d` is a list of the vote count (an integer) and the status (a list). The status is a list of two integers, effectively a negated bit-flag:

```
open:             [ 0, 0]
closed:           [-1, 0]
deleted:          [ 0,-1]
closed & deleted: [-1,-1]

```

The tally of **(negativeQuestions + closed + deleted)** is then just the number of negative numbers, which is shortest to count by counting the hyphens in `d` cast to a string. The final formula is then rearranged as **1-((negativeQuestions + closed + deleted)/totalQuestions)**

---

### Python 2, 35 bytes

```
lambda d:1-1.*`d`.count('-')/len(d)

```

Same approach, but uses the `__repr__` shorthand ``...`` and multiplies by `1.` to cast the count to a float.
> 1 votes

# Answer
# Röda, 38 bytes

```
f a{[-#[a()|[0]for i if[i<0]]/#a*3+1]}

```

Try it online!

It's a function that takes one argument, an array, that has three values per each question: the vote count, close status and delete status. Statuses are either -1 (closed or deleted) or 0 (not closed or not deleted).

Explanation:

```
f a{[-#[a()|[0]for i if[i<0]]/#a*3+1]}
f a{                                 } /* function f with parameter a */
        a()|                           /* push values in a to the stream */
               for i                   /* for each value in the stream: */
                     if[i<0]           /*   if the value is negative: */
            [0]                        /*     push 0 to the stream */
    [                               ]  /* return: */
      #[                    ]          /*   number of values in the stream */
     -                                 /*   negated */
                             /#a*3     /*   divided by number of questions */
                                  +1   /*   plus 1 */

```

Example:

```
main {
    f([
        23, 0, 0,
        7, -1, 0,
        7, -1, 0,
        -1, 0, 0,
        -5, -1, -1,
        -11, 0, -1,
        -3, 0, -1,
        -3, -1, -1,
        -15, -1, -1
    ])
}

```
> 1 votes

# Answer
## JavaScript (ES6), ~~53~~ 46 bytes

```
a=>a.reduce((r,[v,s])=>r-(v<0)-s,l=a.length)/l

```

Takes the state as `0` for a closed NOR deleted question, `1` for a closed XOR deleted question, `2` for a closed AND deleted question.
> 0 votes

# Answer
# Octave, ~~45~~ ~~43~~ ~~42~~ 37 bytes

OP has just said in a comment that it's OK to take the state of questions on this format:

```
Open:              0
Closed:           -1
Deleted:          -1
Closed+Deleted:   -2

```

That makes the challenge quite a bit simpler:

```
@(v,s)(rows(v)-v<0-sum(s))/rows(v)

```

---

Old answer, from when the rules were a bit more strict.

```
@(v,s)((r=nnz(s))-nnz([v<0,s<100,s<99]))/r

```

This takes two variables as input, the votes, `v` and the state `s`, both as row vectors. It counts the number of rows, subtracts the total amount of negative votes, the number of close votes and the number of delete votes, then finally divides by the number of questions again.
> 0 votes

# Answer
# JS: 108 bytes

Note the first slice argument should be 1 if not running from a script. I figured that the scores don't need to be associated with each post since the effect stacks anyway.

Call by script:

`node code.js totalQs numOpen numClosed numDeleted score1 score2 ...`

The code:

`[t,o,c,d,...s]=process.argv.slice(2).map(v=>parseInt(v));console.log((t-c-d-s.reduce((c,v)=>v<0?c+1:c,0))/t)`

## Explanation needed?

`[a, ...b] = [1,2,3]` gives `a==1, b==[2,3]`

`process.argv.slice(2)` gets all the arguments except the first (path to node and script respectively).

`.map(v=>parseInt(v))` converts each element to a number. Hopefully nobody tries NaN inputs ;).

`s.reduce((c,v)=>v<0?c+1:c,0)` loops over `s` (scores) with a function taking the counter `c` and value `v`. If `v` (the score of any post) is `<0` then we `+1` our counter to get the number of negative posts.

`(t-c-d-numberNegative) / t` is the total, minus closed, minus deleted, minus negative, divided by total.
> 0 votes

# Answer
# Mathematica, 32 bytes

```
1-Count[#,a_/;a<0,∞]/Length@#&

```

Anonymous function. Takes a list of pairs of integers and states, where the states are translated from the problem output specification as shown below:

```
o: {0, 0}
c: {-1, 0}
d: {0, -1}
b: {-1, -1}

```

Returns a rational number as output. The Unicode character is U+221E INFINITY for `\[Infinity]`. The algorithm used is conceptually similar to those of other answers.
> 0 votes

# Answer
## Batch, 99 bytes

```
@set/ar=n=o=0,c=d=-1,b=-513
@for %%v in (%*)do @set/a"r+=%%v>>9,n+=1
@set/ar+=n/=2
@echo %r%/%n%

```

Takes input as a single list of votes (limited to ±500 per question) and statuses. Prints an unreduced fraction. 218 bytes to print using decimals:

```
@set/ar=n=o=0,c=d=-1,b=-513
@for %%v in (%*)do @set/a"r+=%%v>>9,n+=1
@set/a"n/=2,r=r*200000/n+200001,r+=r>>31,r>>=1
@if %r:-=% geq 100000 echo %r:~,-5%.%r:~-5%&exit/b
@set/a"r+=(r>>31|1)*1000000
@echo %r:~,-7%0.%r:~-5%

```
> 0 votes

---
Tags: code-golf, arithmetic, array
---


title: Shortest self-analyzing program

text:
# Question
Title: Shortest self-analyzing program
*Oh, `<PROGRAM NAME HERE>`, tell me how many character '`<CHARACTER HERE>`'/s are there in your body.*

---

I do not think it a dupe to this. That question asks for printing a list directly but this one requires some input that will cause problem.

Your work is to write a quine-like program/function that takes an input of one character, and respond with a number telling how many times that character occurs in your program. Comments, indents, trailing spaces, line feeds all count.

The range of acceptable input **MUST** cover all characters the language you are using can accept (not as string literals or comments) and all characters with lesser index in Unicode. For exmaple, Javascript and Python 3 accept Unicode characters for variable name, then it **MUST** allow Unicode input. For some stack processing languages, there are characters like `‘Ȯß`, so part of the non-ASCII input **MUST** also be acceptable.

For example, if your program is in pure ASCII and only LF

```
foo(bar,baz)#there is a space->
    do things

```

The inputs and outputs should be:

* \n -\> 1
* \r -\> 0
* \t -\> 0
* -\> 9
* `a` -\> 4
* `b` -\> 2
* `(` -\> 1
* `)` -\> 1
* \x01 through \x09 -\> 0
* (U+FF0B) -\> undefined behaviour (you can even destroy everything or delete the program itself furiously)

The program with least characters wins.

# Answer
> 0 votes
# Python, 172 chars

```
lambda a:'-mbda#l.fn()+1: \\\'i'.find(a)+1#\\\\\\\\\\\\\\((((((((())))))))))fffffffbd####lllll......nnnnnnnn+1+1+1+1+1+1+1+1+1+1+11:::::::::::::              '''''''''''''''iiiiiiiiiiiiiiiii

```

Using `str.find()+1` to generate 0 for any character not in program. Using comment for complement.

---
Tags: code-golf
---


# Question
Title: Converting rational numbers to an “alien” data format
For a story I'm writing, I needed to convert 101⅐ (101 + 1/7 if that doesn’t show up for you) into base 47.

Expressing an integer in some base brings back memories of first learning how to program back in the days of 8-bit systems; it’s a fairly easy exercise. Doing so using a floating-point format is a bit harder, though. The final twist, identifying the repeating digits, is more challenging to do elegantly.

So I thought I’d do it in a different language from what I’m used to, just for fun and learning the new dialect. And I thought it would be good to share, so here I am. The vast majority of the posts here are (char or byte of source) code golf, but I’m more interested in an elegant expression in the target language. Cyclomatic complexity isn’t a category, but is pretty close.

---

The program should take a *rational number* in a natural way, such as supplying three integers on the command line of the script invocation or standard input. This does not count towards the score (nor does the error checking and defaults if you give it one value only). The *function* (or part that is counted for score) should receive the three values; e.g. 101,1,7 for the example above.

The output is a sequence of code points that are transliterated into *text output* as follows:

* digits 0 through 9 inclusive: ‘0’ through ‘9’ in the normal way
* digits 10 through 46: express as ‘\[10\]’ through ‘\[46\]’
* negative sign: the normal ASCII ‘-’
* separator: ‘:’
* prefix: ‘#’

A number starts with the prefix ‘#’ and has up to three parts, separated by ‘:’. Leading parts are omitted if zero.

The basic natural number (BNN) is encoded using the digits in base 47, outputted in little-endian. That is, 99181 = 11×470 \+ 42×471 \+ 44×472 so the digits, in order output, are \[11\]\[42\]\[44\].

The last (possibly only) part of a number is an integer, which is a leading ‘-’ if the value is negative, followed by the digits of the BNN. So, 99181 would be encoded as `#[11][42][44]` and −99181 would be encoded as `#-[11][42][44]`.

The middle part, if needed, is an exponent as for scientific notation. It states which power of the base (position) is the first digit listed. In the case of integers, this is 470 so the 0-valued part is omitted.

Suppose you divide that by 47, shifting the radix point by one. That is, 99181 ÷ 47 is the same digits but starting with 47−1; that is, 11×47−1 \+ 42×470 \+ 44×471, and the output becomes `#-1:[11][42][44]`. There are two parts, the first is the encoding for the integer −1, and the second is the digits as before.

Now it comes out so neat only if you divide by some power of 47. Normally, a rational number made of small components will end up with a repeating sequence of digits. In decimal, for example, ⅓ is .3333… and ⅐ (1/7) is .142857142857142857… in the first case one digit repeats, in the second case 6 digits repeat.

In the alien real number format, the first part, if present, states how many digits are to be repeated. So, the number 8½ would have a single digit \[23\] repeating forever, so we just encode one of them and state that 1 repeats: `#1:-1:[23]8`. The first part is 1 (the encoded BNN for the value 1) which means that one digit is to be repeated. The second part (negative sign and BNN) indicates that the first digit given is the 47-1 position. The third part is the two digits needed: 26×47-1 \+ 8×470.

---

Somebody should check my results, but I think the correct output for (101 1 7) is:
`#6:-6:[20][13][40][26][33]672`.

# Answer
## Batch, 531 bytes

```
@echo off
set q=
set s=
set m=
if %1 lss 0 set m=-
set/ai=%m%%1,n=%2,d=%3,p=0
:i
set/ar=i%%47,i/=47
if %r% gtr 9 set r=[%r%]
set s=%s%%r%
if %i% gtr 0 goto i
:p
if %n%==0 goto n
set/ao=n,g=d%%47
if %g% gtr 0 goto g
set/ap+=1,d/=47,r=n/d,n%%=d
if %r% gtr 9 set r=[%r%]
set s=%r%%s%
goto p
:g
set/aq+=1,p+=1,r=n*47/d,n=n*47%%d
if %r% gtr 9 set r=[%r%]
set s=%r%%s%
if %n% neq %o% goto g
if %q% gtr 9 set q=[%q%]
set q=%q%:
:n
if %p% gtr 9 (set q=%q%-[%p%]:)else if %p% gtr 0 set q=%q%-%p%:
echo #%q%%m%%s%

```

Takes three parameters, whole number, numerator, denominator representing a mixed number in its lowest terms.
> 3 votes

---
Tags: base-conversion, atomic-code-golf
---


title: Verify the queens puzzle

text:
# Question
Title: Verify the queens puzzle
If you don't know what a queen is in chess, it doesn't matter much; it's just a name :)

Your input will be a *square* of arbitrary width and height containing some amount of queens. The input board will look like this (this board has a width and height of 8):

```
...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..

```

There are 8 queens on this board. If there were, say, 7, or 1, or 10 on here, the board wouldn't be valid.

Here we use a `.` for an empty space, and a `Q` for a queen. You may, alternatively, use any non-whitespace character you wish instead.

This input can be verified as valid, and you should print (or return) a truthy value (if it is was not valid, you should print (or return) a falsy value). It is valid because **no queen is in the same row, column, diagonal or anti-diagonal as another**.

## Examples (don't output things in brackets):

```
...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..

1

...Q.
Q....
.Q...
....Q
..Q..

0

Q.
Q.

0

..Q
...
.Q.

0 (this is 0 because there are only 2 queens on a 3x3 board)

..Q.
Q...
...Q
.Q..

1

Q

1 (this is valid, because the board is only 1x1, so there's no queen that can take another)

```

Let me stress that an input is only valid, if **no queen is in the same row, column, diagonal or anti-diagonal as another**.

### Rules

* You will never receive an empty input
* If the input contains fewer queens than the sqaure root of the area of the board, it is not valid.
* Note there are no valid solutions for a 2x2 or 3x3 board, but there is a solution for every other size *square* board, where the width and height is a natural number.
* The input may be in any reasonable format, as per PPCG rules
* The input will always be a sqaure
* I used 1 and 0 in the examples, but you may use any truthy or falsy values (such as `Why yes, sir, that is indeed the case` and `Why no, sir, that is not the case`)

As this is , the shortest code wins!

# Answer
> 7 votes
## Snails, 14 bytes

```
&
o.,\Q!(z.,\Q

```

Try it online!

Nothing like a 2D pattern matching language for a 2D decision problem. :)

### Explanation

The `&` on the first line is a match mode option which requires the pattern on the second line to match from every possible position in the input. If that's the case, the program prints `1`, otherwise it prints `0`.

As for the pattern itself, note that there's an implicit `)` at the end.

```
o       ,, Move in any orthogonal direction (up, down, left or right).
.,\Q    ,, Make sure that there's a Q somewhere in that direction from the
        ,, starting position of the match.
!(      ,, After finding the Q, make sure that the following part _doesn't_ match:
  z     ,,   Move in any orthogonal or diagonal direction.
  .,\Q  ,,   Try to find another Q in a straight line.
)

```

Why this works is easiest to see by starting from the negative lookahead: by ensuring that there is no `Q` in a straight line from the other `Q` we've already found, we make sure that there are no more than **N** queens (otherwise, there would have to be two in one row, and it wouldn't be possible to find these queens without finding another). Then the first part, making sure that there's a queen reachable in an orthogonal direction from any position, makes sure that there are exactly **N** queens. If one was missing, there would be a row and a column without a queen. Starting from the intersection of these, it wouldn't be possible to find a queen by going only in an orthogonal direction.

# Answer
> 6 votes
# Jelly, 17 or 15 bytes

```
ỴµUŒD;ŒD;ZVṀ;V=1Ṃ

```

Try it online!

Uses  for a queen and `¹` for blank space. (This is mostly a consequence of the ban on taking input as an array, because it forces the input to be strings; converting strings to integers is difficult in Jelly, with the easiest method being evaluation, and it turns out that instead of 1 and 0, using "add 1" () and "add 0" (`¹`) make it possible to omit several sum and map instructions, because we can count the queens in a list by evaluating it.) The truthy and falsey values are Jelly's normal `1` and `0`.

EDIT: The question's been changed since I wrote this answer to allow taking input as a matrix. This allows dropping the leading `Ỵµ`, saving 2 bytes. It also probably allows changing the input format to something more normal, using `S` to sum rather than `V` to evaluate, but I don't think that saves bytes and I kind-of like this funky format.

## Explanation

```
ỴµUŒD;ŒD;ZVṀ;V=1Ṃ
Ỵ                    Split on newlines.
 µ                   Set this value as the default for missing arguments.
     ;  ;            Concatenate the following three values:
  UŒD                - the antidiagonals;
      ŒD             - the diagonals;
         Z           - and the columns.
          V          Evaluate (i.e. count the queens on) all of those.
           Ṁ         Take the largest value among the results.
            ;V       Append the evaluation (i.e. queen count) of {each row}.
              =1     Compare each value to 1.
                Ṃ    Take the minimum (i.e. most falsey) result.

```

So the basic idea is that we ensure that there's at most one queen on each antidiagonal, diagonal, and column; and exactly one queen on each row. These conditions are together enough to require that there's at most one queen on each of the four sorts of line, and a number of queens equal to the side length of the board.

Incidentally, Jelly could probably do with a built-in for antidiagonals, but AFAICT it doesn't seem to have one, so I need to settle for reflecting the board and then taking the diagonals.

Another interesting note is that changing `=1Ṃ` to `E` (all equal) gives a generalized *n*-queens checker, which will also accept an *n*×*n* board where each row, column, diagonal, and antidiagonal contains no more than *k* queens, and the board contains exactly *kn* queens. Restricting *k* to equal 1 actually cost two bytes.

# Answer
> 5 votes
# Octave, ~~57~~ ~~70~~ ~~67~~ ~~51~~ 52 bytes

Saved 1 byte using `flip` instead of `rot90` thanks to @LuisMendo, but found a bug on the 1x1 case

```
@(A)all(sum([A A' (d=@spdiags)(A) d(flip(A))],1)==1)

```

Takes input as a binary matrix with 1 representing a Queen and 0 representing an empty space.

Creates an anonymous function that first concatenates the input matrix and its transpose.

`spdiags` creates a matrix with the same number of rows as the argument, with the diagonals turned into columns (zero-padded as necessary), so concatenate `spdiags` of the input matrix to get the diagonals and `spdiags` of the matrix flipped horizontally to get the antidiagonals.

Now take the sum of each column of the concatenated matrix and make sure each column is exactly 1.

Sample run on ideone.

# Answer
> 4 votes
# MATL, ~~38~~ 34 bytes

*4 bytes off thanks to @beaker!*

```
sG!sGt&n_w&:&XdsGP5M&Xdsv2<GnGzU=*

```

The input is a 2D array of zeros and ones, using semicolons as row separators.

This outputs a column vector of ones as truthy, and a column vector containing at least one zero as falsy.

Try it online! The footer code is an `if` branch to demonstrate truthiness or falsyhood.

Or verify all test cases.

### Explanation

```
s      % Input binary matrix implicitly. Sum of columns. Gives a row vector
G!     % Paste input again. Transpose
s      % Sum of columns (rows in the original matrix). Gives a row vector
G      % Paste input again
t&n    % Duplicate. Push number of rows and number of columns (will be equal)
_w     % Negate, flip
&:     % Binary range. Gives [-n -n+1 ... n] for input of size n×n
&Xd    % Get diagonals -n through n. This gives all diagonals as colums
s      % Sum of each column (diagonals of original matrix). Gives a row vector
GP     % Paste input again. Flip vertically
5M     % Push [-n -n+1 ... n] again
&Xd    % Get diagonals -n through n (anti-diagonals of original matrix)
s      % Sum of each column. Gives a row vector
v      % Concatenate everything into a column vector
2<     % True for elements that are less than 2
Gn     % Paste input again. Number of elements
Gz     % Paste input again. Number of nonzeros (i.e. of queens)
U      % Square
=      % True if equal
*      % Mutiply, element-wise

```

# Answer
> 3 votes
# SnakeEx, 67 bytes

```
m:({q<>}({q<R>}[{q<RF>}{n<RF>}].)*{e<>}<R>)%{4}
e:.$
q:_*Q_*$
n:_+$

```

Uses `_` in place of `.` in the input. Returns 1 or more matches for truthy, 0 matches for falsey. You can find an online interpreter at the link in the header.

### Explanation

SnakeEx is a language from the 2-D Pattern Matching challenge. It defines "snakes" that move around the grid matching stuff. Snakes can spawn other snakes, making the language quite powerful.

Let's look at this program from the bottom up.

```
n:_+$

```

This defines a snake `n` that matches 1 or more underscores and then the edge of the grid. Note that this may be in any of the 8 cardinal directions--the direction is determined when the snake is spawned.

```
q:_*Q_*$

```

Similar to `n` above, this defines `q` as a snake that matches any number of underscores, a single `Q`, any number of underscores, and the edge of the grid. In other words, a row/column/diagonal that has only one queen in it.

```
e:.$

```

`e` is a snake that matches one character and the edge of the grid.

```
m:({q<>}({q<R>}[{q<RF>}{n<RF>}].)*{e<>}<R>)%{4}

```

The main snake `m` uses these building blocks to check the whole board. Conceptually, it runs around the outside edges of the grid, spawning other snakes to check that all columns and rows have exactly one queen, and all diagonals have at most one queen. If any of the spawned snakes fails to match, the entire match fails. Let's break it down.

* `( )%{4}` runs what's inside the parentheses 4 times, once for each side. (In what follows, it's helpful to picture a particular side--say, the top edge of the grid, starting from the top left corner and moving right.)
* `{q<>}` spawns a `q` snake in the same direction that the main snake is moving. This verifies that the current edge meets the "exactly one queen" rule. Note that spawned snakes do not move the main snake's match pointer, so we're still at the beginning of the edge.
* `( )*` matches 0 or more of what's inside the parentheses.
* `{q<R>}` spawns a `q` snake turned rightward from the main snake's direction. (E.g. if the main snake is moving rightward along the top edge, this snake moves downward.) This checks each column/row.
* `[ ]` matches either one of the options inside the brackets:
    + `{q<RF>}` spawns a `q` snake turned 45 degrees rightward (i.e. `R`ight and `F`orward) from the main snake's direction. The `q` snake matches if the diagonal contains exactly one queen.
    + `{n<RF>}` spawns an `n` snake instead. The `n` snake matches if the diagonal contains no queens.
* `.` matches any character, moving the match pointer forward.
* After checking as many horizontals and diagonals as possible, we verify that we're at the edge by spawning `{e<>}`.
* Finally, `<R>` turns the main snake right, ready to match the next edge.

### Weird stuff

* There's nothing in the program to ensure that matching starts at an outside corner. In fact, the truthy test cases yield several matches, some of which start on the inside somewhere. Despite this, none of the falsey cases I've tried have generated any false positives.
* If I'm reading the language spec right, I should have been able to use `X` (branch in all diagonal directions) in place of `RF`. Unfortunately, the online interpreter said that was a syntax error. I also tried `*` (branch in all directions), but that hung the interpreter.
* Theoretically, something like `_*Q?_*$` ought to work for matching "at most one queen" in the diagonals, but that also hung the interpreter. My guess is that the possibility of empty matches causes problems.

# Answer
> 2 votes
# Python 3, ~~232~~ ~~200~~ 155 bytes

```
d=1
f=input()
Q=[]
for i in f:d=[0,d][i.count('Q')==1];Q+=[(len(Q),i.index('Q'))]
print[0,d][sum(k[1]==i[1]or sum(k)==sum(i)for k in Q for i in Q)==len(Q)]

```

Try it online!

-32 bytes thanks to @beaker noticing a change in the input specifications; I have changed the language from Python 3 to 2, thus allowing for me to use `input` to take input as an array of strings or an array of character arrays.

-45 bytes thanks to @Leaky Nun

# Answer
> 2 votes
# , 37 bytes

```
(+/&,=#)*1=[:>./+//.,+//.&|.,+/,+/&|:

```

Anonymous function train which takes Boolean matrix as argument.

Try it online!

`(` `+/` the sum `&` of `,` the ravel `=` equals `#` the tally of rows `)`

`*` and (lit. times)

`1` one `=` equals `[:` the `>./` maximum of

`+/` the sums `/.` diagonally `,` and (lit. catenated to)

`+/` the sums `/.` diagonally `&` of `|.` the reverse `,` and

`+/` the sums across `,` and

`+/` the sums `&` of `|:` the transpose

# Answer
> 2 votes
# Ruby, 120 bytes

Lambda function based on the original spec that required input as a string.

```
->s{t=k=0
a=[]
s.bytes{|i|i>65&&(a.map{|j|t&&=((k-j)**4).imag!=0};a<<k)
k=i<11?k.real+1:k+?i.to_c}
t&&~a.size**2>s.size}

```

converts the Q's into complex numbers and subtracts them from each other. If the difference between the coordinates of any two queens is horizontal, vertical or diagonal, raising it to the 4th power will yield a real number and the arrangement is invalid.

**Ungolfed in test program**

```
f=->s{                                 #Take input as string argument.
  t=k=0                                #k=coordinate of character. t=0 (truthy in ruby.)
  a=[]                                 #Empty array for storing coordinates.
  s.bytes{                             #Iterate through all characters as bytes.
    |i|i>65&&(                         #If alphabetical, compare the current value of k to the contents of a
      a.map{|j|t&&=((k-j)**4).imag!=0} #If k-j is horizontal, vertical or diagonal, (k-j)**4 will be real and t will be false
      a<<k)                            #Add the new value of k to the end of a.
    k=i<11?k.real+1:k+?i.to_c          #If not a newline, increment the imaginary part of k. If a newline, set imaginary to 0 and increment real
  }                                    #s.size should be a*a + a newlines. ~a.size = -1-a.size, so ~a.size**2 = (a.size+1)**2
t&&~a.size**2>s.size}                  #compare a.size with s.size and AND the result with t. Return value.

p f["...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q.."]

p f["...Q.
Q....
.Q...
....Q
..Q.."]

p f["Q.
Q."]

p f["..Q
...
.Q."]

p f["..Q.
Q...
...Q
.Q.."]

p f["Q"]

```

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

```
a=>!a.some((b,i)=>b.some((q,j)=>q&&h[i]|v[j]|d[i+j]|e[i-j]|!(h[i]=v[j]=d[i+j]=e[i-j]=1))|!h[i],h=[],v=[],d=[],e=[])

```

Ungolfed:

```
function queens(arr) {
    horiz = [];
    vert = [];
    diag = [];
    anti = [];
    for (i = 0; i < arr.length; i++) {
        for (j = 0; j < arr.length; j++) {
            if (arr[i][j]) { // if there is a queen...
                if (horiz[i]) return false; // not already on the same row
                if (vert[j]) return false; // or column
                if (diag[i + j]) return false; // or diagonal
                if (anti[i - j]) return false; // or antidiagonal
                horiz[i] = vert[j] = diag[i + j] = anti[i - j] = true; // mark it
            }
        }
        if (!horiz[i]) return false; // fail if no queen in this row
    }
    return true;
}

```

# Answer
> 0 votes
# Ruby, 155 bytes

```
->x{(y=x.map{|r|(i=r.index ?Q)==r.rindex(?Q)?i:p or-2}).zip(y.rotate).map.with_index{|n,i|n.max-n.min==1&&i<y.size-1?-2:n[0]}.inject(:+)*2==(s=x.size)*~-s}

```

This is horrible to read, so I've got a slightly less golfed version below

```
->x{
    (y=x.map{|r|(i=r.index ?Q)==r.rindex(?Q)?i:p or-2})
    .zip(y.rotate)
    .map.with_index{|n,i|n.max-n.min==1&&i<y.size-1?-2:n[0]}
    .inject(:+)*2==(s=x.size)*~-s
}

```

This is the same code, but with some newlines to separate out what's happening.

The code tself is an anonymous lambda function which takes an array of strings (`x`) in the format `["..Q", "Q..", ".Q."]`.

The first line is mapping each string to the index of the Q character in that string. If there is no Q character, it's replaced with -21. This new array of indices is assigned to the variable `y`.

The next line zips this array of indices with itself offset by one (rotated). This results in an array of pairs of consecutive indices.

The next line is particularly complicated. It goes through each of the pairs of indices, and subtracts the smaller from the larger. If this is 1 (and we're not at the last pair2), then there are two queens that are on the same diagonal, and a value of -2 is inserted, otherwise the original index of the queen in the string is inserted.

The last line sums up all the indexes for each and checks to see if it is the triangle number for n-1, where n is the width (or height) of the square.

1: -1 would have been my go-to, but it's 1 apart from 0, so would mess with the checking of diagonals. The negative-ness of it is important to make the final sum wrong. I thought about a high number (with single digits) like 9, but I can't be sure that won't result in an incorrect verification.
2: The board doesn't wrap round, whereas ruby's `rotate` array function does, and if the last pair is different by one it doesn't matter - that's not a diagonal.

# Answer
> 0 votes
# Python 3, ~~185~~ ~~176~~ ~~175~~ ~~172~~ 171 bytes

```
lambda x,c=lambda x:x.count("Q")==1:all([*map(c,x+[[l[i]for l in x]for i in range(len(x[0]))])])*~any(map(lambda s:"Q%sQ"%(s*".")in"".join(x),[len(x[0]),len(x[0])-2]))==-1

```

An anonymous function taking a list of strings as input.

Python 2, 175 bytes

```
lambda x:all([a.count("Q")==1for a in x]+[[l[i]for l in x].count("Q")==1for i in range(len(x[0]))]+[all(map(lambda s:"Q%sQ"%(s*".")not in"".join(x),[len(x[0]),len(x[0])-2]))])

```

# Answer
> 0 votes
# PHP, ~~137~~ 143 bytes

inspired by Neil´s solution

```
for($n=1+strlen($s=$argv[1])**.5|0;($c=$s[$p])&&!(Q==$c&&$v[$x=$p%$n]++|$h[$x=$p/$n]++|$d[$y-$x]++|$a[$y+$x]++);$p++);echo$n-1==count($a)&&!$c;

```

takes input from first command line argument; run with `-r`. Requires single byte line breaks.
Actually you can use any character but `0` for the line break.
prints true (`1`) or false (empty string).

**breakdown**

```
for($n=1+strlen($s=$argv[1])**.5|0; // copy input to $s, $n=size+1 (for the linebreak)
    ($c=$s[$p])&&!(                 // loop through characters
        Q==$c&&                         // if queen: test and increment lines
            $v[$x=$p%$n]++|$h[$x=$p/$n]++|$d[$y-$x]++|$a[$y+$x]++
    );                                  // break if a line had been marked before
    $p++);
echo$n-1==count($a)             // print result: true for $n-1(=size) marks
    &&!$c;                      // and loop has finished

```

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


# Question
Title: Solve an equation with (almost) any numbers you like
Given a string of the characters `+=-` where there is at least one `=`, insert positive integers between all the symbols and at the start and the end such that the math equations are satisfied.

For example, given the input

```
+-=-=

```

you need to insert positive integers A through F like this

```
A+B-C=D-E=F

```

such that the equations are all satisfied, i.e. `A + B - C` and `D - E` and `F` are all the same number.

There are many possible ways to do this since, as long as the equations work out, any set of positive integers may be used. Each line here is a possible valid output to input `+-=-=`:

```
2+3-4=6-5=1
1+1-1=2-1=1
4+2-4=4-2=2
100+1-10=182-91=91
89+231-77=1024-781=243

```

Note that the value of the expressions is not required to be a positive integer like the inserted numbers are. For example, given input `-=-` the outputs `1-10=8-17` (evals to -9) and `10-1=17-8` (evals to 9) are both equally valid. Of course for some inputs such as `=` it's impossible to have a negative as the expression since only positive numbers like `5=5` can be inserted.

Note also that zero is not a positive integer.

**The shortest code in bytes wins.**

You may output the numbers as a list instead of inserting them directly into the string. If you do output the string there may be spaces separating symbols and numbers. So, for input `+-=-=`, outputting

```
2, 3, 4, 6, 5, 1

```

or

```
2 + 3 - 4 = 6 - 5 = 1

```

is equivalent to outputting

```
2+3-4=6-5=1

```

## Test Cases

```
Input | One Possible Output
= | 1=1
== | 2=2=2
+= | 1+3=4
=+ | 2=1+1
-= | 30-10=20
=- | 1=2-1
=-= | 3=7-4=3
=+= | 2=1+1=2
=== | 100=100=100=100
+=- | 3+2=7-2
-=+ | 7-2=3+2
+=+ | 3+3=3+3
-=- | 1-10=8-17
--= | 60-1-1=58
++= | 60+1+1=62
-+= | 60-9+1=52
+-= | 60+9-1=68
+-=-= | 2+3-4=6-5=1
--=-- | 2-1-1=2-1-1
==-== | 47=47=50-3=47=47
=++=+-=-+=--= | 3=1+1+1=3+1-1=1-1+3=5-1-1=3
+--++-=-+-+- | 35+10-16-29+20+107-1000=5-4+3-2+1-876
====== | 8=8=8=8=8=8=8

```

# Answer
## Retina, 58 bytes

```
[-+]
$&1
\B((\+1)|(-1))*
$._$*1$#3$*1$#2$*_$&
+`1_

1+
$.&

```

Try it online!

Alternative solution at the same byte count:

```
((\+)|(-))*
$._$*1$#3$*1$#2$*_$&
+`1_

([+-])1*
$+1
1+
$.&

```

Try it online!

### Explanation

The basic idea is to turn all the `+`s and `-`s into simple `+1` and `-1` operations and then to prepend a sufficiently large number that makes all the equations work. To make the equations match, we can simply prepend the same number to each of them, and then reduce it by one for each `+1` and increase it by one for each `-1` after it. Since we'll be working with unary numbers, the only catch is that the first number needs to be large enough that we can reduce it by 1 enough times.

```
[-+]
$&1

```

We start by inserting a `1` after each `-` or `+`.

```
\B((\+1)|(-1))*
$._$*1$#3$*1$#2$*_$&

```

The `\B` ensures that these matches are either at the beginning of the input, or between a `=` and a `+` or `-`, i.e. all the positions where we want to insert the leading number of an expression. The `((\+1)|(-1))*` part then simply counts the number of `+1`s and `-1`s in groups `2` and `3` respectively. Now let's break down the substitution string:

```
$._$*1   # For each character in the current string, insert a 1. This is
         # an offset which is the same for each expression and is guaranteed
         # to be large enough that all subsequent +1s can be cancelled.
$#3$*1   # For each -1, insert a 1.
$#2$*_   # For each +1, insert a _.
$&       # Re-insert the string of +1s and -1s.

```

```
+`1_

```

Repeatedly drop `1_` from the string, applying the required cancellation from the `+1`s.

```
1+
$.&

```

Finally, replace all the strings of `1`s with their lengths to convert from unary to decimal.
> 16 votes

# Answer
# Python 2, 76 bytes

```
lambda e:sum([[len(e+s)-2*s.count('+')]+[1]*len(s)for s in e.split('=')],[])

```

Try it online!
> 8 votes

# Answer
# Python 2, ~~199~~ ~~179~~ ~~178~~ ~~172~~ ~~162~~ ~~158~~ ~~156~~ ~~152~~ 151 bytes

Way too long, but the solution was easy to create.

```
from itertools import*
i=input()
k='%s'
s=k+k.join(i)+k
for p in product(*[range(1,65537)]*-~len(i)):
    if eval((s%p).replace('=','==')):print s%p;break

```

**Try it online**

This will try every possibility until it finds a solution. The program is extremely slow. It also performs the string replacement every iteration. The "172" edit made it *drastically* slower, since rather than starting with a small range it starts at the max. For example, the inputs `-=` or `=+` have to try 2\**32 attempts before reaching a solution.

To speed up the program, use the version with 178 bytes from the edit history.
> 6 votes

# Answer
# Python 2, ~~120~~ 119 bytes

<sup>-1 byte thanks to mbomb007</sup>

```
a=['1'+(n and('1'.join(n)+'1'))for n in input().split('=')]
print'='.join(`max(map(eval,a))-eval(c)+1`+c[1:]for c in a)

```

Try it online! or Verify all test cases

First I insert `1` in every position, to check the highest value, then add it as offset on every equation. This work because you can't add negative numbers, so the minimum result is given by the amount of `+` in the equation that only have `+`.
> 5 votes

# Answer
# JavaScript (ES6), ~~92~~ 82 bytes

*Golfed 8 bytes with a trick from @xnor*

```
let f =
x=>x.split`=`.map(q=>(x+q).length-2*~-q.split`+`.length+[...q,''].join(1)).join`=`
```

```
<input oninput="if(/^[+=-]+$/.test(value))O.innerHTML=f(value)" value="="><br>
<pre id=O>1=1</pre>
```

The trick here is to insert a `1` after every `+` or `-`, then prepend to each expression the number that makes the expression equal the length of the input. This way we can guarantee that the number is always positive; since there's always at least 1 `=` in the string, the number of `+`s can never reach the length of the string, so the remainder is always at least `1`. You can verify this by typing in an arbitrary number of `+`s in the snippet above.
> 5 votes

# Answer
# GNU Prolog, 156 bytes

```
x(L,R,V)-->{E#>0},({L=[E|R],E=V};x(L,[E|R],X),("+",{V#=X+E};"-",{V#=X-E})).
q(L,R,V)-->x(L,T,V),({T=R};"=",q(T,R,V)).
s(Q,L):-q(L,[],_,Q,[]),fd_labeling(L).

```

## Explanation

We've got a bunch of equations to solve, so why not use an actual equation solver?

`x` is basically an equation evaluator for equations of the form `+-+`; in addition to the equation itself, it has two additional arguments (a difference list `L,R` that contains the values of the equation, and a value `V` that the equation evaluates to). As usual in Prolog, it can be used any way round (e.g. you can specify `V` and get an `L,R`, specify `L,R` and get a `V`, specify both and verify that the value is correct, or specify neither in which case appropriate constraints will be placed on both `V` and `L,R`). The "current element" of `L,R` is named `E`, and we also include an assertion that `E` is greater than 0 (because the question requires the use of positive numbers). This function is slightly more verbose than I'd like, e.g. I had to write the `[E|R]` pattern match/unmatch twice, due to the fact that lists are right-associative but addition and subtraction are left-associative. Sadly, we need to use an actual list, rather than inventing our own left-associative list type out of cons cells, for `fd_labeling` to work.

`q` is similar to `x`, but also includes `=`. It basically just calls `x`, and itself recursively. Incidentally, it's a very clear demonstration of how difference lists work, showing that you can concatenate two difference lists `L,T` and `T,R` into a single difference list `L,R`. The basic idea is that a difference list is a partial function that takes an argument `R` and returns a value `L` which is `R` with the list itself prepended to it. Thus, by identifying the argument of one difference list and the return value of another, we can compose the functions, and thus concatenate the lists.

Finally, `s`, which is the funciton that actually solves the task in the question, is a wrapper function that calls `q` with arguments. We convert the difference list to a regular list by supplying `[]` as its argument, and use `fd_labeling` to find a solution to the equation we built up. (By default, it appears to like setting values to 1 if there's no reason to set them to something else. However, it can be configured; `value_method(random)` gives more "interesting" solutions than putting 1s everywhere, for example, and is still very fast.)

## Sample output

With the program as written:

```
| ?- s("=++=+-=-+=--=", V).

V = [3,1,1,1,3,1,1,3,1,1,5,1,1,3] ?

```

If I make the program a bit longer to add a `value_method(random)`, the outcome varies, but looks something like this:

```
| ?- s("=++=+-=-+=--=", V).

V = [68,6,12,50,85,114,131,45,3,26,71,1,2,68] ?

```

In both cases, the `?` at the end of the output means that there may be more than one solution. (Of course, in this case, we know that there's a *lot* more than one solution!)
> 5 votes

# Answer
# Mathematica, 116 bytes

```
Join@@(Prepend[#^2,1-Min[Tr/@c]+Tr@#]&/@(c=Characters@StringSplit["0"<>#<>"0","="]/."+"->-1/."-"->1/."0"->Nothing))&

```

Pure function taking a string as input and returning a list of positive integers. Basic strategy: we only ever add 1 and subtract 1, and we choose the initial numbers in each expression to make everything equal.

`c=Characters@StringSplit[#,"="]/."+"->-1/."-"->1` would split the input string at every equals sign, then replace each `+` by `-1` and each `-` by `1`. However, if there's an equals sign at the beginning or end, then it would get ignored. Therefore we artificially add a new character at each end (`"0"<>#<>"0"`) and make it go away after the string-splitting is complete (`/."0"->Nothing`).

The total of each sublist now equals an integer that we can put in front of the `+`s and `-`s to make each expression equal. `1-Min[Tr/@c]` is the smallest integer that we can add to each total to make them all positive. So `Prepend[#^2,1-Min[Tr/@c]+Tr@#]&` takes each sublist (the `^2` turns all their entries to `1`) and prepends its total shifted by this smallest compensating integer. The resulting lists are `Join`ed together to produce the output.
> 4 votes

# Answer
# PHP, ~~207~~ ~~204~~ ~~197~~ 114 bytes

direct approach: much shorter and faster

```
foreach(explode("=",$argn)as$t)echo"="[!$c],strlen($argn)+($c=count_chars($t))[45]-$c[43],@chunk_split($t,!!$t,1);

```

Run with `echo '<input>' | php -nR '<code>'` or test it online.

**breakdown**

```
foreach(explode("=",$argn)as$t) // loop through terms
    echo                            // print ...
        "="[!$c],                       // 1. "=" if not first term
        strlen($argn)                   // 2. maximum number
            +($c=count_chars($t))[45]   //    + number of "-"
            -$c[43],                    //    - number of "+"
        @chunk_split($t,!!$t,1);        // 3. each operator followed by "1"

```
* `!$c` is true in the first iteration, cast to `1` for string indexing; `"="[1]` is empty.
After that, `$c` is set and `!$c` false, cast to `0` and `"="[0]` is the first character.
* The maximum value for any term needs not exceed the number of pluses +1;
so we´re definitely safe with the length of the input. All terms will evaluate to that.
* `chunk_split($s,$n,$i)` inserts `$i` after every `$n` characters of `$s` \- and at the end.
To prevent empty terms turning to `1`, an error is forced by setting the chunk length to `0`.
> 3 votes

# Answer
# Ruby, 76

```
->s{(?1+s.gsub(/./){|a|a+?1}).split(?=).map{|e|e[0]="#{5**8-eval(e)}";e}*?=}

```

The target value for the expressions is fixed at `5**8` minus 1 for golfing reasons! Originally I was using `s.size+1` minus 1.

**Ungolfed in test program**

```
f=->s{(?1+s.gsub(/./){|a|a+?1}).           #add a 1 at the beginning and after every symbol
       split(?=).                          #split into an array of expressions at = signs
       map{|e|                             #for each expression string
         e[0]="#{5**8-eval(e)}";e          #change the first number to 5**8-eval(e)
       }*?=                                #and rejoin the strings
}

puts f["="]
puts f["=="]
puts f["+="]
puts f["=+"]
puts f["-="]
puts f["=-"]
puts f["=-="]
puts f["=+="]
puts f["==="]
puts f["+=-"]
puts f["-=+"]
puts f["+=+"]
puts f["-=-"]
puts f["--="]
puts f["++="]
puts f["-+="]
puts f["+-="]
puts f["+-=-="]
puts f["--=--"]
puts f["==-=="]
puts f["=++=+-=-+=--="]
puts f["+--++-=-+-+-"]
puts f["======"]

```

**Output**

```
390624=390624
390624=390624=390624
390623+1=390624
390624=390623+1
390625-1=390624
390624=390625-1
390624=390625-1=390624
390624=390623+1=390624
390624=390624=390624=390624
390623+1=390625-1
390625-1=390623+1
390623+1=390623+1
390625-1=390625-1
390626-1-1=390624
390622+1+1=390624
390624-1+1=390624
390624+1-1=390624
390624+1-1=390625-1=390624
390626-1-1=390626-1-1
390624=390624=390625-1=390624=390624
390624=390622+1+1=390624+1-1=390624-1+1=390626-1-1=390624
390624+1-1-1+1+1-1=390625-1+1-1+1-1
390624=390624=390624=390624=390624=390624=390624

```
> 3 votes

# Answer
# Röda, ~~112~~ ~~110~~ 109 bytes

```
f x{[(`:$x:`/"=")()|{|p|p~=":",""a=p;a~=`\+`,""b=p;b~="-","";["=",#x-#b+#a];{(p/"")|{|o|[o,"1"*#o]}_}}_][1:]}

```

Try it online!

The split function did not work as I intended with this program. For example, `split("", sep="")` returns one empty string instead of nothing. How is that logical? Due to this the program is nearly 20 bytes larger than what it could be if the split semantics were ideal.

The idea of this answer is that we know that the length of the input string must be greater or equal to the value of the equation, so we define the value of the equation to be the length of the string. For every part of the equation, we think every operator being `+1` or `-1` and subtract and add them to value of the equation.

Ungolfed:

```
function f(x) {
    /* Adds ":"s around the string to prevent "=" being split wrong. */
    [split(`:$x:`, sep="=") | for p do
        p ~= ":", ""          /* Removes colons. */
        a := p; b := p        /* Initializes a and b to be p. */
        a ~= "\\+", ""        /* The lengths of a and are now equal to the */
        b ~= "-", ""          /* numbers of "-" and "+" characters in x. */
        push("=", #x-#b+#a)   /* Prints "=" and the value of the equation */
                              /* minus number of "+"s plus number of "-"s. */
        split(p, sep="") | for o do /* For each operator: */
            push(o)                 /* Prints the operator. */
            push(1) if [o != ""]    /* Prints 1 unless the operator is "". */
        done
    done][1:] /* Removes the first character of the output ("="). */
}

```
> 1 votes

---
Tags: code-golf, math, arithmetic, integer, expression-building
---


title: Pali-n-drome this List

text:
# Question
Title: Pali-n-drome this List
The challenge here is to extend an implementation of palindrome given the following as inputs:

* `n > 1` and a list `l`.

Your program must palindrome the list both vertically and horizontally, that is to say it must first palindrome the list itself, then each element in the list after; or the other way around. Before palindromization, all elements are ensured to be equal length. The palindrome action is then to be performed `n` times in sequence until the desired output is met. The easiest way to show the expected outputs is just to run through a few examples:

---

One iteration performed on `[123,456,789]`:

First you palindromize the list to `[123,456,789,456,123]`.

* While this is not a palindrome if joined together, it is a palindrome in terms of the list.
* `[a,b,c]` became `[a,b,c,b,a]`, so the LIST was palindromized.

Then, you palindromize each list element `[12321,45654,78987,45654,12321]`.

This is how each iteration is performed, it's essentially an omnidirectional palindrome.

---

Given `n=1 and l=[123,456,789]`:

```
12321
45654
78987
45654
12321

```

Given `n=2 and l=[123,456,789]`

```
123212321
456545654
789878987
456545654
123212321
456545654
789878987
456545654
123212321

```

Given `n=1 and l=[3,2,1]`:

```
3
2
1
2
3

```

Given `n=2 and l=["hat","mad"," a "]`:

```
hatahatah
madamadam
 a a a a
madamadam
hatahatah
madamadam
 a a a a
madamadam
hatahatah

```

Given `n=2 and l=[" 3 ","2000"," 100"]`:

```
 3   3 3   3
2000002000002
100 00100 001
2000002000002
 3   3 3   3
2000002000002
100 00100 001
2000002000002
 3   3 3   3

```

Given `n=4 and l=["3 ","20","1 "]`:

```
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3

```

Given `n=3 and l=["_|__","__|_","___|"]`:

```
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_

```

Given `n=2 and l=["---|---","__|","___|","____|"]`:

```
---|-----|-----|-----|---
  __|   |__   __|   |__
 ___|   |___ ___|   |___
 ____| |____ ____| |____
 ___|   |___ ___|   |___
  __|   |__   __|   |__
---|-----|-----|-----|---
  __|   |__   __|   |__
 ___|   |___ ___|   |___
 ____| |____ ____| |____
 ___|   |___ ___|   |___
  __|   |__   __|   |__
---|-----|-----|-----|---

```

# Rules

* `n` will always be greater than 1.
* `l` will always have more than 1 element.
* All elements of `l` are the same length.
* This is shortest solution will be marked as winner.

# Answer
# 05AB1E, 4 bytes

Note that if only a single iteration was required (`n=1`), then the program would be the palindrome `û€û`.

```
Fû€û

```

**Try it online**

```
F       Do n times
 û      Palindromize the list
  €û    Palindromize each element in the list

```

---

If padding the input was still a required part of the program (11 bytes):

```
€R.B€RIFû€û

```

I couldn't find a shorter way to right-justify. Left-justification and centering were all easy, but this was longer for some reason. Using `E` or `²` instead of `I` also works.
> 9 votes

# Answer
# Python 2, ~~71~~ 63 bytes

```
lambda x,n,f=lambda x:x+x[-2::-1]:eval('f(map(f,'*n+`x`+'))'*n)

```

Try it online!

Assign a palindrome function to `f`, generate and evaluate the following pattern (for `n=4`)
`f(map(f,f(map(f,f(map(f,f(map(f,<input>))))))))`
> 7 votes

# Answer
# Jelly, 6 bytes

```
ŒḄŒB$¡

```

Dyadic link, or full program taking the list and `n`.

**Try it online!**

Using both versions of Lynn's fantastic built-in "bounce".

```
ŒḄŒB$¡ - Main link: l, n
     ¡ - repeat n times
    $  -     last two links as a monad (firstly with l then the result...)
ŒḄ     -         bounce ("palindromise") the list
  ŒB   -         bounce the elements

```
> 6 votes

# Answer
# Python 2, 64 bytes

```
h=lambda a:a+a[-2::-1]
f=lambda a,n:n and f(h(map(h,a)),n-1)or a

```

**Try it online!** \- footer prints each of the elements of the resulting list, one per line, a "pretty print".

`h` is the palindomisation function, it appends to the input, all the elements of a list from the last but one, index -2, to the start in steps of size -1.

`f` calls `h` with the result of calling `h` on each element in turn, reduces `n` by one and calls itself until `n` reaches 0, at which point `a` is the finished product.
> 5 votes

# Answer
# APL, 15 bytes

```
(Z¨Z←⊢,1↓⌽)⍣⎕⊢⎕

```

Explanation:

* `(`...`)⍣⎕⊢⎕`: read the list and `N` as input, and run `N` times:
    + `⊢,1↓⌽`: the list, followed by the tail of the reversed list
    + `Z←`: store this function in `Z`
    + : and apply it to each element of the list as well

Test:

```
          (Z¨Z←⊢,1↓⌽)⍣⎕⊢⎕
    ⎕:
          'hat' 'mad' ' a '
    ⎕:
          2
    ┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
    │hatahatah│madamadam│ a a a a │madamadam│hatahatah│madamadam│ a a a a │madamadam│hatahatah│
    └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘

```
> 2 votes

# Answer
# Groovy, 66 bytes

```
{x,n->f={z->z+z[z.size()-2..0]};n.times{x=f(x).collect{f(it)}};x}

```
> 1 votes

# Answer
## Haskell, 51 bytes

```
x%n=iterate((++)<*>reverse.init)x!!n
x?n=(%n)<$>x%n

```

Usage example: `["123","456","789"] ? 1` -\> `["12321","45654","78987","45654","12321"]`. Try it online!.

`(++)<*>reverse.init` makes a palindrome out of a list, `iterate(...)x` repeats this again and again and collects the intermediate results in a list, `!!n` picks the nth element of this list. `(%n)<$>x%n` makes a n-palindrom of each element of the n-palindrome of `x`.
> 1 votes

# Answer
## JavaScript (ES6), 87 bytes

```
f=(n,l,r=l=>[...a].reverse().slice(1))=>n--?f(l.concat(r(l)).map(s=>s+r(s).join``),n):l

```
> 1 votes

# Answer
# Pip, 25 bytes

24 bytes of code, +1 for `-l` flag.

```
Lq{gM:_.@>RV_gAL:@>RVg}g

```

Takes the list as command-line arguments and the number *n* from stdin. Try it online!

### Explanation

```
                          g is list of cmdline args (implicit)
Lq{                   }   Read a line of input and loop that many times:
      _.@>RV_             Lambda function: take all but the first character (@>) of the
                           reverse (RV) of the argument (_), and concatenate that (.) to
                           the argument (_)
   gM:                    Map this function to g and assign the result back to g
                 @>RVg    Take all but the first element of the reverse of g
             gAL:         Append that list to g and assign the result back to g
                       g  After the loop, print g (each item on its own line due to -l)

```
> 1 votes

---
Tags: code-golf
---


title: CSV cleanup: remove all in col after (

text:
# Question
Title: CSV cleanup: remove all in col after (
### Problem

Given a file with:

```
56 (65%), 33(75%), , 44, "“hello”,(5) world", goodbye
89 (25%), 33(75%), , 44, "hello world", goodbye
92 (97%), 33(75%), , 44, "hello world", goodbye

```

### Goal

Write back to that file with:

```
56, 33, , 44, "“hello”,(5) world", goodbye
89, 33, , 44, "hello world", goodbye
92, 33, , 44, "hello world", goodbye

```

### Example implementation \[Python 518 bytes\]

```
import csv
from sys import argv
from itertools import takewhile, imap

with open(argv[1], 'r+') as f0:
    r = csv.reader(f0, delimiter=',', quotechar='"')
    w = csv.writer(f0, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    rows = tuple(imap(lambda line: ''.join(
        '{}\0'.format(''.join(
            takewhile(lambda ch: ch != '(', col))).rstrip() for col in line), r))
    f0.seek(0)
    tuple(imap(lambda line: w.writerow(line.split('\0')), rows))

```

# Answer
**Perl: 15 Bytes +1 for -p option**

```
s/ ?\([^,"]+//g

```

**Usage:**

```
perl -pe 's/ ?\([^,"]+//g' file.csv

```
> 1 votes

---
Tags: code-golf, string, sequence, parsing, subsequence
---


title: Random subset generator

text:
# Question
Title: Random subset generator
Randomly choose one out of `k`-length, ordered subset of characters in a string, while only storing a limited number of characters. The subset must be chosen with equal probability and may contain repeated characters. Do this without generating all possible permutations and assume k is at most the length of the string. For example, the string `daddy` has 7 subsets of length two: `da`, `dd`, `dy`, `ad`, `ay`, `yd`, `ya`. The function should return any one of them with the probability of `1/7`.

# Answer
# Pyth - 5 bytes

While we're arguing about the nomenclature, I'm just guessing at the rules based on the example to just mean pick one from all unique permutations of length `n` of the string.

```
O{.PF

```

Try it online here.
> 1 votes

# Answer
# Perl 6,  ~~75~~  71 bytes

```
{set(flat $^a.comb.combinations($^b).map: *.permutations.map: *.join).pick}

```

Try it

```
{set($^a.comb.combinations($^b).map: |*.permutations.map: *.join).pick}

```

Try it

## Expanded:

```
{
  set(                         # get the unique values from: (equal probability)

    $^a.comb.combinations($^b) # get the combinations
      .map: |*.permutations    # get the permutations of the combinations
        .map: *.join           # join each permutation into a string

  ).pick                       # pick one
}

```

---

The following could almost work except that it has a different probability if there are any repeats of characters.

```
{$^a.comb.pick($^b).join}

```
> 0 votes

---
Tags: code-golf, random, probability-theory
---


# Question
Title: Create every combination of variable groups up to order n
**SPECIFICATION**

Given `m` variables, create every combination up to order `n`. For example,

The output of mapping two variables (`a` and `b`) to order `1` would be:

* a
* b
* a b

The output of mapping two variables (`a` and `b`) to order `2` would be:

* a
* a2
* b
* b2
* a b
* a2 b
* a b2
* a2 b2

The output of mapping two variables (`a` and `b`) to order `3` would be:

* a
* a2
* a3
* b
* b2
* b3
* a b
* a2 b
* a3 b
* a3 b2
* a b2
* a b3
* a2 b3
* a2 b2
* a3 b3

The output of mapping three variables (`a`, `b`, and `c`) to order `1` would be:

* a
* b
* c
* a b
* b c
* a c
* a b c

The output of mapping `m` variables to order `n` would be:

* etc.

**WINNING CRITERIA**

Output every possible combination as outlined above. Order does not matter. Where in your code you print to the screen does not matter. All that matters is that what shows up in your output is correct.

# Answer
# Brachylog, 6 bytes

```
j₎o⊇ᵘb

```

Takes input as a couple, containing the list of variables and the order. Output is a list of lists of variables, where powers are represented by repeated variables. (e.g. "a²b" is \["a","a","b"\])

Try it online!

`j₎` joins the first input with itself as many times as stated by the second input. `o` orders the list obtained, and then `⊇ᵘ` finds all unique subsets of that ordered list. Finally, we remove the first element with `b`, since this will always be the empty answer, which is not contemplated by the challenge.
> 4 votes

# Answer
# LATEX, 354 bytes

When I saw this I knew it had to be done in Latex. Equations just look so crisp and clean in Latex and I can't stand using `^` for power.

```
\documentclass{article}\input tikz\usepackage{intcalc}\usepackage{ifthen}\begin{document}\typein[\a]{}\typein[\b]{}\foreach\x in{1,...,\intcalcPow{\b+1}{\a}}{\begin{equation}\foreach[count=\i]\y in{a,...,z}{\ifthenelse{\(\i<\a\)\OR\(\i=\a\)}{\y^\intcalcDiv{\intcalcMod{\x}{\intcalcPow{\b+1}{\i}}}{\intcalcPow{\b+1}{\i-1}}}{}}\end{equation}}\end{document}

```

## Explanation

There are three main forces at work here `\typein` which is what allows us to take input from the command line, the `intcalc` package which is what allows us to make calculations with our variables, and the Latex`equation` environment.

---

Once we have taken in input we begin a loop we loop `\intcalcPow{\b+1}{\a}` times, once for each result we want to print. Each loop we begin an `equation` environment and loop through the alphabet keeping track of `\y` for the current letter and `\i` for the current number of runs. If `\i` is greater than or equal to `\a` we don't print anything at all (according to the specs this is not strictly necessary however Latex will overflow for values greater than 1 if we don't do this). We then print `\y` to our equation and raise it to the power of

```
\intcalcDiv{\intcalcMod{\x}{\intcalcPow{\b+1}{\i}}}{\intcalcPow{\b+1}{\i-1}}

```

That whole mess simply means take the `\i`th digit of `\x` in base `\b+1`. This ensures that the powers are decoded properly.

### Example output:

Here is the output for 3, 2
> 14 votes

# Answer
# Mathematica, ~~51~~ 50 bytes

```
Rest[1##&@@@PowerRange[1,#^#2,#]~Distribute~List]&

```

Assumes "given `m` variables" means the first input is a list of variables.

**If first input is an integer, 69 bytes**

```
Rest[1##&@@@PowerRange[v=Unique[]~Table~#;1,v^#2,v]~Distribute~List]&

```

The variables are in the form `$<integer>` (e.g. `$5`)
> 5 votes

# Answer
## Haskell, ~~71~~ ~~58~~ ~~54~~ 53 bytes

```
n#m=tail$concat<$>mapM(\x->(\i->x<$[1..i])<$>[0..n])m

```

Returns a list of strings and uses the output format `"aabbb"` for `"a^2 b^3"`.

Usage example: `3 # "ab"` -\> `["b","bb","bbb","a","ab","abb","abbb","aa","aab","aabb","aabbb","aaa","aaab","aaabb","aaabbb"]`. Try it online!.

Many bytes are spent for output formatting. A more flexible output, e.g. pairs of (variable, power) -\> `[('a',2),('b',3),('c',1)]` for `"a^2 b^3 c^1"` would save a lot.

How it works

```
    mapM(\x->    )m      -- for each variable x in the input list m
      \i->x<$[1..i]      -- make i copies of x
             <$>[0..n]   -- for all numbers from 0 to n
                         -- in fact mapM makes all possible combinations hereof, i.e.
                         -- [["",""], ["", "b"], ["", "bb"] ... ["a",""], ["a","b"], ...]
  concat<$>              -- join all inner lists
                         --    e.g ["aa","bbb"]  -> "aabbb"
tail                     -- drop the first (all powers = ^0)

```

With maximum flexibility, i.e. output format as (variable, power) pairs and including all-zero powers (`"a^0 b^0 c^0"`) it boils down to

### Haskell, 25 bytes:

```
f n=mapM((<$>[0..n]).(,))

```

Usage example: `f 2 "ab"`:

```
[[('a',0),('b',0)],
 [('a',0),('b',1)],
 [('a',0),('b',2)],
 [('a',1),('b',0)],
 [('a',1),('b',1)],
 [('a',1),('b',2)],
 [('a',2),('b',0)],
 [('a',2),('b',1)],
 [('a',2),('b',2)]]

```

Dropping all-zero powers costs 5 bytes for a total of 30: `f n=tail.mapM((<$>[0..n]).(,))`.
> 4 votes

# Answer
# Jelly, ~~20~~ 17 bytes

```
ṗj€“”Ṣ€
ŒPçÐ€j“”Q

```

A dyadic link (function) that accepts a list of variable names\* and the maximal order (an integer) and returns a list where each entry is a fully expanded representation of the multiplication (e.g. **foo0bar3bof2** would be `['bar', 'bar', 'bar', 'bof', 'bof']`.

* the variable names may be a string of unique characters (strings become lists of characters).

**Try it online!** \- the footer calls the link as a dyad and then separates the resulting list of lists by line feeds and each entry by spaces for ease of reading.

*Note:* includes the **0** order (empty product) a dequeue, , may be inserted here `...ŒPḊç...` to avoid that.

### How?

```
ṗj€“”Ṣ€ - Link 1, sorted results of a Cartesian power: elements, power
ṗ       - Cartesian power of elements with given power
 j€“”   - join €ach with "" (flatten each by one level)
     Ṣ€ - sort €ach

ŒPçÐ€j“”Q - Main link: variableNames, maximalOrder
ŒP        - power-set of variableNames (e.g for ['a','b','c'] this would be ['','a','b','c','ab','ac','bc','abc'])
   Ð€     - for €ach mapped over right argument (i.e. over the range [1,2,...,maximalOrder])
  ç       -     call the last link (1) as a dyad (i.e. power-set results are the elements and one of the range values is the power)
     j“”  - join with "" (flatten by one level)
        Q - unique values

```

---

13 byte version that will only work for a single string of unique characters (or a list of unique characters):

```
ŒPṗÐ€j“”F€Ṣ€Q

```

try it
> 4 votes

# Answer
# Mathematica 100 bytes

Surely there is a more efficient way to accomplish this!

Two variables to order 4:

```
(Times@@@(MapThread[Power,#]&/@Outer[List,{Alphabet[][[1;;#]]},Rest@Tuples[Range[0,#2],#],1][[1]])) &

```
> 3 votes

# Answer
# Bash + sed, 60

A different, shorter approach to my previous answer.

Input as command-line parameters - `m` is given as a comma-separated list of variable names, and `n` as an integer:

```
p=eval\ printf
$p -vc %s {$1}^\\{0..$2}
$p '%s\\n' $c|sed 1d

```

Try it online.

---

Previous Answer:

# Bash + coreutils, 91

Welcome to eval-escape-brace hell. Sometimes shell-script really gives just the right tool for the job. This is **not** the case here, but it works.

Input as command-line parameters - `m` is given as a comma-separated list of variable names, and `n` as an integer. Output is written out longhand - e.g. `a^2` is actually written `aa`. This is acceptable as per this comment.

```
p=eval\ printf
$p -vc {%$[$2-1]s}
$p '%s\\n' $($p %s \{{$1}${c// /,}\\\,})|tr -d {}|sort -u

```

There may be shorter ways to do this.

Try it online.

# Explanation

* `printf -vc {%$[$2-1]s}` assigns the variable `c` to a string like `{ }`, where the number of spaces is the order `n` \- 1, so if `n` = 1, the result is `{}`, if `n` = 2, the result is `{ }`, etc.
* `${a[$1]}` uses `m` as an index to the array `a`, so if `m` is 3, then the result is `c`
* `\{{a..${a[$1]}}${c// /,}\\,}` is a multi-part brace expansion:
    + `\{` \- a literal `{`
    + `{$1}` is a is the brace expansion of the list `m`, e.g. `{a,b,c}` or `a b c`
    + `${c// /,}` replaces the spaces in `$c` with commas, e.g. `{,,}` for `n` = 3, which is also a brace expansion which effectively repeats each element of `{a..c}` `n` times
    + `\\\,}` \- a literal `,}`
* So for `m` = "a,b" and `n` = 2, this expands to `{a,} {a,} {b,} {b,}`
* The inner `printf` removes the spaces to give `{a,}{a,}{b,}{b,}`, which itself is a brace expansion
* This expands to `aabb aab aab aa abb ab ab a abb ab ab a bb b b`
* The outer `printf` puts each of these elements on its own line
* `sort -u` removes the duplicates
* The `tr -d {}` is there to handle the case when `n` = 1. In this case the variable `c` will be `{}` which is not a brace expansion, but instead the literal characters are inserted. The `tr` removes them.

`eval`s and `\` escapes are placed *very* carefully to ensure that all the expansions occur in the necessary order.
> 3 votes

# Answer
## JavaScript (ES proposal), 142 bytes

```
f=
(v,n)=>[...Array(++v**n)].map((_,i)=>i.toString(v).padStart(n,0).replace(/./g,(c,j)=>(+c?(10+j).toString(36):``)+(c>1?c.sup():``))).join`<br>`
```

```
<div oninput=o.innerHTML=f(v.value,n.value)><input id=v type=number min=1 value=1><input id=n type=number min=1 value=1><span id=o><br>a
```

Requires a browser with both `**` and `padStart` support, so try Firefox 52 or Chrome 57.
> 3 votes

# Answer
# Röda, ~~49~~ ~~48~~ 46 bytes

```
f n{r=[""]{|v|r=r...[seq(0,n)|[v.._]]}_;r[1:]}

```

Try it online!

I think it is correct. It doesn't use any separator between a variable and its order. The previous version used `!`, but I realized that it isn't strictly required.

Explained:

```
function f(n) {
    r := [""] /* r is a list with one empty string. */
    /* Loops over the variable names in the stream. */
    for var do
        /* Concatenates every element in r to */
        /* every element in the list that contains orders of */
        /* variable var. */
        r = r...[
            push(var..x) for x in [seq(0, n)]
        ]
    done
    r[1:] /* Return elements of r not counting the first. */
}

```
> 3 votes

# Answer
# Python, 112 bytes

```
import itertools as t
f=lambda n,v:[''.join(map(str.__mul__,v,I))for I in t.product(range(n),repeat=len(v))][1:]

```

Usage:

```
for x in f(3, 'ab'):
    print(x)

```

Output:

```
b
bb
a
ab
abb
aa
aab
aabb

```

Nicer format in **115 bytes**:

```
import itertools as t
f=lambda n,v:[''.join(map('{}^{}'.format,v,I))for I in t.product(range(n),repeat=len(v))][1:]

```

Output (same usage):

```
a^0b^1
a^0b^2
a^1b^0
a^1b^1
a^1b^2
a^2b^0
a^2b^1
a^2b^2

```

Even nicer in **125 bytes**:

```
import itertools as t
f=lambda n,v:[''.join(c+'^%s'%i for c,i in zip(v,I)if i)for I in t.product(range(n),repeat=len(v))][1:]

```

Output:

```
b^1
b^2
a^1
a^1b^1
a^1b^2
a^2
a^2b^1
a^2b^2

```

The last 4 bytes (`[1:]`) in all are for removing the empty product.

These work in both Python 2 and 3.
> 1 votes

# Answer
# C++14, ~~146~~ 140 bytes

-6 byte for simpler output format.

Unnamed lambda, assuming input `s` like `std::string` and `o` as `std::ostream`:

```
[](auto s,int n,auto&o){int l=s.size(),k,c,*p=new int[l]{1};while(!c){for(c=1,k=0;k<l;o<<s[k]<<"^"<<p[k],p[k++]*=!(c=(p[k]+=c)>n));o<<" ";}}

```

Usage and explanation:

```
#include<iostream>
#include<string>

auto f=
[](auto s, int n, auto&o){
 int l=s.size(),              //string length
     k,                       //running variable for l
     c,                       //carry for the increment
    *p=new int[l]{1};         //init array with first elem 1
 while(!c){                   //if carry was leftover, break
  for(
   k=0,c=1;                   //always start with carry
   k<l;
    o<<s[k]<<"^"<<p[k],       //output
    p[k++]*=!(c=(p[k]+=c)>n)
//               p[k]+=c      //inc p[k]
//            c=(p[k]+=c)>n   //if value is greater than order
//  p[k++]*=!(c=(p[k]+=c)>n)  //set p[k] to 0 and inc k
  );
  o<<" ";
 }
}
;

main(){
 f(std::string("ab"),3,std::cout);
 std::cout << "\n";
 f(std::string("abc"),2,std::cout);
}

```

Output:

```
a^1b^0 a^2b^0 a^3b^0 a^0b^1 a^1b^1 a^2b^1 a^3b^1 a^0b^2 a^1b^2 a^2b^2 a^3b^2 a^0b^3 a^1b^3 a^2b^3 a^3b^3
a^1b^0c^0 a^0b^1c^0 a^1b^1c^0 a^0b^0c^1 a^1b^0c^1 a^0b^1c^1 a^1b^1c^1

```
> 0 votes

---
Tags: code-golf, arithmetic
---