title: Lists and arrays, part by part

text:
# Question
Title: Lists and arrays, part by part
In this challenge, you'll get four different but somewhat related tasks that must be solved in a specific manner. First, I'll explain the tasks, then follows an explanation of how you must solve it.

Your code should for all four tasks take two positive integers as input: `n,m`, where `n<m`. All tasks must be solved in the same language. The orientation of matrices are optional (n-by-m may be interpreted as "n rows, m columns", or "n columns, m rows").

### Task 1:

Create (and output/print) a vector / list consisting of the elements: `n, n+1 ... m-1, m`. So, for `n=4, m=9`, you should output: `4,5,6,7,8,9`.

### Task 2:

Create (and output/print) a matrix / array / list of lists (or equivalent) looking like this:

```
n,   n+1, ... m-1, m
n+1, n+2, ... m-1, m+1
...
n+m, n+m+1, ... 2*m-1, 2*m

```

For `n=4, m=9` you should output:

```
4, 5, 6, 7, 8, 9
5, 6, 7, 8, 9, 10
...
13, 14, 15, 16, 17, 18

```

### Task 3:

Create (and output/print) an n-by-m multiplication table (on any suitable format). Example for `n=4, m=9`:

```
1   2   3  4
2   4   6  8
3   6   9  12
4   8  12  16
5  10  15  20
6  12  18  24
7  14  21  28
8  16  24  32
9  18  27  36

```

### Task 4:

Output / print a vector / list consisting of the elements in the multiplication table from task 3, sorted in ascending order, keeping duplicate values. For `n=4, m=9`, you should output: `1, 2, 2, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 12, 12, 12, 14, 15, 16, 16, 18, 18, 20, 21, 24, 24, 27, 28, 32, 36`.

# The challenge:

Now, all the tasks above are quite trivial. The real challenge here is that the code for task 2 must start with the code for task 1, the code for task 3 must start with the code for task 2 and the code for task 4 must start with the code for task 3.

**To make it more clear:**

Suppose the code for **Task 1** is (works in Octave):

```
@(n,m)(n:m)

```

Then your code for **Task 2** could be (works in Octave):

```
@(n,m)(n:m)+(0:m)'

```

The code for task **Task 3** must be (doesn't work in Octave):

```
@(n,m)(n:m)+(0:m)'"Code_for_task_3"

```

And finally, the code for **Task 4** must be (doesn't work in Octave):

```
@(n,m)(n:m)+(0:m)'"Code_for_task_3""Code_for_task_4"

```

---

This is , so the submission with the shortest code for task 4 in each language wins. As always: Explanations are highly encouraged.

# Answer
# Jelly, 12 bytes

### Task 1

```
r

```

Try it online!

### Task 2

```
r+þ0r$}

```

Try it online!

### Task 3

```
r+þ0r$}
×þ

```

Try it online!

### Task 4

```
r+þ0r$}
×þFṢ

```

Try it online!

## How it works

### Task 1

`r` is the *dyadic range* atom and does exactly what the task asks for.

### Task 2

A dyadic chain that begins with three dyadic links is a *fork*; the outmost links get evaluated first, then the middle link is called with the results to both sides as arguments.

* `r` behaves as before, yielding **\[n, …, m\]**.
* `0r$}` is a quicklink (or quickquicklink, if you will).

The quick `$` (monadich chain) consumes the links `0` (yield **0**) and `r` (dyadic range) and turns them into a monadic chain. When called with argument **k**, this will yield **\[0, …, k\]**.

The quick `}` (right argument) takes the quicklink created by `$` and turns it into a *dyadic* link that calls `0r$` with `0r$}`'s right argument.

`0r$}` will be called with left argument **n** and right argument **m**, so `0r$` is alled with argument **m** and yields **\[0, …, m\]**.
* is another quicklink. `þ` (table) will call `+` (addition) for every element in its left argument and any element in its right argument, grouping the results for each right argument into a single row.

will be called with left argument **\[n, …, m\]** and right argument **\[0, …, m\]**, yielding the desired table.

### Task 3

Every line in a Jelly program defines a different link. The last one is the *main link* and, like C's `main` function, is the only link that is executed by default. The remaining links can be called from the main link, but we won't do this here.

As before, `þ` (table) will call `×` (addition) for every element in its left argument and any element in its right argument, grouping the results for each right argument into a single row.

Since both arguments to `×þ` are integers, `þ` casts them to ranges, transforming the arguments **n** and **m** into **\[1, …, n\]** and **\[1, …, m\]**.

### Task 4

`×þ` works as before. The following links are monadic, making them *atops*, i.e., they are applied on top of the previous ones.

After executing `×þ`, `F` flattens the resulting 2D array, and  sorts the resulting 1D array.
> 6 votes

# Answer
# 05AB1E, ~~18~~ 17 bytes

**Task 1**

```
Ÿ

```

Try it online

**Task 2**

```
Ÿ²FD>})

```

Try it online

**Task 3**

```
Ÿ²FD>})v¹LN*})¦

```

Try it online

**Task 4**

```
Ÿ²FD>})v¹LN*})¦˜{

```

Try it online

## Explanations

**Task 1**

```
Ÿ     # range[n ... m]

```

**Task 2**

```
Ÿ        # range[n ... m]
 ²F      # m times do:
   D     # duplicate
    >    # increment
     }   # end loop
      )  # wrap in list

```

**Task 3**

```
v          # for each list in result of Task 2 do
 ¹L        # push range[1 ... n]
   N*      # multiply by index
     }     # end loop
      )    # wrap in list
       ¦   # discard first element

```

**Task 4**

```
˜          # flatten the result from Task 3
 {         # sort

```
> 5 votes

# Answer
# MATL, ~~18~~ 17 bytes

### Task 1

```
&:

```

Try it online!

### Task 2

```
&:O2G:h!+

```

Try it online!

### Task 3

```
&:O2G:h!+:7M!*

```

Try it online!

### Task 4

```
&:O2G:h!+:7M!*1eS

```

Try it online!

## Explanation

### Task 1

```
&:    % Binary range [n n+1 ... m] from implicit inputs n, m

```

### Task 2

```
      % ... Stack contains [n n+1 ... m]
O     % Push 0
2G    % Push second input, m
:     % Unary range: gives [1 2 ... m]
h     % Concatenate horizontally: gives [0 1 2 ... m]
!     % Transpose into a column vector
+     % Add with broadcast

```

### Task 3

```
      % ... Stack contains matrix from task 2
:     % Unary range. For matrix input it uses its (1,1) entry. So this gives [1 2 ... n]
7M    % Push [1 2 ... m] again
!     % Transpose into a column vector
*     % Multiply with broadcast

```

### Task 4

```
      % ... Stack contains matrix from task 3
1e    % Linearize into a row vector
S     % Sort

```
> 3 votes

# Answer
## Mathematica, 84 77 bytes

*Edit: Thanks to Martin Ender for saving 7 bytes.*

**Task 1:**

```
{n,m}n~Range~m

```

Pure `Function` with arguments `n` and `m` which outputs `n~Range~m`, the infix form of `Range[n,m]`.

**Task 2:**

```
{n,m}n~Range~m~Table~(m+1)//0~Range~m+#&

```

`n~Range~m~Table~(m+1)` creates a 2D array with `m+1` rows, where each row is the output of the previous task. Then `//0~Range~m+#&` is postfix application of the function `0~Range~m+#&` which effectively adds `0` to the first row, `1` to the second row, and so on up to `m` for the `m+1`-th row.

**Task 3:**

```
{n,m}n~Range~m~Table~(m+1)//0~Range~m+#&//1##&~Array~{n,m}&

```

This just applies the constant function `1##&~Array~{n,m}&` to the output of the previous task.

**Task 4:**

```
{n,m}n~Range~m~Table~(m+1)//0~Range~m+#&//1##&~Array~{n,m}&//Flatten//Sort

```

`Flatten`s and `Sort`s the multiplication table.
> 3 votes

# Answer
# Python, 183 bytes

**Task 1, 29 bytes**

```
r=range
a=lambda n,m:r(n,m+1)

```

Try it online!

**Task 2, 84 bytes**

```
r=range
a=lambda n,m:r(n,m+1)
s=lambda n,m:[[w+i for w in r(n,m)] for i in a(0,m+1)]

```

Try it online!

**Task 3, 137 bytes**

```
r=range
a=lambda n,m:r(n,m+1)
s=lambda n,m:[[w+i for w in r(n,m)] for i in a(0,m+1)]
d=lambda n,m:[[w*i for w in a(1,n)] for i in a(1,m)]

```

Try it online!

**Task 4, ~~183~~167 bytes**

```
r=range
a=lambda n,m:r(n,m+1)
s=lambda n,m:[[w+i for w in r(n,m)] for i in a(0,m+1)]
d=lambda n,m:[[w*i for w in a(1,n)] for i in a(1,m)]
f=lambda(z):sorted(sum(z,[]))

```

Try it online!

## Explanation:

**Task 1:**

Simple enough, it generates a `n` to `m` list using Python's built-in `range` function.

**Task 2:**

For every number `0` to `m+1`, it adds that number to each item of a list from `n` to `m`.

**Task 3:**

For each number from `1` to `m`, it multiplies that number by every number in a list from `1` to `n`.

**Task 4:**

This uses Python's built in `sorted` function which sorts a list from least to greatest. The list comprehension in the function is used to flatten the list. It creates a list of every item in every item of the list given to it by task 3.

* Saved very many bytes thanks to @math\_junkie.
* Saved 16 bytes thanks to @ThisGuy

Saved very many bytes thanks to @math\_junkie.
> 2 votes

# Answer
# PHP 7, 200 bytes

Uses the output buffer to clear previous output.

### Task 1

```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');

```

Saves the code in `$s` to reuse it later. The `$v` variable is for the last task.

### Task 2

```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');for(;++$i<=$m;)eval($s);

```

Prints the remaining lines.

### Task 3

```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');for(;++$i<=$m;)eval($s);for(($c=ob_clean)();++$j<=$m;print"
")for(;++$$j<=$n;sort($v))echo$v[]=$j*$$j,' ';

```

Clears the output buffer and prints the multiplication table, saving the numbers to `$v`.

### Task 4

```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');for(;++$i<=$m;)eval($s);for(($c=ob_clean)();++$j<=$m;print"
")for(;++$$j<=$n;sort($v))echo$v[]=$j*$$j,' ';$c();eval($s);

```

Clears the output buffer again and prints `$v`.
> 2 votes

# Answer
# PowerShell, 126 bytes

### Task 1

```
param($n,$m)$n..$m

```

Try it online!

Uses the `..` built-in range operator. The default behavior for the implied `Write-Output` inserts a newline between elements, so that's why the output shows as newline separated.

---

### Task 2

```
param($n,$m)$n..$m>2;0..$m|%{$i=$_;($n..$m|%{$_+$i})-join','}

```

Try it online!

Dumps the first task to STDERR with `>2;`, then loops from `0` to `$m`, each iteration setting helper `$i` before looping again from `$n` to `$m` and incrementing each number by `$i`. Those are `-join`ed together with commas, else this would be an ambiguous gigantic long one-element-per-line output.

---

### Task 3

```
param($n,$m)$n..$m>2;0..$m|%{$i=$_;($n..$m|%{$_+$i})-join','}>2;(1..$m|%{$i=$_;(1..$n|%{$_*$i})-join' '})

```

Try it online!

Same sort of thing `>2;` to dump the previous to STDERR. Then we simply double-loop from `1` to `$m` then `1` to `$n`, setting helper `$i` along the way, multiply the values, and `-join` with a space to make it tabular. Note the encapsulating parens -- they'll come into play on the next task -- but here they just ensure that the output is put onto the pipeline (which it already would be, so they're redundant).

---

### Task 4

```
param($n,$m)$n..$m>2;0..$m|%{$i=$_;($n..$m|%{$_+$i})-join','}>2;(1..$m|%{$i=$_;(1..$n|%{$_*$i})-join' '})-split' '|%{+$_}|sort

```

Try it online!

Aha! Finally some redundancy. Since the previous task has parens, we can tack on the `-split` on whitespace without worry, cast each one to an integer `|%{+$_}`, and then `|sort`. The output is again newline separated.

---

I *think* there are some ways to better leverage the redundancy between tasks -- still golfing it some.
> 1 votes

# Answer
# ES2016-ish, 401 384 chars

Here's a first try. I'm sure it could be condensed a bit, but it's pretty short. Arrow functions FTW! (Love those implicit return statements.) New and improved with template strings!

### Task 1

```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `)

```

Call `z(n,m)` for the log output. (I'm aliasing console.log for later golfing.)

### Task 2

Second verse... expands on the first.

```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `),p,o,g=(n,m)=>{p=n,o=m;return [...a(m+1).keys()].map((d)=>f(d+p,d+o))},y=(n,m)=>l(g(n,m).join`\n`

```

Now call `y(n,m)`. Pretty, no?

### Task 3

Have to bypass most of the existing functionality `<sadface />`.

```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `),p,o,g=(n,m)=>{p=n,o=m;return [...a(m+1).keys()].map((d)=>f(d+p,d+o))},y=(n,m)=>l(g(n,m).join`\n`,h=(n,m)=>[...a(m).keys()].map((d)=>(d+1)*n).join`\t`,i=(n,m)=>[...a(n).keys()].map((d)=>h((d+1),m)),v=(n,m)=>i(n,m).join`\n`

```

Now the method name is `v`. Call it the same way.

### Task 4

And now we can reuse again.

```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `),p,o,g=(n,m)=>{p=n,o=m;return [...a(m+1).keys()].map((d)=>f(d+p,d+o))},y=(n,m)=>l(g(n,m).join`\n`,h=(n,m)=>[...a(m).keys()].map((d)=>(d+1)*n).join`\t`,i=(n,m)=>[...a(n).keys()].map((d)=>h((d+1),m)),v=(n,m)=>i(n,m).join`\n`,t=(n,m)=>l(v(n,m).match(/\d+/g).sort((a,b)=>+a>+b||+(a===b)*2-1).join(`, `)

```

Had to skip `u` for my method, so it's `t`. Bummed that I had to put in that sort function, because the `String.match` returns values as... strings.
> 1 votes

# Answer
# Ruby, ~~121~~ 103 bytes

Everything in Ruby is truthy except for `nil` and `false`, which means that the tasks can be set up to ignore previous input with naught but a well-placed `and`/`&&`.

**Task 1**

Try it online!

```
n,m=$*.map &:to_i
p [*n..m]

```

**Task 2**

Try it online!

```
n,m=$*.map &:to_i
p [*n..m]&&(0..m).map{|i|[*n+i..m+i]}

```

**Task 3**

Try it online!

```
n,m=$*.map &:to_i
p [*n..m]&&(0..m).map{|i|[*n+i..m+i]}&&(1..m).map{|i|(1..n).map{|j|i*j}}

```

**Task 4**

Try it online!

```
n,m=$*.map &:to_i
p [*n..m]&&(0..m).map{|i|[*n+i..m+i]}&&(1..m).map{|i|(1..n).map{|j|i*j}}.flatten.sort

```
> 0 votes

---
Tags: code-golf, number, matrix, multiple-holes
---


title: Predict the Bomb's Landing Point!

text:
# Question
Title: Predict the Bomb's Landing Point!
# Introduction

It was just a normal day, here at your military base. Suddenly, you looked up to see a bomb falling down from the sky! You need to create a program to predict where it will fall, and tell you the location.

# Challenge

You will be given a bomb in the form of `Start-X Start-Y X-velocity Y-velocity`. You can assume that they will all be positive integers. 0 is a valid input only for `Start-x` and `Start-y`. The bomb starts with x `Start-x`, and y `Start-y`. Each "frame" (no graphical output required), the bomb will move `x-velocity` units right, then `y-velocity` units down. Continue doing this until the bomb reaches y of 0 or below. Then, output what it's x was when it hit the ground.

# Test Cases

1

Input:`0 10 2 2`

Output:`10`

2

Input:`5 4 3 2`

Output:`11`

3

Input:`11,8,7,3`

Output:`32`

This is , so shortest answer in bytes wins!

# Answer
# 05AB1E, 9 bytes

```
¹³²(I÷(*+

```

Try online
> 1 votes

# Answer
# JavaScript, ~~29~~ 28 bytes

Thanks @user5090812 for golfing off 1 byte

```
(a,b,x,y)=>a+x*((b+y-1)/y|0)

```

Try it online!

If it did not have to move x then y but was instead falling in a straight line it would be 18 bytes

```
(a,b,x,y)=>a+x*b/y

```
> 1 votes

# Answer
# TI-Basic, 21 bytes

```
Input :Prompt A,B:X+A+Aint(Y/B-E~9

```

If the ceiling function did not have to be implemented, it would be more straightforward at 13 bytes:

```
Input :Prompt A,B:X+AY/B

```
> 1 votes

# Answer
# Python, ~~45~~ 28 Bytes

```
lambda a,b,x,y:a+x*-(-b//y)

```

Try it online!
> 1 votes

# Answer
# Scheme ~~40~~ 36 Bytes

```
λ(x y u v)(+ x(* u(ceiling(/ y v))))

```
> 1 votes

# Answer
# Haskell, 21 bytes

```
(a#b)x y=a-x*div(-b)y

```

The trivial answer: defines an operator that takes 4 arguments and then uses the formula.

Could probably be golfed more.

EDIT: Yep, Ørjan Johansen points out we can use `a-x*div b(-y)`, which brings us to 22 bytes. Try it online!

At this point, the code is really more other people than mine, so I'm going to mark this answer community wiki. Feel free to golf this further if you want :)
> 1 votes

# Answer
# C#, 46 bytes

```
(a,b,c,d)=>a+c*(int)Math.Ceiling((double)b/d);

```
> 0 votes

# Answer
# Ruby, 21 bytes

```
->x,y,v,w{x-v*(y/-w)}

```
> 0 votes

# Answer
# Java 7, 66 bytes

```
int f(int a,int b,int x,int y){return a+x*(int)Math.ceil(1f*b/y);}

```
> 0 votes

---
Tags: code-golf, physics
---


title: "Monitorize" an Image

text:
# Question
Title: "Monitorize" an Image
**The Problem:**

This challenge comes from a real problem I was having. I have a dual monitor setup at work, and I wanted to use the following image as my wallpaper:

However, my monitors have quite significant bezels, and when I set my background, it looks something like this, where the pier appears (appiers?) to be broken:

I was able to solve this by making an image with the center cut out of it, and then stretching it back to the original size, as in the image below:

---

**The Challenge:**

Write a program that takes in an image and "monitorizes" it for use with a dual monitor setup (i.e. deletes the center section of the image, where the bezels are). The rules are as follows:

1. It must be a full program that accepts the image, either as a path (string argument, etc), or in the form of a file chooser dialog.
2. The program must take as an input the number of vertical lines (one pixel in width) to crop out from the center of the image
3. The cropping must come from the center (width-wise) of the original image
4. The resultant image must be re-scaled back to the original size of the input image. (Either the halves can be scaled individually, and then concatenated, or concatenated and then scaled. Scaling individually produces a better image/effect, but is hardly noticeable in the real world)
5. Background images are generally even, so to make this challenge easier, input images will only have an even number of pixels, and number of lines to remove will only be even as well.
6. This challenge is code golf - shortest code in bytes wins

**Good Luck!**

# Answer
> 1 votes
## Octave, 85 bytes

```
@(f,n)imsave(imresize((o=imread(f))(:,[1:(end-n)/2,(end+n)/2:end],:),size(o)(1:2)),f)

```

Defines an anonymous function with `f` the file name, and `n` the number of columns to remove. Since an anonymous function requires a single expression, inline assignment is used, a feature not present in MATLAB.

### MATLAB, 98 bytes

As a bonus, I also golfed a MATLAB compatible answer. Interestingly, this is only 13 bytes longer, since the Octave version needs a lot of parentheses to correctly parse the inline assignments.

```
function  m(f,n)
o=imread(f);imsave(imresize(o(:,[1:(end-n)/2,(end+n)/2:end],:),size(o(:,:,1))),f)

```

# Answer
> 5 votes
## Matlab 2013, 150 bytes

Here is my attempt in Matlab. Definitely won't be the shortest code, but it's a start.

Warning, this overwrites the original image, so make a copy first.

**Golfed Version**

```
function  mi(f,n)
o=imread(f);
s=size(o);
imwrite([imresize(o(:,1:((s(2)-n)/2),:),[s(1),s(2)/2]) imresize(o(:,((s(2)+n)/2):end,:),[s(1),s(2)/2])], f);
end

```

---

**Ungolfed Code, with improvements for odd image sizes and odd number of columns**

```
function  monitorizeImage( filename, num_columns )

orig = imread(filename);
orig_size = size(orig);

f = factor(orig_size(2));
origsize_iseven = f(1)==2;

f = factor(num_columns);
num_columns_iseven = f(1)==2;

odd_even_size_mismatch = xor(origsize_iseven,num_columns_iseven);

img_resized = imresize(orig,[orig_size(1) orig_size(2)+odd_even_size_mismatch]);

leftimg = img_resized(:,1:((orig_size(2)+odd_even_size_mismatch-num_columns)/2),:);
leftimg = imresize(leftimg,[orig_size(1),floor(orig_size(2)/2)]);
rightimg = img_resized(:,((orig_size(2)-odd_even_size_mismatch+num_columns)/2):end,:);
rightimg = imresize(rightimg,[orig_size(1),floor(orig_size(2)/2)]);

monitorized_image = [leftimg rightimg];
monitorized_image = imresize(monitorized_image,[orig_size(1),orig_size(2)+ ~origsize_iseven]);

[~, ~, ext] = fileparts(filename);

imwrite(monitorized_image,strcat(filename(1:end-length(ext)),'_',num2str(num_columns),ext));

end

```

# Answer
> 3 votes
# Wolfram Language, ~~134~~, ~~127~~, ~~119~~ 111 bytes

```
f[i_,c_]:=(d=ImageDimensions@i;ImageAssemble[ImageTake[i,a=All,#]&/@{{0,e=-#&@@d/2-c/2},{-e,a}}]~ImageResize~d)

```

Creates a function `f` that takes an image as the first input (as a symbol in Mathematica or the Wolfram Cloud), and an integer as the second input.

**Ungolfed**:

```
f[image_,columns_]:=(  (*Define Function*)
    d=ImageDimensions[image];  (*Get image dimensions*)
    e=d[[1]]/2+columns/2;  (*Add half the image width to half the number of removed columns*)
    ImageResize[ImageAssemble[Map[ImageTake[i,All,#]&,{{0,-e},{e,All}}]],d]  (*Map the function onto a list with the desired column ranges and merge and scale the resulting image*)
)

```

~~Technically, it won't work properly if either of the image dimensions exceed 362,880 pixels, but I assume that's okay, since that is way outside the scope of the problem (and some computers).~~ Fixed!

# Answer
> 2 votes
# PHP, 206 bytes

```
($c=imagecopyresized)($t=imagecreatetruecolor($w=imagesx($s=imagecreatefrompng($argv[1])),$h=imagesy($s)),$s,0,0,0,0,$v=$w/2,$h,$x=$v-$argv[2]/2,$h);$c($t,$s,$v,0,$w-$x,0,$v,$h,$x,$h);imagepng($t,$argv[3]);

```

takes three command line arguments: source file name, number of lines to crop and target filename. Run with `-r`.

You may want to use `imagecopyresampled` instead of `imagecopyresized` (+2 bytes) for a better result.

**ungolfed**

```
$s=imagecreatefrompng($argv[1]);    # load source image
$w=imagesx($s);$h=imagesy($s);      # get image dimensions
$t=imagecreatetruecolor($w,$h);     # create target image
$v=$w/2;                            # $v = half width
$x=$v-$argv[2]/2;                   # $x = width of remaining halves
                                    # resize and copy halves:
imagecopyresized($t,$s, 0,0,    0,0,$v,$h,$x,$h);
imagecopyresized($t,$s,$v,0,$w-$x,0,$v,$h,$x,$h);
imagepng($t,$argv[3]);              # save target image

```

I could save 9 more bytes by sending the PNG result to STDOUT ... but what for?

---
Tags: code-golf, image-processing
---


title: Straight Line to Text

text:
# Question
Title: Straight Line to Text
**Input:**

2 numbers, x and y.

**Output:**

Output a text block where x is the width of the text block and y is the height of the text block. Then there will be a straight line going from the top left to the bottom right and to show it, there should be a # where the line should cross.

The # should be generated using the straight line equation, `y = mx + c` where m is the gradient of the line which can be retrieved through making `m` as `y` divided by `x`. `x` is the current line index. `c` is the height intercept and can be found by multiplying the gradient by the `x` value and adding the `y` value. So, in short, it would be `(y/x) * lineIndex + (y/x * x + h)`. This would all be rounded to the nearest position in the current line.

**Rules:**

* there can only be 1 # per line
* it has to be in the form of a string/whatever the equivalent in your language of choice. This has to be able to cover multiple lines as well.
* in text block, after the # there does not need to be more spaces. Just initial ones to offset the #

**Examples:**

(don't mind the `|`, they are where the lines start and stop)

Where x is 9 and y is 1:

```
|        #|

```

Where x is 1 and y is 5:

```
|#|
|#|
|#|
|#|
|#|

```

where x is 9 and y is 5:

```
| #       |
|   #     |
|    #    |
|      #  |
|        #|

```

where x is 5 and y is 9:

```
|#    |
|#    |
| #   |
| #   |
|  #  |
|  #  |
|   # |
|   # |
|    #|

```

where x is 9 and y is 2:

```
|   #     |
|        #|

```

where x is 9 and y is 3:

```
|  #      |
|     #   |
|        #|

```

Edit: More detail in the output. Added 3rd rule. Added 5th and 6th example

Edit2: Fixed errors in the given examples (Sorry!). Revised over the output to make it much clearer v. sorry for any confusion :S

# Answer
# C, ~~74~~ 70 bytes

*Thanks to @Johan du Toit for saving 4 bytes!*

```
i;f(x,y){for(i=y;i--;)printf("%*c\n",(int)round((i-y)/(-1.*y/x)),35);}

```

Try it online!
> 1 votes

# Answer
# PHP, 66 Bytes

```
for([,$x,$y]=$argv;$i<$y;)printf("%".round(++$i*$x/$y)."s\n","#");

```
> 1 votes

# Answer
# JavaScript (ES6), 77 bytes

```
x=>y=>[...Array(y).keys()].map(a=>" ".repeat(0|((a+1)/(y/x))+.5)+"#").join`
`

```

```
f=x=>y=>[...Array(y).keys()].map(a=>" ".repeat(0|((a+1)/(y/x))+.5)+"#").join`
`

console.log(f(9)(5));
```
> 1 votes

# Answer
# Python, ~~64~~ 63 bytes

*1 byte saved thanks to @Cole*

```
def f(x,y):[print(' '*round((i+1)*x/y-1)+'#')for i in range(y)]

```

Try it online!
> 1 votes

# Answer
# Japt, 21 bytes

```
ÆSpºX+1 /(U/V  r)+"#

```

Try it online!

Input is in the format of `y x`. +1 byte for the `-R` flag.
> 0 votes

# Answer
# AWK, ~~55~~ 44 bytes

```
 {for(;++j<=$2;)printf"%*c\n",$1/$2*j+0.5,35}

```

Using hints from @manatwork and the solution from @Steadybox

The previous code is handy as an example of using an `sprintf` within a `printf`

```
{for(;++j<=$2;)printf sprintf("%%%.0fs\n",$1/$2*j),"#"}

```

Example usage:

```
awk '{for(;++j<=$2;)printf"%*c\n",$1/$2*j+0.5,35}' <<< "9 3"

```
> 0 votes

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


title: Piano Chords on White Keys

text:
# Question
Title: Piano Chords on White Keys
# Backstory \[which is not true\]

A piano is set up like this:

However, on my piano, all of the black keys are broken!

I still want to be able to play some chords on my broken piano though.

In music, a chord is a group of notes that are played together. To allow for input of chords, I will first define what a semitone is.

### What is a semitone?

A semitone is the smallest distance in Western music. If you look at the top part of the piano, you see that you can usually move from a black key to a white key, or vice versa; however, between `B` and `C` and `E` and `F` there is no black key.

### What is a chord?

For the purposes of this challenge, we define a chord as a bunch of notes with a certain number of semitones between them. For example, let's take a took at a `4-3-3` chord starting on `C` (for music people, this is a V7 chord in F major). We start at `C`. We count up 4 semitones: `C#`, `D`, `D#`, `E`. The next note is `E`, and we count 3 semitones up after that: `F`, `F#`, `G`. The next note is `G`, and we count 3 semitones up after that: `G#`, `A`, `Bb`. So, we get `C-E-G-Bb`. Yay! But wait... `Bb` is a black key and those are broken... However, if we start from `G`, we get `G-B-D-F`! Yay!

### Input

Input is given as a list of integers in any reasonable format. This represents the chord as described above.

### Output

Output should be a list of notes on which I can start to only need to use white keys. This can also just be a string of all of the up to 7 notes because all of the keynames will be one character. You must be able to handle having an empty output as well.

# Test Cases

```
input -> output // comments
4 3 -> C F G // this is a major triad
3 4 -> D E A // this is a minor triad
4 3 3 -> G // this is the major-minor seventh chord
3 3 3 -> [empty output] // this is the diminished-diminished seventh chord. All of them use black keys
4 4 -> [empty output] // this is an augmented triad
3 3 -> B // this is a diminished triad
1 -> B E // this is just a minor second
11 -> C F // this is just a major seventh

```

# Other specs

* Standard Loopholes forbidden
* You may assume that the input has at least one integer
* You may assume that all of the integers are non-negative and less than 12 (because the piano repeats every 12 notes)
* Output may be in any order

# Winning Criteria

The shortest valid submission as of April 15th will be accepted.

# Answer
> 3 votes
# Jelly, 25 bytes

```
236ḃ2ṙÐ€7+\€Ṭ
+\ịþ¢Ạ€TịØA

```

**Try it online!** or see a test suite

### How?

```
236ḃ2ṙÐ€7+\€Ṭ - Link 1, white-note-offsets: no arguments
236ḃ2         - 236 in bijective base 2 [2, 2, 1, 2, 2, 1, 2] - semitones G->A, A->B ...
     ṙÐ€7     - rotate left by, mapped over [1,2,3,4,5,6,7] - i.e. as above for each
                    starting white key (1st one A->B,B->C,...; 2nd B->C,C->D,...; etc)
         +\€  - reduce €ach with addition - i.e. absolute number of semitones: [[2,3,5,7,8,10,12],[1,3,5,6,8,10,12],[2,4,5,7,9,11,12],[2,3,5,7,9,10,12],[1,3,5,7,8,10,12],[2,4,6,7,9,11,12],[2,4,5,7,9,10,12]]
            Ṭ - untruth (vectorises) - make lists with 1s at those indexes: [[0,1,1,0,1,0,1,1,0,1,0,1],[1,0,1,0,1,1,0,1,0,1,0,1],[0,1,0,1,1,0,1,0,1,0,1,1],[0,1,1,0,1,0,1,0,1,1,0,1],[1,0,1,0,1,0,1,1,0,1,0,1],[0,1,0,1,0,1,1,0,1,0,1,1],[0,1,0,1,1,0,1,0,1,1,0,1]]

+\ịþ¢Ạ€TịØA - Main link: list of semitone gap integers (even negatives will work)
+\          - reduce by addition - gets the absolute semitone offsets needed
    ¢       - last link (1) as a nilad
   þ        - outer product with:
  ị         -     index into - 7 lists, each with 1s for white and 0s for black keys hit
                      note that indexing is modular and all the lists are length 12
                      so any integer is a valid absolute offset, not just 0-11 inclusive
     Ạ€     - all truthy for €ach - for each get a 1 if all keys are white ones, else 0
       T    - truthy indexes - get the valid starting white keys as numbers from 1 to 7
        ị   - index into:
         ØA -     the uppercase alphabet

```

# Answer
> 6 votes
# MATL, 31 bytes

*Thanks to Jonathan Allan for a correction.*

```
'BAGFEDC'"GYs12X\110BQX@YSYsm?@

```

Try it online! Or verify all test cases.

### Explanation

The pattern `2 2 1 2 2 2 1` specifies the intervals between consecutive white keys. The program uses a loop that applies all cyclic shifts to this basic pattern, in order to test each key as a potential lowest note of the input chord. For each shift, the cumulative sum of the pattern is obtained. For example, for `B` as potential lowest note, the pattern has been shifted to `1 2 2 1 2 2 2` and its cumulative sum is `1 3 5 6 8 10 12`.

Now, to see if this can support a `4 3 3` chord we compute the cumulative sum of the chord intervals, which is `4 7 10`; reduce it via 1-based modulo 12 (an interval of `14` would give `2`); and check if those numbers are all members of the allowed values `1 3 5 6 8 10 12`. That's not the case in this example. Had it been the case, we would output the letter `B`.

The correspondence between cyclic shifts and output letters is defined by the string `'BAGFEDC'`. This indicates that `'B'` (first character) corresponds to a cyclic shift by `1`; `'A'` (second character) corresponds to a cyclic shift by `2` etc.

```
'BAGFEDC'  % Push this string
"          % For each character from the string
  G        %   Push input array
  Ys       %   Cumulative sum
  12X\     %   1-based modulo 12, element-wise (1,12,13,14 respectively give 1,12,1,2)
  110BQ    %   Push 110, convert to binary, add 1 element-wise: gives [2 2 1 2 2 2 1]
  X@       %   Push current iteration index, starting at 1
  YS       %   Cyclic shift to the right by that amount
  Ys       %   Cumulative sum
  m        %   Ismember. Gives an array of true of false entries
  ?        %   If all true
    @      %     Push current character
           %   End (implicit)
           % End (implicit)
           % Display (implicit)

```

# Answer
> 5 votes
# Mathematica, 110 bytes (ISO 8859-1 encoding)

```
±i_:=#&@@@Select["A#BC#D#EF#G#"~StringTake~{Mod[#,12,1]}&/@#&/@(Accumulate[i~Prepend~#]&/@Range@12),FreeQ@"#"]

```

Defines a unary function `±` taking a list of integers as input (no restrictions on the size or signs of the integers, actually) and returns a list of one-character strings. For example, `±{3,4}` returns `{"A","D","E"}`.

`"A#BC#D#EF#G#"~StringTake~{Mod[#,12,1]}&/@#` is a function that turns a list of integers into the corresponding note names, except that `#` stands for any black key. This is applied to each element of `Accumulate[i~Prepend~#]&/@Range@12`, which builds up a list of note values from the list input list of note intervals, starting with each possible note from 1 to 12. We filter out all such note-name lists that contain `"#"` using `Select[...,FreeQ@"#"]`, and then return the first note in each remaining list using `#&@@@`.

# Answer
> 3 votes
# Python 2, ~~159~~ 155 bytes

(Posting this after making sure there's a valid submission that's shorter than this one)

```
import numpy
s='C.D.EF.G.A.B'
def k(y):return lambda x:s[(x+y)%12]
for i in range(12):
    if s[i]!='.'and'.'not in map(k(i),numpy.cumsum(input())):print s[i]

```

Pretty much just the trivial solution. Inputs as a list of integers and outputs with each character on an individual line.

-4 bytes by removing an unnecessary variable

# Answer
> 3 votes
## JavaScript (ES6), ~~72~~ ~~71~~ 68 bytes

```
a=>[..."C1D1EF1G1A1B"].filter((c,i,b)=>!+c>a.some(e=>+b[i+=e,i%12]))

```

Loops through each key omitting black keys, then checking that the cumulative sum of semitones never lands on a black key.

Edit: Saved 3 bytes thanks to @Arnauld.

---
Tags: code-golf, music
---


title: Tiling the unit square

text:
# Question
Title: Tiling the unit square
## Background

By expanding and cancelling terms, it is easy to show the following identity:

However, it is an open problem whether all 1/n-by-1/(n+1) rectangles can tile the unit square.

## The Task

Your program should take a positive integer N as input in any convenient manner, and pack all 1/n-by-1/(n+1) open rectangles with n between 1 and N inclusive into the unit square, such that no two overlap.

For each rectangle you must generate the following integers in order:

* 1 if the horizontal edges are longer than the vertical edges, else 0
* The numerator and denominator of the x-coordinate of the bottom-left corner
* The numerator and the denominator of the y-coordinate of the bottom-left corner

Note that we take the unit square to be `(0, 1) x (0, 1)`, with x-values running from left to right, and y-values running from bottom to top.

The final expected output is the concatenation of these integers for each rectangle in order of increasing n, in any convenient format (e.g. printed to stdout, or as a list returned from a function).

## Example Input and Output

Input:

```
3

```

Output:

```
0 0 1 0 1 1 1 2 0 1 1 1 2 1 3

```

This parses as the following:

```
0 (0/1, 0/1)  1 (1/2, 0/1)  1 (1/2, 1/3)

```

## Scoring

This is a code-golf challenge, so the answer with the fewest bytes wins. However, your algorithm should also be reasonably efficient; it should be able to run for all `N<=100` in a total of around 10 minutes.

Your solution must give valid solutions for all `N<=100`, but provably complete algorithms are also welcome even if they aren't the shortest.

# Answer
> 2 votes
# Haskell, ~~263~~ 262 bytes

```
import Data.Ratio;f m=let{(#)n z|n>m=[[]]|True=[a:y|(a,j)<-[((o,x,y),[c|c<-(u&w,h-v,x,g):(w-u,h&v,a,y):z,c/=b])|b@(w,h,x,y)<-z,(o,u,v)<-[(o,1%(n+1-o),1%(n+o))|o<-[0,1]],(a,g)<-[(x+u,y+v)|u<=w,v<=h],let(&)p q|w>h=p|True=q],y<-(n+1)#j]}in(1#[(1%1,1%1,0%1,0%1)])!!0

```

This follows the algorithm described in Paulhus 1997, *An Algorithm for Packing Squares*, doi:10.1006/jcta.1997.2836. The key observation in the paper, which is empirically if not theoretically verified, is that the region left over after placing a rectangle in a box can be split into two sub-boxes whose filling can then in turn be regarded as independent.

Rather than finding the smallest width sub-box to fit the next rectangle into, the code performs a search across all possible sub-boxes; in practice this does not make an appreciable slow down for *n*\<100.

Output is in the form of a list of entries as tuples with the fraction marker `%` still included. The integers in the formatted output are in the desired order, but strictly speaking some post-processing would be required to produce the list of integers alone.

Sample run:

`*Main> f 5
(0,0 % 1,0 % 1),(0,1 % 2,0 % 1),(0,1 % 2,1 % 2),(0,3 % 4,1 % 2),(1,1 % 2,5 % 6)`

**Edit:** removed an errant space after a `let`.

---
Tags: code-golf, geometry, search, packing
---


# Question
Title: How much reputation does a steam user have?
# Introduction

For those not familiar with steam - or at least this particular aspect:

Often on peoples' profiles, people leave comments saying either "+rep \_____" or "-rep \_____". These are an unofficial means of showing whether you think someone in the community has a good or a bad reputation, for a number of reasons. Such comments look like:

> +rep a good player
>
> +rep helpful
>
> -rep hacker
>
> -rep scammer

---

# Task

The program must take input through any consensual way. The input consists of a string with optional newlines (`\n`). At the very start of each line, `'+rep '` or `'-rep '` might be present. The rest of the line can be discarded. If the line doesn't start with `'+rep '` or `'-rep '` (note the trailing space), the line should be ignored.

The program then must keep a total reputation score. Starting at `0`, this score should be incremented on every line that starts with `'+rep '` and decremented on every line that starts with `'-rep '`.

This result should be output in any agreed-upon way.

---

# Test cases

```
Input:
+rep fast trade
+rep nice person
-rep too good

Output: 1

Input:
-rep hacker
-rep scammer
-rep was mean

Output: -3

Input:
first
i don't like him
+rep good at cs go

Output: 1

Input (note the lack of a trailing space on the third line):
+rep +rep
hi +rep
-rep

Output: 1

Input:
+ rep

Output: 0

Input:
+rep like
-thing

Output: 1

```

---

## Bonus

I don't even know if it's possible, but bonus points if you can somehow get these comments from Steam.

# Answer
# 05AB1E, ~~18~~ ~~16~~ 17 bytes

Saved 2 bytes thanks to *Okx*
+1 byte due to change in spec where rep now need to be followed by a space.

```
|vy5£„+-S„·Ý «QÆO

```

Try it online!

**Explanation**

```
|v                   # for each line of input
  y5£                # get the first 4 chars of input
     „+-S„·Ý «       # push the list ['+rep ','-rep ']
              Q      # check each for equality
                     # results in either [1,0] for +rep, [0,1] for -rep or [0,0] for others
               Æ     # reduce by subtraction, gives either 1, -1 or 0
                O    # sum

```
> 9 votes

# Answer
# Python 3, 73 bytes

I'm sure this answer is garbage and will be beaten soon, but there's no other python answers yet

```
lambda x:sum(["- +".index(i[0])-1for i in x.split('\n')if i[1:4]=="rep"])

```

Use like this:

```
f = lambda x:sum(["- +".index(i[0])-1for i in x.split('\n')if i[1:4]=="rep"])
print(f("PUT INPUT HERE"))

```

## Fetching from steam

Here's some sample code which fetches the first 100 comments from KennyS' profile and calculates his rep.

```
import requests
from bs4 import BeautifulSoup

# Kenny's profile as Steam ID 64
# You can adjust this to whatever numbers you want
STEAM_PROFILE_URL = "76561198024905796"
payload =  {"start" : 0, "count" : 100}
r = requests.post("http://steamcommunity.com/comment/Profile/render/{}/-1/".format(STEAM_PROFILE_URL), payload)

# Comments are html inside a json object
soup = BeautifulSoup(r.json()["comments_html"], "html.parser")

# Get raw text for every comment.
# The " ".join() strips out the newlines and tabs which are part of html
comments = [" ".join(s.text.split()) for s in soup.find_all("div", {"class" : "commentthread_comment_text"})]

calculateRep = lambda x:sum(["- +".index(i[0])-1for i in x.split('\n')if i[1:4]=="rep"])

print(calculateRep("\n".join(comments)))

```
> 10 votes

# Answer
# Perl 5, 25 bytes

24 bytes of code + `-p` flag.

```
$\+=/^\+rep /-/^-rep /}{

```

Try it online!

`/^\+rep /` returns `1` if the line starts with `+rep`; `/^-rep /` returns `1` if the line starts with `-rep` (so only one of them will be one at most). We use `$\` to store the result, as it is implicitly printed at the end (thanks to `-p` flag and those unmatched `}{`).
> 9 votes

# Answer
# Python 2, 54 bytes

```
q=('\n'+input()).count;print q('\n+rep ')-q('\n-rep ')

```

Try it online! Takes a multiline string as input.

Counts the appearances of `'+rep '` and `'-rep '` only at starts of lines by searching for the string following a newline symbol. To catch the first line, a newline is prepended to the input.
> 6 votes

# Answer
# Retina, ~~63~~ ~~51~~ ~~50~~ 49 bytes

Didn't quite comply with the spec so I fixed some issues but also golfed it a lot (by borrowing the first line from Kritixi Lithos's solution).

Saved another byte thanks to Kritixi Lithos.

```
ms`(?!^[+-]rep ).

+`\+-|-\+

(.)+
$1$.&
T`+
$^
0

```

Try it online!

**Explanation**

```
ms`(?!^[+-]rep ).

```

First, everything from the input is deleted, except for the `+` and `-` from any `+rep` or `-rep` at the start of a line.

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

```

Then adjacent pairs of `+` and `-` are removed until no more can be removed. After this, what's left is either a run of `+`s, a run of `-`s, or nothing.

```
(.)+
$1$.&

```

Then a run of one or more characters (either `+` or `-`) is replaced with the character making up the run followed by the length of the run. This way, `+` is preserved at the start for positive results and `-` for negatives.

```
T`+

```

Then all `+`s are removed, in the event that the rep is positive.

```
$^
0

```

Finally, if the string is empty at this point, the rep is 0, so we write 0.
> 5 votes

# Answer
## PHP, 118 bytes

```
function s($a,$c=0){foreach(explode("
",$a)as$b){$b=substr($b,0,1).'1';if(is_numeric($b){$c+=$b});}return$c-($a=="");}

```

Try it online!

Used like this:

```
echo s("-rep bad
+rep good
+rep very good
+rep exceeds expectation");

```
> 3 votes

# Answer
# JavaScript, 55 bytes

Thanks @Neil for golfing off 12 bytes Thanks @Arnauld for golfing off 2 bytes

```
x=>x.split(/^\+rep /m).length-x.split(/^-rep /m).length

```

Try it online!

```
var y=x=>(x.match(/^\+rep /gm)||'').length-(x.match(/^-rep /gm)||'').length

document.querySelector('div').innerText=y(document.querySelector('textarea').value)
```

```
textarea{
  width: 95%;height: 100px;
  }
```

```
<textarea oninput = "document.querySelector('div').innerText=y(this.value)">
-rep Cheater!!
+rep very good, fun to play with
+rep my friend +rep
good
</textarea>
<div></div>
```
> 3 votes

# Answer
# Retina, ~~59~~ ~~53~~ ~~52~~ 50 bytes

```
ms`(?!^[+-]rep ).

+`\+-|-\+

-+
-$.&
\++
$.&
^$
0

```

Try it online!

Check out Basic Sunset's shorter answer in the same language!

### Explanation

```
ms`(?!^[+-]rep ).

```

Removes everything except for `[+-]rep` s.

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

```

Repeatedly removes 1 `-` for every `+` and vice versa.

```
-+
-$.&

```

Prepend a `-` (because the number is negative) to `-`s as well as replacing the `-`s with the number of `-`s.

```
\+
$.&

```

Do the same for `+`s, but don't prepend a `-`.

```
^$
0

```

Finally, if there is nothing, replace it with a `0`.
> 3 votes

# Answer
# Mathematica, 47 bytes (ISO 8859-1 encoding)

```
(±c_:=StringCount["
"<>#,c];±"
+rep"-±"
-rep")&

```

Pure function taking a newline-separated string as input and returning an integer. Note that the three newlines in the code are flanked by quotes and are thus each equivalent to `"\n"` in a string (but this way is one byte shorter than `"\n"`). `StringCount` does the heavy lifting; we manually add a newline to the beginning of the string so that the first line matches when appropriate. `±` is a unary helping function to avoid repetition of `StringCount`.

The alternative solution

```
(±c_:=StringCount["
"<>#,"
"<>c<>"rep"];±"+"-±"-")&

```

is 4 bytes longer, but I do like the sequence `±"+"-±"-"`....
> 3 votes

# Answer
# Röda, 53 bytes

```
{{|l|[1]if[l=~`\+rep .*`];[-1]if[l=~`-rep .*`]}_|sum}

```

Try it online!
> 3 votes

# Answer
# Java, 109 bytes

```
l->{int i=0;for(String s:l.split("\n")){if(s.startsWith("+rep "))i++;if(s.startsWith("-rep "))i--;}return i;}

```

Trying to make this shorter using `Stream`'s
> 1 votes

# Answer
# Stacked, 45 bytes

```
'^([+-])rep |.'{.a:''['#'a+]a if}mrepl'0'\+#~

```

Try it online!

Alternatively (49 bytes):

```
lines'^[-+]rep 'match$#'YES[0#0# '#'\+]"!''#`0\#~

```

## Explanation

```
'^([+-])rep |.'{.a:''['#'a+]a if}mrepl'0'\+#~

```

This basically extracts all `+` or `-` attached to the beginning of the line and `rep`. Then, to each, it prepends a `#`. Then, to the entire thing, a `0` is prepended. `#~` evaluates the string, which now looks something like:

```
0#+#+#-

```

`#+` is increment and `#-` is decrement. Thus, we obtain our desired result.
> 1 votes

# Answer
# Retina, 38 bytes

```
M!m`^[+-]rep
Os`.
+`\+-

*\M1!`-
[+-]

```

Try it online!

A different (and shorter) solution than the ones already posted in Retina.

### Explanation

```
M!m`^[+-]rep

```

(This line has a trailing space). Keep only the relevant parts of the input, i.e. the `+rep` or `-rep` at the beginning of a line.

```
Os`.

```

Sort all characters (including newlines). this will put +s and -s next to each other.

```
+`\+-

```

Repeatedly remove `+-` couples until at most one of the two signs remains.

```
*\M1!`-

```

Match the first `-` (if present) and print it without modifying the string.

```
[+-]

```

Count the number of signs remaining, and print it since this is the final stage of the program.
> 1 votes

# Answer
# JavaScript ES6, ~~85~~ 79 bytes

```
l=>eval(l.split`
`.map(i=>(r=i.slice(0,5))==`+rep `?1:r==`-rep `?-1:0).join`+`)

```

---

## Try it

```
f=l=>eval(l.split`
`.map(i=>(r=i.slice(0,5))==`+rep `?1:r==`-rep `?-1:0).join`+`);

console.log(f(`+rep fast trade
+rep nice person
-rep too good`));

console.log(f(`-rep hacker
-rep scammer
-rep was mean`));

console.log(f(`first
i don't like him
+rep good at cs go`));

console.log(f(`+rep +rep
hi +rep
-rep`));

console.log(f(`+ rep`));

console.log(f(`+rep like
-thing`));
```

---

## Ungolfed

```
const repcount=list=>{
    let array=list.split("\n");
    let values=array.map(item=>{
        let rep=item.slice(0,5);
        return rep==="+rep "?1:rep==="-rep "?-1:0;
    });
    let result=values.reduce((a,b)=>a+b);
    return result;
};

```

---

## History

### 85 bytes

```
l=>l.split`\n`.map(i=>(r=i.slice(0,5))=="+rep "?1:r=="-rep "?-1:0).reduce((a,b)=>a+b)

```
> 0 votes

# Answer
# C#, 87 bytes

```
s=>{int n=0;foreach(var t in s.Split('\n'))n+=t.IndexOf("rep ")==1?44-t[0]:0;return n;}

```

Anonymous function which splits the input string by using the newline character, searches for the "rep " string prefixed by a character and, if it finds it, increments the reputation (the `n` variable) by 1 or -1.

Full program with ungolfed method and test cases:

```
using System;

class P
{
    static void Main()
    {
        Func<string, int> f =
        s=>
        {
            int n = 0;
            foreach (var t in s.Split('\n'))
                n += t.IndexOf("rep ") == 1 ?
                    44 - t[0]
                    :
                    0;

            return n;
        };

        // test cases:
        Console.WriteLine(f(@"+rep fast trade
+rep nice person
-rep too good"));       // 1

        Console.WriteLine(f(@"-rep hacker
-rep scammer
-rep was mean"));       // -3

        Console.WriteLine(f(@"first
i don't like him
+rep good at cs go"));  // 1

        Console.WriteLine(f(@"+rep +rep
hi +rep
-rep"));            // 1

        Console.WriteLine(f(@"+ rep"));     // 0

        Console.WriteLine(f(@"+rep like
-thing"));          // 1
    }
}

```

**Note that the ASCII code for `+` is 43 and for `-` is 45. This method passes all test cases from the OP. However, if the first character is something else, this will lead to wrong answers!**

This can be fixed at the cost of 17 bytes:

# C# fixed, 104 bytes

```
s=>{int n=0;foreach(var t in s.Split('\n'))n+=t.IndexOf("rep ")==1?t[0]==43?1:t[0]==45?-1:0:0;return n;}

```

The modified anonymous function will check for a `+` or `-` sign as the first character in each line.
> 0 votes

# Answer
# Japt, 14 bytes

```
r`œp`1 f".%d

```

Try it online!

+1 byte for `-x` flag
> 0 votes

# Answer
# C++, 144 bytes

```
#import<iostream>
int f(){int r=0;for(std::string s;std::getline(std::cin,s);)if((s[0]==43|s[0]==45)&s.substr(1,4)=="rep ")r-=s[0]-44;return r;}

```

Try it online!
> 0 votes

# Answer
# Ruby, 46 bytes

```
->x{rep=1;eval ?0+x.map{|a|a[/^[+-]rep /]}*''}

```

Get all the +/-rep from input, and put together in a single string. Then evaluate that for rep=1.
> 0 votes

# Answer
## C#, 104 bytes

---

Despite existing already one solution -- and mine being longer -- I still think I should post it, since the on already here might fail if something like `'=rep '` gets in it's way.

---

**Golfed**

```
i=>{var c=0;foreach(var o in i.Split('\n'))c+=o.IndexOf("rep ")!=1?0:o[0]==43?1:o[0]==45?-1:0;return c;}

```

---

**Ungolfed**

```
i => {
   var c = 0;

   foreach( var o in i.Split( '\n' ) )
      c += o.IndexOf( "rep " ) != 1
         ? 0
         : o[ 0 ] == 43
            ? 1
            : o[ 0 ] == 45
               ? -1
               : 0;

   return c;
}

```

---

**Ungolfed readable**

```
i => {
   // Counter for the 'reputation'
   var c = 0;

   // Cycle through every line
   foreach( var o in i.Split( '\n' ) )
      // Check if the "rep " string has index 1
      //   ( Index 0 should be the sign )
      c += o.IndexOf( "rep " ) != 1
         // Add 0 if the rep isn't on the right position
         ? 0
         // Check for the '+' sign
         : o[ 0 ] == 43
            // Add 1 if the sign is found
            ? 1
            // Check for the '-' sign
            : o[ 0 ] == 45
               // Add -1 if the sign is found
               ? -1
               // Add 0 if another char is found
               : 0;

   // Return the 'reputation'
   return c;
}

```

---

**Full code**

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, Int32> f = i => {
            var c = 0;

            foreach( var o in i.Split( '\n' ) )
               c += o.IndexOf( "rep " ) != 1
               ? 0
                  : o[ 0 ] == 43
                  ? 1
                  : o[ 0 ] == 45
                     ? -1
                     : 0;

            return c;
         };

         List<String>
            testCases = new List<String>() {
               @"+rep fast trade
+rep nice person
-rep too good",
               @"-rep hacker
-rep scammer
-rep was mean",
               @"first
i don't like him
+rep good at cs go",
               @"+rep +rep
hi +rep
-rep",
               @"+ rep",
               @"+rep like
-thing",
         };

         foreach( String testCase in testCases ) {
            Console.WriteLine( $"{testCase}\n{f( testCase )}\n" );
         }

         Console.ReadLine();
      }
   }
}

```

---

**Releases**

* **v1.0** \- `104 bytes` \- Initial solution.

---

**Notes**

Nothing to add
> 0 votes

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


title: Extract an RGB channel of an image

text:
# Question
Title: Extract an RGB channel of an image
Given an image, either as input (possibly in RGB triplets) or with the filename as input (you may assume the image has a specific filename, possibly without an extension), output an image representing a single color channel of the image.

You will also take another input, representing which channel to output. The input can be one of any 3 distinct symbols. However, the symbols must be either a string or a number. You cannot take a matrice to apply to the array as input however. (such as `{1, 0, 0}`, or `{0, 1, 0}`).

You will output the `<input>` channel of the input image. You may either save it to a file or output a set of RGB pairs.

Your program should have no limits on the size of the image (in px), and must support either `.png`, `.jpg`/`.jpeg`/`.JPG`, or RGB triplets as image formats. (it can support as many as you want however)

Test case:

Red channel:

Green channel:

Blue channel:

And another test case, entirely of red. Original photo, red, green, and blue. (warning: the plain and red channel hurt to look at for too long)

2 more test cases:

Original, red, green, blue.

Original, red, green, blue.

The latter two test cases are from Images with all colors.

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

I/O: array of RGB triplets

```
⎕×⊂⎕=⍳3

```

Try it online!

`⍳3` first three integers

`⎕=` compare numeric input (the chosen channel) to that

enclose (so each image triplet pairs up this entire triplet)

`⎕×` multiply numeric input (the array of triplets) with that

# Answer
> 12 votes
# JavaScript (ES6), 29 bytes

```
a=>n=>a.map(b=>b.map(c=>c&n))

```

Input is a 2D array of 24-bit integers (e.g. `[[0x0000ff,0x00ff00],[0xff0000,0xffffff]]`) and `16711680` for red, `65280` for green, `255` for blue. If this isn't valid, try this instead:

## JavaScript (ES6), 48 bytes

```
a=>n=>a.map(b=>b.map(c=>c.map((d,i)=>i==n?d:0)))

```

Input is a 3D array of color values and `0` for red, `1` for green, `2` for blue.

# Answer
> 10 votes
## Mathematica, 13 bytes

```
ImageMultiply

```

This should be the legitimate version of JungHwan Min's answer. This function takes the image and one of `Red`, `Green`, `Blue` as input. For example:

As a fun-fact, there's also `ColorSeparate` which gives you individual channels, but it returns them as single-channel/greyscale images, so you'd need to multiply them by the colour afterwards anyway.

# Answer
> 8 votes
# Bash + ImageMagick, ~~35~~ ~~32~~ 27 bytes

```
mogrify -channel $1 -fx 0 i

```

Assumes the image is in the file `i` and the script takes one of `RG`, `BG`, `BR` for blue, red, and green respectively; outputs to the file `i`.

# Answer
> 8 votes
# Spectrum, noncompeting, 1 byte

(Non-competing because this challenge inspired this language.) In reality, Spectrum is an npm library with a language interface for the commands.

```
I

```

Takes input as:

```
<filename>
channel

```

Call the program as:

```
cat input.txt | node spectrum.js "I"

```

Alternatively, you may supply information to the prompts:

```
λ node spectrum.js "I"
input> Ov3Gm.png
input> r
[ Image { 512x512 } ]

```

This leaves the image on the stack. To view it, add `O` at the end, like so:

```
λ node spectrum.js "IO"
input> Ov3Gm.png
input> r
[]

```

---

For some extra fun, try `echo filename | node spectrum.js "wO"`. It performs all three channel isolations at once:

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

```
a=>b=>a.map((v,i)=>i%3^b?0:v)

```

A lot like ETHproductions' answer but with more flexible input than the first method and smaller than the second one.

This defines a function which accepts the image as a 1-dimensional array of numerical colour intensities. This function then returns another function which accepts an integer value representing the desired colour channel.

Colours can be represented by any numerical range as long as 0 indicates a complete absence of colour. E.g. `0.0 - 1.0` or `0 - 255`

**Examples:**

If image data is in the format RGB then calling the function with arguments `(imageData)(0)` will return the image with only the red channel.

If image data is in the format BGR then calling the function with arguments `(imageData)(2)` will also return the image with only the red channel.

# Answer
> 6 votes
# Python 2, 69 bytes

```
from cv2 import*
def f(s,i):k=imread(s);k[:,:,[i,i-1]]=0;imwrite(s,k)

```

Still golfing.

Takes input as `filename, n` (where `n` is 0, 1, or 2). Saves the new image over the old one. `0` is green, `1` is red, and `2` is blue. Thanks to @ovs, @Mikhail and @Rod for bytes off.

# Answer
> 5 votes
# CJam, 12 bytes

```
{3,f=f{f.*}}

```

An anonymous block that expects a 3D array of RGB triplets and a number between 0 and 2 inclusive on the stack. Leaves the extracted array on the stack afterward.

```
Red   -> 0
Green -> 1
Blue  -> 2

```

Could possibly be golfed by using a bizarre input format, but I feel like that's cheating a bit.

Try it online!

The test case is made up just to demonstrate, using the triplets from an actual image would be way too big.

**Explanation**

```
3,          e# The range [0 1 2]
  f=        e# Check each for equality with the RGB indicator, gives the indicator array:
            e#  [1 0 0] for 0, [0 1 0] for 1, [0 0 1] for 2
    f{      e# Map on each row of the array using the indicator array as an extra parameter
      f.*   e#  Perform vectorized multiplication of the indicator array with each triplet.
            e#   For red, multiplies red by 1, and green and blue by 0. Does similarly
            e#   for green and blue.
         }  e# (end of block)

```

# Answer
> 5 votes
# PowerShell, 282 bytes

```
$x,$y=$args;1..($a=New-Object System.Drawing.Bitmap $x).Height|%{$h=--$_;1..$a.Width|%{$i=("$($a.GetPixel(--$_,$h)|select R,G,B)"|iex)[$y];$r,$g,$b=(((0,0,$i),(0,$i,0))[$y-eq'G'],($i,0,0))[$y-eq'R'];$a.SetPixel($_,$h,[system.drawing.color]::fromargb($r,$g,$b))}};$a.save("$x$y.png")

```

None of this fancy "golfing the input" or "using built-ins." Phooey on that. ;-)

This here takes the full path of an input PNG (though, strictly speaking, it doesn't *need* to be a PNG, since JPG, BMP, etc. are supported by .NET, but I've only tried it on PNGs), and one of `(R, G, B)` for the color channel, then stores those into `$x` and `$y`. We then create a `New-Object` of type `System.Drawing.Bitmap` of `$x` and store that into `$a`.

Then we do a double loop over all pixels. First from `1` up to `$a`'s `.Height`, setting `$h` each iteration (it's zero-indexed, so that's why we `--$_`, which saves bytes over `( .height-1)`. Inside, we loop from `1` up to `$a`'s `.Width`.

Each iteration, we're performing a `.GetPixel` on the particular `w,h` coordinates, which returns a `System.Drawing.Color` object. We `select` out the `R G B` values thereof. The `iex` here is a neat trick that turns this into a hashtable (e.g., something like `@{R=34; G=177; B=76}`) so we can index into that directly with the desired color channel `[$y]`. That value is stored into `$i`.

Next, we set three values `$r, $g, $b` to be the result of some pseudo-ternary operators based on the letter value of `$y`. So, for example, if `$y` is `R`, then the result here is `$r=$i, $g=0, $b=0`.

Then, we do a `.SetPixel` back onto that particular `w,h` coordinate, constructing a new `System.Drawing.Color` using the static `FromARGB` (which assumes the alpha to be fully opaque). Once we've finished looping, we then simply `.Save` the PNG to a new file.

*Note: This does take a long while, since it's completely independently looping through every pixel and performing a bunch of calculations and calls each iteration.*

Tests:

# Answer
> 3 votes
# Bash + ImageMagick, 41 bytes

```
C="RGB"
mogrify -channel ${C//$1} -fx 0 x

```

Input is a file named `x`, command line parameter one of `R` or `G` or `B`

Output overwrites the input file

Differs from betseg's answer in taking more natural single-letter channel parameter. Also overwriting instead of outputting a new file which betseg is free to steal :)

# Answer
> 3 votes
# Chip, 78 bytes

```
 ~Z~vS
f/F,^-.
e/E|,-Z.
d/D|>zz^.
a/AMx-x-].
b/BMx-]v-'
c/CM]v-'
 >--v'
G/gh/H

```

Try it online!

Chip is a 2D language that operates on the component bits of each byte in a byte stream.

### Overview

This particular solution expects the first byte of input to be the control character--to define which channel(s) to keep--and following is the bytes of image data. The image data must be RGB triplets, one byte per channel, 24 bits per pixel:

```
|  1  |  2  |  3  |  4  |  5  |  6  |  7  | ... | 3n-2 |  3n  | 3n+1 |
|     |   First Pixel   |   Second Pixel  | ... |      nth Pixel     |
| Ctl | Red | Grn | Blu | Red | Grn | Blu | ... |  Red |  Grn |  Blu |

```

The control character is interpreted as a bit field, though only the three lowest bits have meaning:

```
0x1  keep Red channel
0x2  keep Green channel
0x4  keep Blue channel

```

This means we can use ASCII characters to select which channel we want:

`1` means red
`2` means blue
`4` means green

Or do something fancier:

`5` keep red and blue, but not green
`7` keep all channels (image is unchanged)
`0` drop all channels (image is black)

### How it works

This solution is rather jumbled up due to golfing, but here goes:

1. Read the three low bits of the first byte with `C`, `B`, and `A`, and store those bits in their corresponding `M`emory cells. Also, `S`uppress output for the first cycle.
2. Loop over those three bits repeatedly. If the current bit it is on, close the `/` switches to output the current input byte, if it is off, open the switches so that we output a zero byte.
3. Continue until input is exhausted.

### Viewing the results

Sure, you could use hexdump or something boring, but it turns out this is (almost) an actual valid image format: binary Portable PixMap.

Just plop the image data from above (minus the control byte, of course) into the file below, adjust the width/height to be valid, and you can view the image in a proper viewer like IrfanView, though simpler ones (like most browser built-ins) can't handle it.

```
P6
{width as ASCII} {height as ASCII}
255
{binary image data here}

```

For example (using escapes for the raw data):

```
P6
3 1
255
\xff\x00\x00\x00\xff\x00\x00\x00\xff

```

# Answer
> 3 votes
# MATL, ~~21~~ 13 bytes

```
Yi3:iml&!*3YG

```

The color channel should be specified using the following mapping: `1:red`, `2:green`, `3:blue`

The Online interpreters are unable to use `imread` to read images so here is a slightly modified version where I have hard-coded a random image into the source.

**Explanation**

```
        % Implicitly grab first input as a string (filename)
Yi      % Read the image in from a filename or URL
3:      % Push the string literal 'rgb' to the stack
i       % Grab the second input as a number
m       % Check for membership. So for example 2 will yield [false, true, false]
l&!     % Permute the dimensions to turn this 1 x 3 array into a 1 x 1 x 3 array
*       % Multiply this with the input RGB image. It will maintain the channel which
        % corresponds with the TRUE values and zero-out the channels that corresponded to
        % the FALSE values
3YG     % Display the image

```

# Answer
> 2 votes
# 05AB1E, 16 bytes

```
vyvy2ô²è}})¹0ègô

```

Try it online!

Uses hex colors in a 2D array format and \[0,1,2\] for each channel.

# Answer
> 2 votes
# Clojure, ~~421~~ 332 bytes

**-89 bytes** by aggressively inlining everything, changing from my ridiculous old method of stripping the channels, and getting rid of an unnecessary accidental import.

```
(import '(java.awt.image BufferedImage)'(clojure.lang Keyword)'(javax.imageio ImageIO)'(java.io File)'(java.awt Color))(fn[p i](doseq[y(range(.getHeight p))x(range(.getWidth p))](.setRGB p x y(.getRGB(apply #(Color. % %2 %3)(#(let[c(Color. %)](assoc [0 0 0]i(([(.getRed c)(.getGreen c)(.getBlue c)]%)i)))(.getRGB p x y))))))(ImageIO/write p"jpg"(File."./o.jpg")))

```

Smacked this out half an hour before my shift started with no idea what I was doing. I have little experience with `BufferedImage`, so there may be a better way of going about this. I'm also abusing `Color` to convert back-and-forth between integer and individual channel representations of colors.

This is comically huge compared to the other answers for a couple reasons (besides the obvious that Clojure isn't a golfing language):

* Instead of just manipulating a byte array, this actually takes as input a picture, alters it, and outputs it.
* I'm using Java-interop, which while handy can be quite verbose at times. The imports alone are larger than many answers.

See the code below for a break down.

```
(ns bits.restrict-channel
  (:import (java.awt.image BufferedImage)
           (clojure.lang Keyword)
           (javax.imageio ImageIO)
           (java.io File)
           (java.awt Color)))

(defn restrict-channel
  "Accepts a BufferedImage and a index between 0 and 2 (inclusive).
  Removes color from all channels EXCEPT the channel indicated by color-i.
  color-i of 0 = keep red
  color-i of 1 = keep green
  color-i of 2 = keep blue"
  [^BufferedImage image ^long color-i]
  (let [; Turn a number representing RGB into a triplet representing [R G B]
        channels #(let [c (Color. %)]
                    [(.getRed c) (.getGreen c) (.getBlue c)])

        ; Create a new triplet that only contains color in the color-i channel
        zero-channels #(assoc [0 0 0] color-i ((channels %) color-i))]

    ; Loop over each pixel
    (doseq [y (range (.getHeight image))
            x (range (.getWidth image))]

      ; Grab the current color...
      (let [cur-color (.getRGB image x y)]

        ; ... setting it to stripped color triplet returned by zero-channels
        (.setRGB image x y

                          ; This "apply" part is just applying the stripped triplet to the Color constructor
                         ;  This is needed to convert the separate channels into the integer representation that `BufferedImage` uses.

                 (.getRGB (apply #(Color. % %2 %3) (zero-channels cur-color))))))

    ; Save the result to file
    (ImageIO/write image "jpg" (File. "./o.jpg"))))

```

# Answer
> 1 votes
# Lua (love2d Framework), 498 bytes

I did this more as a exercise for myself, so it's not as short as it could be (though I did try to golf), but I wanted to add it to here cause I think I did good. Even if I'm too late.

Here the golfed code, under it is the explained and untangled version.

```
l=love g,p,rm,bm,gm,s=l.graphics,0,1,1,1,[[uniform float m[4];vec4 effect(vec4 co,Image t,vec2 c,vec2 s){vec4 p=Texel(t,c);p.r=p.r*m[0];p.b=p.b*m[1];p.g=p.g*m[2];return p;}]]t=g.setShader h=g.newShader(s)function l.draw()h:send("m",rm,gm,bm)if p~=0 then t(h)g.draw(p)t()end end function l.filedropped(f)a=f:getFilename()p=g.newImage(f)end function l.keypressed(k)if k=="0"then rm,gm,bm=1,1,1 end if k=="1"then rm,gm,bm=1,0,0 end if k=="2"then rm,gm,bm=0,1,0 end if k=="3"then rm,gm,bm=0,0,1 end end

```

Here is the code which has to get a \*.jpg file dropped into it. After the image was inserted you can press the number buttons for red(1) green(2) or blue(3) channels. Also to see the default picture again press 0. Actually it just shows the picture in the window.

```
l=love
g=l.graphics
p=0
rm,bm,gm=1,1,1
s = [[uniform float m[4];
vec4 effect(vec4 co,Image t,vec2 c,vec2 s){vec4 p=Texel(t,c);p.r = p.r * m[0];p.b = p.b * m[1]; p.g = p.g * m[2]; return p;}
]]
sh=g.newShader(s)

function l.draw()
  sh:send("m",rm,gm,bm)
  if p~=0 then
    g.setShader(sh)
    g.draw(p)
    g.setShader()
  end
end

function l.filedropped(f)
  a=f:getFilename()
  p=g.newImage(f)
end

function l.keypressed(k)
  if k=="0"then rm,gm,bm=1,1,1 end
  if k=="1"then rm,gm,bm=1,0,0 end
  if k=="2"then rm,gm,bm=0,1,0 end
  if k=="3"then rm,gm,bm=0,0,1 end
end

```

The important part which does all the work is the shader which is the small string declaration at the beginning or untangled:

```
uniform float m[4];
vec4 effect(vec4 co,Image t,vec2 c,vec2 s)
{
    vec4 p=Texel(t,c);
    p.r = p.r * m[0];
    p.b = p.b * m[1];
    p.g = p.g * m[2];
    return p;
}

```

which gets the actual pixel of the image and just shows the channels as needed.

My test image and the different outputs for the channels (also for sure the other ones)

# Answer
> 0 votes
# C, ~~60~~ 58 bytes

```
main(a,b)char**b;{while(scanf(b[1],&a)>0)printf("%d ",a);}

```

Image input is a list of numbers (in decimal) between 0 and 255 on `stdin`, e.g.

```
255 0 0  192 192 192  31 41 59 ...

```

The channel is specified as the first argument to the program, and is one of

```
red   -> "%d%*d%*d"
green -> "%*d%d%*d"
blue  -> "%*d%*d%d"

```

Example:

```
$ echo "255 0 0" | ./extract "%d%*d%*d"
255

```

---
Tags: code-golf, graphical-output, image-processing, color
---


title: A code golf challenge, m'kay

text:
# Question
Title: A code golf challenge, m'kay
Mr. Mackey is a South Park character well-known for adding "m'kay" in everything he says.

Write a program or function that transforms a string of text into something Mr. Mackey would say.

### M'kay placement

* `m'kay` has a **random 50% chance** of being added **after the punctuations `,`, `.`, `?` and `!`**. If that is the case, it will be followed by the exact same punctuation mark that preceeds it and preceeded by a space.

For example, in the sentence `Test, test.`, there are two places where `m'kay` can be added: after the comma, and after the period, with a 50% chance at each place. Possible results would be `Test, m'kay, test`. or `Test, test. M'kay.` or `Test, m'kay, test. M'kay.`.
* There must always be **at least one `m'kay` added**. Moreover, it cannot always be at the same place and each valid place where `m'kay` could be added must occur with equal probability. That is, you can't add `m'kay` always at the end of the string if because of randomness you never added any `m'kay`. If there is only one `m'kay`, it must have the same probability of appearing in each valid position, even though its presence is enforced.
* If `m'kay` is after `?`, `.` or `!`, the `m` must be uppercased.
* The number of `m` in `m'kay` must be uniformely picked between 1 and 3. That is, `m'kay`, `mm'kay` and `mmm'kay` are all possible choices, each with probability 0.33... If it must be uppercased (see above rule), all `m` must be uppercased.

### Inputs, outputs

* Inputs are ASCII strings containing characters from ASCII Dec 32 (Space) to ASCII Dec 126 (Tilde `~`). There are no linebreaks in the input. You may assumed that any input will contain at least one of `, . ? !`.
* You may assume that there are no `m'kay` or any of its variants in the input.

Inputs may be taken from STDIN, function arguments, command line, or anything similar.
* Output may be via STDOUT, a function return, or something similar.

### Test cases

* Input: `Test.`

Possible output: `Test. M'kay.`

* Input: `Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.`

Possible output: `Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. MMM'kay. It's 100% free, mm'kay, no registration required.`

* Input: `Drugs are bad, so, if you do drugs, you're bad, because drugs are bad. They can hurt your body, cause drugs are bad.`

Possible output: `Drugs are bad, m'kay, so, if you do drugs, you're bad, m'kay, because drugs are bad. They can hurt your body, m'kay, cause drugs are bad. M'kay.`

* Input: `Do you understand? Really? Good!`

Possible output: `Do you understand? MM'kay? Really? Good! MMM'kay!`

### Scoring

This is , so the shortest code in bytes wins, m'kay?

# Answer
# CJam, ~~65~~ ~~52~~ 49 bytes

```
l{_{_",.?!"#:IW>)mr{SI'M'm?3mr)*"'kay"3$}&}%_@=}g

```

Try it online in the CJam interpreter.

### How it works

```
l            e# Read a line from STDIN.
{            e# Do:
  _          e#   Duplicate the line.
  {          e#   For each of its characters:
    _",.?!"# e#     Find its index in that string.
    :IW>     e#     Save the index in I and check if it's greater than -1.
    )        e#     Add 1 to the resulting Boolean.
     mr      e#     Pseudo-randomly select a non-negative integer below that sum.
             e#     If I == -1 the result will always be 0.
    {        e#     If the result is 1:
      S      e#       Push a space.
      I'M'm? e#       Select 'm' if I == 0 (comma) and 'M' otherwise.
      3mr)   e#       Pseudo-randomly select an integer in [1 2 3].
      *      e#       Repeat the M that many times.
      "'kay" e#       Push that string. MMM'kay.
      3$     e#       Copy the proper punctuation.
    }&       e#
  }%         e#
  _          e#   Copy the resulting array.
  @=         e#   Compare it to the copy from the beginning.
}g           e# Repeat the loop while the arrays are equal.
             e# This makes sure that there's at least one m'kay. M'kay.

```
> 14 votes

# Answer
# APL (66)

```
{∊⍉⍵⍪⍉⍪(¯1+⌈?2×⍵∊',.!?')/¨{' ',⍵,⍨'''kay',⍨'mM'[1+⍵≠',']/⍨?3}¨⍵}⍣≢

```

Result of 10 runs:

```
      ↑ ({∊⍉⍵⍪⍉⍪(¯1+⌈?2×⍵∊',.!?')/¨{' ',⍵,⍨'''kay',⍨'mM'[1+⍵≠',']/⍨?3}¨⍵}⍣≢)¨ 10/⊂'Test, test. Test! Test?'
Test, m'kay, test. Test! Test?
Test, test. M'kay. Test! MMM'kay! Test? M'kay?
Test, mm'kay, test. Test! MM'kay! Test? MM'kay?
Test, mmm'kay, test. Test! Test? M'kay?
Test, mm'kay, test. Test! Test? M'kay?
Test, test. MM'kay. Test! Test? MMM'kay?
Test, test. MMM'kay. Test! MMM'kay! Test? M'kay?
Test, test. Test! MM'kay! Test?
Test, mm'kay, test. M'kay. Test! Test?
Test, test. MM'kay. Test! MM'kay! Test?

```

Explanation:

* `{`...`}⍣≢`: apply the function to the input until the value changes
    + Generate a `M'kay` for each character:
    + `{`...`}¨⍵`: for each character in the input:
        - `'mM'[1+⍵≠',']/⍨?3`: generate 1 to 3 `m`s or `M`s depending on whether the character was a comma or not.
        - `'''kay',⍨`: append the string `'kay`.
        - `⍵,⍨`: append the character
        - `' ',`: prepend a space.
    + `(¯1+⌈?2×⍵∊',.!?')/¨`: for each `M'kay`', if its corresponding character is one of `.,!?`, select it with 50% chance, otherwise select it with 0% chance.
    + `⍉⍵⍪⍉⍪`: match each selection with its character,
    + : list all the simple elements (characters) in order.
> 22 votes

# Answer
# K5, ~~99~~ 90 bytes

```
{f::0;{x;~f}{,/{f::f|r:(*1?2)&#&",.?!"=x;x,("";" ",((1+1?3)#"Mm"@x=","),"'kay",x)@r}'x}/x}

```

Well, *someone* needed to kick-start this!

Saved 9 bytes by using a less fancy method of uppercasing the M.

## Explanation

```
{                                                                                }  Define a function
 f::0;                                                                                Set `f` (used to determine when to stop) to 0.
      {x;~f}{                                                                         }/x   While `f` is 0 (no "m'kay"s have been inserted), loop over the string argument
               {                                                                   }'x      For each character in the string
                       (*1?2)&#&",.?!"=x                                                    If we are at a punctuation character, generate a random number between 0 and 1
                     r:                                                                     and assign it to `r`
                f::f|                                                                       If the number is one, an "m'kay" will be inserted, so the outer while loop should exit after this
                                                            "Mm"@x=","                      If the punctuation is a comma, then use a lowecase `m`, otherwise use `M`
                                                    (1+1?3)#                                Repeat the `m` between 1 and 3 times
                                               " ",(                  ),"'kay",x            Join the "m'kay" string to the punctuation and prepend a space
                                         x,("";                                 )@r         If the random number is 1, append the "m'kay" string, to the current string
             ,/                                                                             Join the resulting string

```

## 99-byte version

```
{f::0;{x;~f}{,/{f::f|r:(*1?2)&#&",.?!"=x;x,("";" ",((1+1?3)#`c$(-32*~","=x)+"m"),"'kay",x)@r}'x}/x}

```
> 9 votes

# Answer
# Julia, mm'kay, ~~115~~ 114 bytes

```
f(s)=(R=replace(s,r"[,.?!]",r->r*(" "*(r==","?"m":"M")^rand(1:3)*"'kay"*r)^rand(0:1));ismatch(r"m'kay"i,R)?R:f(R))

```

This creates a recursive function that accepts a string and returns a string.

Ungolfed + explanation:

```
function f(s)
    # Replace occurrences of punctuation using random repeats
    R = replace(s, r"[,.?!]", r -> r*(" " * (r == "," ? "m" : "M")^rand(1:3) * "'kay" * r)^rand(0:1))

    # Check whether anything was replaced
    if ismatch(r"m'kay"i, R)
        # If so, return the replaced string
        R
    else
        # Otherwise recurse
        f(R)
    end
end

```

I dislike South Park, but the thrill of the golf was too enticing to pass this up. Thanks to KRyan for simplifying a regex, saving 1 byte.
> 7 votes

# Answer
# JavaScript ES6, ~~79~~ ~~86~~ 108 bytes

Turns out making the `M` repeat takes a lot of bytes.

```
(s,z=Math.random)=>s.replace(/([!?.,])/g,l=>z(t=t+1)>=.5||t?` ${(l==','?'m':'M').repeat(0|z()*3+1)}'kay`+l:l)

```

Old version (doesn't repeat)**(86 bytes)**

```
(s,t=1)=>s.replace(/([!?.,])/g,l=>Math.random()>=.5||--t?` ${l==','?'m':'M'}'kay`+l:l)

```

Older version (doesn't repeat, doesn't require at least one m'kay)**(79 bytes)**:

```
s=>s.replace(/([!?.,])/g,l=>~~(Math.random()*2)?l+` ${l==','?'m':'M'}'kay`+l:l)

```

Oldest version:

```
s=>(r=t=>t.replace(/([!?.])/,"$1 M'kay$1").replace(/,/,", m'kay,"),r(s),[for(i of s)~~(Math.random()*2)?r(i):i].join``)

```
> 6 votes

# Answer
# Pyth, ~~51~~ ~~50~~ 49

*Saved 1 byte thanks to @Maltysen.*

```
 fnzJsm?&O2}dK",.!?"s[d\ *hO3?xKd\M\m"'kay"d)dz0J

```

Try it online.

Explanation & more golfing coming soon.
> 5 votes

# Answer
# C, 170 bytes

First crack at it:

```
n;main(r,v,p)char**v,*p;{for(srand(time(0)),p=v[1];r=rand(),*p;p++)if(strchr(".,?!",putchar(*p))&&r%2||(!*(p+1)&&!n))n=printf(" %.*s'kay%c",r/2%3+1,*p%4?"MMM":"mmm",*p);}

```

Ungolfed:

```
n;
main(r,v,p)
char**v,*p;
{
    for(srand(time(0)), p=v[1]; r=rand(), *p; p++) /* loop through string */
        if(strchr(".,?!",putchar(*p)) /* print the char, check if punctuation */
            && r % 2 /* should we say it? */
            || (!*(p+1) && !n)) /* If this is the end of the string and we haven't M'kay'd, then do it now */
            n=printf(" %.*s'kay%c", r/2%3+1, *p%4 ? "MMM" : "mmm", *p); /* say it! */
}

```
> 4 votes

# Answer
## Scala, 191 bytes

```
var(r,s,a,o)=(util.Random,readLine,1>2,"")
while(!a){o=""
for(c<-s)o+=(if(",.?!".contains(c)&&r.nextBoolean){a=2>1
s"$c ${(if(c==46)"M"else"m")*(1+r.nextInt(3))}'kay$c"}else s"$c")}
print(o)

```
> 4 votes

# Answer
# Mathematica, 202 bytes

```
i=0;r=Random;x=r[];
h=" "<>If[#==",","m","M"]~Table~{Ceiling[3r[]]}<>"'kay"<>#&;
(ee/.a:>(If[e~Count~a@__==i&&#==Floor[x*i],h@#2,""]&))@
StringReplace[#,x:","|"."|"?"|"!":>x~~RandomChoice@{i++~a~x,h@x}]&

```

Line breaks added for readability. Evaluates to an anonymous function taking the string as an argument. ( is shorthand for `\[Function]`.)

Ungolfed:

```
h[x_]:=" " <> Table[
    If[x==",", "m", "M"],
    { Ceiling[3 Random[]] }
] <> "'kay" <> x;

```

`h` takes a punctuation char and makes it `" m'kay,"`, `" mm'kay,"`, etc. randomly and capitalized appropriately.

```
f[s_] := (i = 0;
   StringReplace[s,
    x : "," | "." | "?" | "!" :>
     x ~~ RandomChoice[{a[i++, x], h[x]}]]);

```

`f` takes a string and looks for any punctuation character `x`; when it finds it, it tacks on with 50% probability the appropriate `h[x]`, and 50% an expression like `a[3, x]`. It also updates `i` to the total number of punctuation replaced (with both cases). So `f["X, x."]` might evaluate to

```
"X," ~~ h[","] ~~ " x." ~~ a[1, "."]           ...which might expand to
"X, mmm'kay, x." ~~ a[1, "."]                  , and i would equal 2

```

Finally, `g` will deal with the `a`'s.

```
g[expr_] := (r = Random[];
  expr /. a -> (If[Count[expr, a[__]] == i && # == Floor[r*i], h[#2], ""] &))

```

`Count` will count how many `a`'s we put in there; if it equals `i`, the total number of punctuation, then we didn't add any m'kays. In this case, we will have expressions like `a[0, _] ... a[i-1, _]`, and we define `a` so that it'll return an m'kay for exactly one of `0..i-1`.
> 3 votes

# Answer
# Perl, ~~93~~ ~~89~~ 88 bytes

```
$_=$0=<>;s/[.?!]|(,)/$&.($".($1?"m":M)x(1+rand 3)."'kay$&")[rand 2]/ge while$0eq$_;print

```

Can definitely be golfed some more!

*4 bytes cut off thanks to Dom Hastings*
> 2 votes

# Answer
# Python, 173 168 156

```
from random import randint as R
    m,k,s,C="mM","'kay",input(),0
    while C<1:
        S=""
        for c in s:r=R(0,c in",.!?");C+=r;S+=c+(' '+m[c!=","]*R(1,3)+k+c)*r
    print(S)

```

Ungolfed:

```
from random import randint
m, kay = "mM", "'kay"
string = input()
count = 0
while count < 1: #at least one occurrence
    newString= ""
    for char in s:
        rm  = randint(1,3) #number of "m"
        rmk = randint(0, char in ",.!?") #occurrence of "m'kay"
        count += rmk
        newString += char + (' ' + m[c != ","] * rm + kay + char) * rmk
print(newString)

```
> 2 votes

# Answer
## **\>\<\>, 150 bytes**

```
i:0(?v
r0&v >
?v~>:0(?v::o1[:::",.?!"{=${=+${=+r=+]
>x~^    >&:0)?;&"."14.
v>&1+&1[:","=&"yak'"&84**"M"+
 >  >84*v
>x::^>22 .
 >: ^]
ol0=?^  >

```

13 wasted bytes, but I've gotten a little bored trying to rearrange it. Also, randomisation in a Funge is hard to golf -.-
> 2 votes

# Answer
## C++ 290

**My solution**

```
void M(string x){
srand(rand());
string p(",.?!");
char c=0,m='m',n='M';
int r=0;
size_t z=0;
for(size_t i=0;i<x.size();i++)
{
c=x[i];cout<<c;
z=p.find(c);
r=rand()%2;
if(z!=string::npos&&r)
{
cout<<' ';
c=(z?n:m);
r=rand()%3+1;
while(r--){cout<<c;}
cout<<"\'kay";
}
}
}

```

**Explanation** variable z determines which punctuation mark and z=0 indicates to use 'm' rather than 'M'.

**Test**

```
int main()
{
int x=5;
while(x--){
string S("Do you understand? Really? Good! Yes, I do.");
M(S);
cout<<endl;
}
return 0;
}

```
> 2 votes

# Answer
# JavaScript ES6, 121 bytes

```
(s,r=Math.random,f=t=>t==s?f(s.replace(/[!?.,]/g,m=>r()<.5?m:m+" "+(m==","?"mmm":"MMM").slice(r()*3)+"'kay"+m)):t)=>f(s)

```

Crashes if the given string contains no suitable punctuation.
> 1 votes

# Answer
# Lua, ~~162~~ 160 bytes

```
r=math.random;s,m=io.read()repeat m=s:gsub("([,.?!])",function(p)return p..(r()>.5 and" "..(p==","and"m"or"M"):rep(r(1)).."'kay"..p or"")end)until s~=m;print(m)

```

> Did you ever hear the tragedy of Darth Plagueis The Wise? MM'kay? I thought not. MMM'kay. It’s not a story the Jedi would tell you. M'kay. It’s a Sith legend. Darth Plagueis was a Dark Lord of the Sith, m'kay, so powerful and so wise he could use the Force to influence the midichlorians to create life… He had such a knowledge of the dark side that he could even keep the ones he cared about from dying. MM'kay. The dark side of the Force is a pathway to many abilities some consider to be unnatural. MM'kay. He became so powerful… the only thing he was afraid of was losing his power, mmm'kay, which eventually, mm'kay, of course, m'kay, he did. M'kay. Unfortunately, he taught his apprentice everything he knew, then his apprentice killed him in his sleep. M'kay. Ironic. He could save others from death, but not himself.
> 1 votes

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


title: Let's do some location arithmetic!

text:
# Question
Title: Let's do some location arithmetic!
From the Wikipedia article:

> Location arithmetic (Latin arithmeticæ localis) is the additive (non-positional) binary numeral systems, which John Napier explored as a computation technique in his treatise Rabdology (1617), both symbolically and on a chessboard-like grid.

## What?

Location numerals is a way of writing numbers using letters of the alphabet.

> Binary notation had not yet been standardized, so Napier used what he called location numerals to represent binary numbers. Napier's system uses sign-value notation to represent numbers; it uses successive letters from the English alphabet to represent successive powers of two: **a = 2^0 = 1, b = 2^1 = 2, c = 2^2 = 4, d = 2^3 = 8, e = 2^4 = 16** and so on.

## An example

**`ab`** = 1+2 = 3 in base 10

**`aabb`** = 1+1+2+2 = 6 in base 10

Note that `aabb` can be shortened to `bc` by replacing any 2 instances of a letter by a higher one.

## Addition

You just concatenate the two numbers and simplify.

`acd` \+ `bde` = `acdbde` = `abcdde` = `acebe` = `abcf` = `39` in base 10

## Subtraction

Just remove all digits appearing equally in both parts of the subtraction. Expanding (converting `b` to `aa`) may be necessary

`abde`\- `ad` = `be` = 18 in base 10

## Multiplication

This is a bit harder.

Lets say we want to multiply `acd` (13) by `def` (56). First you arrange `acd` vertically:

```
a
c
d

```

Then you add `def` after the first `a`:

```
a def
c
d

```

Now, c is 2 positions later in the alphabet than a, so we add 2 positions in the alphabet to `def` to make `fgh`. That is added to the second row.

```
a def
c fgh
d

```

Lastly, d is 1 position later in the alphabet than c, so we add 1 position in the alphabet to `fgh` to make `ghi`. That is added to the third row.

```
a def
c fgh
d ghi

```

Then you take the sum of the right: `def` \+ `fgh` \+ `ghi` = `deffgghhi` = `deggghhi` = `deghhhi` = `deghii` = `deghj` (728)

## Another example of multiplication

Input:

```
bc * de

```

First:

```
b
c

```

Then

```
b ef
c

```

Then

```
b ef
c fg

```

**Note that we wrote down `ef` on the first line. That's because `bc` starts with `b`, and `b` is the second letter in the alphabet, so we need to shift `de` by 1 letter, so it becomes `ef`.**

Then

```
ef+fg

```

Output:

```
eh

```

## Division

This is not part of this challenge, because it can get very complex.

# Your actual challenge

Your program or function must take input as a string that looks like this:

```
a + b

```

And you must output:

```
ab

```

Of course, your program or function must support numbers of arbitrary length (up to the string or input limit of your language) with any of the operators `+`, `-`, or `*`. Some more examples:

Input:

```
ab + bd

```

Output:

```
acd

```

Input:

```
d - ab

```

Output:

```
ac

```

Input:

```
ab * cd

```

Output:

```
cf

```

# Notes:

* The order of letters in the output doesn't matter, but you can always assume that the order of letters in numbers in the input will be ascending (a before z).
* You may take input with a trailing newline and output with a trailing newline.
* You may *not* take input as a list of `ab`, `*` and `bd` for `ab * bd`.
* The english alphabet is used (`abcdefghijklmnopqrstuvwxyz`)
* Your output must be simplified (`aa` is not allowed, `b` is required)
* The input will be simplified (`b` \+ `c`, not `aa` \+ `bb` or `aa` \+ `aaaa`)
* You may require a space before and the operator (`+`, `-`, or `*`), or you may require there to be none.
* There will only be one operator per input.
* You may assume that the output and the input will never go over 2^27-1 (`abcdefghijklmnopqrstuvwxyz`)
* **This is , so the shortest answer in bytes wins!**

# Answer
# Jelly, ~~26~~ 25 bytes

```
i@€Øað’2*S;ḟ.Ḣ
ḲÇ€VBṚTịØa

```

Uses Jelly's operators (`×` rather than `*` and `_` rather than `-`) in the input string as allowed by the OP.

(Requires spaces around the operators)

**Try it online!** or see the test suite

### How?

```
i@€Øað’2*S;ḟ.Ḣ - Link 1, transform from input sub-string to value or operator: sub-string
i@€            - 1st index of, for €ach (or 0 if not found) [reversed @rguments] in:
   Øa          -      lowercase alphabet (i.e. a->1, b->2, ..., non-alpha->0)
     ð         - dyadic chain separation i.e. f(result above, substring):
      ’        - decrement (i.e a->0, b->1, ..., non-alpha->-1)
       2*      - 2 raised to that power
         S     - sum
          ;    - concatenate with the substring
           ḟ   - filter out:
            .  -     0.5 (for an operator substring the evaluated 0.5 is removed)
             Ḣ - head (i.e. the evaluation for a location, and the operator otherwise)

ḲÇ€VBṚTịØa - Main link: string                        e.g. 'ab × cd'
Ḳ          - split on spaces                               [['a','b'],['×'],['c','d']]
 Ç€        - last link (1) as a monadic function for €ach  [3,'×',12]
   V       - evaluate as Jelly code                        36
    B      - convert to binary                             [1,0,0,1,0,0]
     Ṛ     - reverse                                       [0,0,1,0,0,1]
      T    - truthy indexes                                [3,6]
       ị   - index into:
        Øa -     lowercase alphabet                        ['c','f'] (i.e. "cf", which is implicitly printed when run as a full program)

```
> 2 votes

# Answer
## JavaScript (ES6), ~~136~~ ~~134~~ 133 bytes

*Saved 1 byte thanks to Luke*

```
s=>[...a='abcdefghijklmnopqrstuvwxyz'].filter((c,i)=>eval(s.replace(/\w+/g,s=>[...s].reduce((p,c)=>p|1<<a.search(c),0)))&1<<i).join``

```

### Test cases

```
let f =

s=>[...a='abcdefghijklmnopqrstuvwxyz'].filter((c,i)=>eval(s.replace(/\w+/g,s=>[...s].reduce((p,c)=>p|1<<a.search(c),0)))&1<<i).join``

console.log(f('ab + bd'));  // acd
console.log(f('d - ab'));   // ac
console.log(f('ab * cd'));  // cf
```
> 6 votes

# Answer
## Mathematica, 168 bytes

```
FixedPoint[StringReplace[x_~~x_:>FromCharacterCode[c@x+1]],Table["a",ToExpression@StringReplace[#,x:LetterCharacter..:>ToString@Tr[2^((c=ToCharacterCode)@x-97)]]]<>""]&

```

My initial solution (before the post was edited to clarify that the output must be simplified) was `64` bytes shorter:

```
Table["a",ToExpression@StringReplace[#,x:LetterCharacter..:>ToString@Tr[2^(ToCharacterCode@x-97)]]]<>""

```

This just modified that solution to work. It's probably shorter to actually use the methods described in the challenge, but I wanted to put this up anyway.

## Explanation:

Replaces each sequence of letters with its corresponding integer by character code arithmetic, then converts the resulting string to an expression (which will automatically simplify to an integer), then produces a string of `a` characters of length equal to that integer, and finally replaces adjacent identical characters with the next character code up until a fixed point is reached.
> 6 votes

# Answer
# Perl 5, 95 bytes

94 bytes of code + `-p` flag.

```
s/\w/a x 2**(-97+ord$&)/ge;s/(.*)-\1|\+//;/\*/&&($_=$`x length$');1while s/(.)\1/chr 1+ord$1/e

```

Try it online!

Three steps here:
\- `s/\w/a x 2**(-97+ord$&)/ge;` converts the input into a string of `a` only.
\- `s/(.*)-\1|+//;/*/&&($_=$`x length$')` will execute the operator (that are very simple on strings of `a`): `+` is the concatenation, `-` means removing from the first part as many `a` as there are in the second part, and `*` means duplicating the first part as many times as there are `a` in the second part.
\- `1while s/(.)\1/chr 1+ord$1/e` folds the consecutive same letters into the next letter in the alphabet.
> 4 votes

# Answer
# 05AB1E, 29 bytes

```
ð¡À¬U¦v0yvAyko+}}X.VbRvyiANèJ

```

Try it online! or as a Test suite

**Explanation**

```
ð¡                             # split input on string
  À                            # rotate left
   ¬U¦                         # get the operator, store it in X and remove it from list
      v                        # for each side of the equation
       0                       # push 0 as an accumulator
        yv                     # for each letter in each side of the equation
          Ayk                  # get its index in the alphabet
             o                 # raise 2 to this power
              +                # add to the accumulator
               }}              # end loops
                 X.V           # apply the operator to the 2 numbers now on the stack
                    bR         # convert to binary and reverse
                      v        # for each binary digit
                       yi      # if it is true
                         ANè   # get the letter at that index in the alphabet
                            J  # join stack to a single string

```
> 4 votes

# Answer
# C & x86 asm, 340 Bytes

Compile with -O0

```
#define G getchar()
g(){int c,a=0;for(;islower(c=G);)a+=1<<(c-97);return a;}
main(){short o[]={[43]=0x4403,[45]=0x442b,[42]=0x6cf7};
mprotect((long)&&l&~4095,4096,7);
for(;;){int c,b=0,a=g();*(short*)&&l=o[G];G;g();asm("xchg %%eax,%0":"+m"(a));
l:asm("addl %1,%%eax":"=a"(c):"m"(a));
for(;a=c>>b;b++)if(a&=1)putchar(97+b);putchar(10);}}

```

**Explanation**

Since C doesn't have `eval()`, I used a table of x86 instructions in its place. I had to choose instructions which were all the same length (or padded with nops), and which expected src and destination of the same types. Of particular annoyance was that MUL can only write to registers, and the 1-byte MUL opcodes can only write to EAX. Additionally, there seemed to be no register-writing SUB instruction which subtracted from memory, instead of the other way around, hence the XCHG.

**edit**

Since it was asked in the comments, a more traditional appraoch would look like this:

```
#define G getchar()
#define return r
#define int i
g(){i c,a=0;for(;islower(c=G);)a+=1<<(c-97);r a;}
a(i x,i y){r x+y;}s(i x,i y){r x-y;}m(i x,i y){r x*y;}
main(){i(*o[])(i,i)={[43]=a,[45]=s,[42]=m};
for(;;){i c,b,a=g();b=G;G;g();c=o[b](a,g());
for(b=0;a=c>>b;b++)if(a&=1)putchar(97+b);putchar(10);}}

```

It's actually a bit shorter, at 301 chars, for a few reasons: 1. Because there need to be a lot of functions, the overhead of each can be chopped with some preprocessor rules. 2. Modern linux protects from execution on the stack, so the mprotect() call to disable this sacrificed 34 bytes. 3. The XCHG call is very sub-optimal, costing another 30 bytes. If not for those things, the x86 combo would win by about 10-20 bytes.

Also chopped 2 bytes from both by improving the islower() call in g.
> 4 votes

# Answer
# GNU sed + coreutils, 329 bytes

Yeah, I have no idea what got into me, but at least I know sed scripting a bit better now. Note that this solution requires GNU sed's `e` extension, which runs a shell command.

```
/\+/{s/\+//
b S}
/-/{:E
/a+-a+/{s/(a*)(a*)-\2/\1/
b S}
s/.*/echo &|tr b-z- A-Y-/
e
s/([A-Z])/\L\1\1/g
b E}
/\*/{h
:M
/^\*/{x
s/[^\n]*//
s/\n//g
b S}
s/(.).*\*(.*)/echo \2|tr a-z \1-za-z/
e
H
g
s/.(.*)/\1/
h
s/\n.*//
b M}
:S
s/^.*$/echo &|grep -o .|sort|tr -d '\n'/
e
:L
s/(.)\1/\u\1/g
/^[a-z]*$/ q
s/.*/echo &|tr A-Z b-za/;e
b L

```

I assume that there will not be spaces around the operators. From my terminal:

```
$ sed -rf golf.sed <<< a+b
ab
$ sed -rf golf.sed <<< ab+bd
acd
$ sed -rf golf.sed <<< abc+b
ad
$ sed -rf golf.sed <<< d-ab
ca
$ sed -rf golf.sed <<< ab*cd
cf
$ sed -rf golf.sed <<< bc*de
eh
$ sed -rf golf.sed <<< acd*def
deghj

```

And, for those saner than I: the commented version!

```
#!/bin/sed -rf

/\+/ {
    s/\+//
    b simplify
}

/-/ {
    # expand pattern space; everything will now be 'a's
    :E
    /a+-a+/{
        # Remove doubled 'a's on either side of the dash. For example,
        # for input d-ab, space is now 'aaaa-aaa'; substitute this to 'a'
        s/(a*)(a*)-\2/\1/
        b simplify
    }
    # shift letters that aren't 'a' down and double them
    s/.*/echo &|tr b-z- A-Y-/;e
    s/([A-Z])/\L\1\1/g
    b E
}

/\*/ {
    # Hold space: line 1 is pattern, other lines are output
    h
    :M

    # if space starts with *, we've eaten entire arg0; sum and simplify
    /^\*/ {
        x
        s/[^\n]*//      # remove first line, which is our pattern
        s/\n//g         # remove newlines to add results together
        b simplify
    }

    # convert pattern into shifting command
    s/(.).*\*(.*)/echo \2|tr a-z \1-za-z/

    # execute it, append result to hold space
    e
    H

    # restore pattern, with leading char and all output lines removed
    g
    s/.(.*)/\1/
    h
    s/\n.*//

    b M
}

:simplify
# reorder all letters so all 'a's are before all 'b's are before all 'c's
# are before ... etc
# See https://stackoverflow.com/questions/2373874
s/^.*$/echo &|grep -o .|sort|tr -d '\n'/
e

:L
# Replace repeated characters with themselves upper-cased, then translate
# upper-cased characters to what they should be.
s/(.)\1/\u\1/g
/^[a-z]*$/ q
s/.*/echo &|tr A-Z b-za/;e
b L

```
> 4 votes

# Answer
# PHP, 168

Output Ascending with use of eval

```
[$a,$o,$b]=explode(" ",$argn);function d($s){for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);return$n;}for(eval("\$k=d($a)$o d($b);");$i<26;)echo$k&2**$i++?chr(96+$i):"";

```

# PHP, 185 Bytes

Output Ascending

```
[$a,$o,$b]=explode(" ",$argn);function d($s){for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);return$n;}for(;$i<26;)echo(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b))&2**$i++?chr(96+$i):"";

```

Online Version

Expanded

```
[$a,$o,$b]=explode(" ",$argn); # part the input into variables
function d($s){ # make decimal value
    for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);
    return$n;
}
for(;$i<26;)
echo(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b))&2**$i++?chr(96+$i):""; # Bitwise Compare and Output

```

## PHP, 201 Bytes

Output Decending

```
[$a,$o,$b]=explode(" ",$argn);function d($s){for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);return$n;}for($r=(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b));$r;$r-=2**$l)$t.=chr(97+$l=log($r,2)^0);echo$t;

```

Online Version

Expanded

```
[$a,$o,$b]=explode(" ",$argn); # part the input into variables
function d($s){ # make decimal value
    for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);
    return$n;
}
for(
$r=(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b)) # result of the operation
;$r;
$r-=2**$l) # subtract the letter value
$t.=chr(97+$l=log($r,2)^0); # find greatest letter
echo$t; # Output

```
> 3 votes

# Answer
# Python 3, 176 167 bytes

```
i=lambda a:str(sum(1<<ord(i)-97for i in a))
def f(a):
 a,b,c=a.split();m=eval(i(a)+b+i(c));r=''
 while m:
  t=0
  while m>=2**t*2:t+=1
  r+=chr(97+t);m-=2**t
 return r

```

Try it online!
> 3 votes

# Answer
# PHP, 130

```
for($d=a;$e=$argn[$i++];)$e!=' '?$d!=b?$$d+=1<<ord($e)-97:$b=$e:++$d;eval("for(;\$j++<27;)echo($a$b$c>>\$j-1)&1?chr(96+\$j):'';");

```

expanded version:

```
for($d=a;$e=$argn[$i++];)       // for each char in the input
  $e!=' '?                      //   if space
    $d!=b?                      //     if not the operation
      $$d+=1<<ord($e)-97:       //       add 2^(char - 'a')
      $b=$e:                    //     else save operation
    ++$d;                       //   else increase "pointer"
eval("for(;\$j++<27;)           // for each bit in the output
        echo($a$b$c>>\$j-1)&1?  //   calulate the result and check the bit
          chr(96+\$j):          //     output corrosponding char
          '';                   //     output nothing
     ");

```

run with `php -R <code>`.
> 1 votes

# Answer
# AWK, 201 bytes

```
BEGIN{RS="(.)"}n=index(V="abcdefghijklmnopqrstuvwxyz",RT){s+=2^--n}index("+-*",RT){a=s RT
s=0}END{RS="\n"
"(awk '$0="a s"'<<<1)"|getline v
for(j=26;j--;)if((s=v-2^j)>=0){v=s;c=substr(V,j+1,1)c}print c}

```

`"(awk '$0="a s"'<<<1)"|getline v` is the best way I could come up with to do an `evaluate` in `AWK`. I may be "cheating" a little to call this just `AWK`, since I am executing a command, but at least the command is also `AWK` :)

I'm sure I'm missing some way to reduce the byte-count, but I sure can't see it.

Usage is fairly standard, e.g. put the code in `FILE` and do:

```
awk -f FILE <<< "bc + ab"

```

Note that spaces are not required and any non-op/non\[a-z\] character will be silently ignored. Could be extended to work with numbers greater than "abcdefghijklmnopqrstuvwxyz" by changing the loop. To do division, simply add the `/` character to the operation string :). Also, will print a blank line if the `result <= 0`.
> 0 votes

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