title: Letter, Number, Symbol, Space, Repeat

text:
# Question
Title: Letter, Number, Symbol, Space, Repeat
There are 97 ASCII characters that people encounter on a regular basis. They fall into four categories:

1. Letters (52 total)

```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

```
2. Numbers or Digits (10 total)

```
0123456789

```
3. Symbols & Punctuation (32 total)

```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

```
4. Whitespace (3 total)

Space , tab `\t`, and newline `\n`. (We'll treat newline variants like `\r\n` as one character.)

For conciseness, we'll call these categories L, N, S, and W respectively.

Choose any of the 24 permutations of the letters `LNSW` you desire and repeat it indefinitely to form a programming template for yourself.

For example, you might choose the permutation `NLWS`, so your programming template would be:

```
NLWSNLWSNLWSNLWSNLWS...

```

**You need to write a program or function based on this template, where:**

1. Every `L` is replaced with any letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`).
2. Every `N` is replaced with any number (`0123456789`).
3. Every `S` is replaced with any symbol (`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`).
4. Every `W` is replaced with any whitespace character ( `\t\n`).

Basically, your code must follow the pattern

```
<letter><number><symbol><whitespace><letter><number><symbol><whitespace>...

```

as the question title suggests, except you may choose a different ordering of the four character categories, if desired.

**Note that:**

* Replacements for a category can be different characters. e.g. `9a ^8B\t~7c\n]` validly conforms to the template `NLWSNLWSNLWS` (`\t` and `\n` would be their literal chars).
* There are no code length restrictions. e.g. `1A +2B -` and `1A +2B` and `1A`  and `1` all conform to the template `NLWSNLWSNLWS...`.

**What your template-conformed code must do** is take in one unextended ASCII character and output a number from 0 to 4 based on what category it is a member of in the categorization above. That is, output `1` if the input is a letter, `2` if a number, `3` if a symbol, and `4` if whitespace. Output `0` if the input is none of these (a control character).

For input, you may alternatively take in a number 0 to 127 inclusive that represents the code of the input ASCII character.

The input (as char code) and output pairs your code must have are precisely as follows:

```
in out
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 4
10 4
11 0 or 4
12 0 or 4
13 0 or 4
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 0
24 0
25 0
26 0
27 0
28 0
29 0
30 0
31 0
32 4
33 3
34 3
35 3
36 3
37 3
38 3
39 3
40 3
41 3
42 3
43 3
44 3
45 3
46 3
47 3
48 2
49 2
50 2
51 2
52 2
53 2
54 2
55 2
56 2
57 2
58 3
59 3
60 3
61 3
62 3
63 3
64 3
65 1
66 1
67 1
68 1
69 1
70 1
71 1
72 1
73 1
74 1
75 1
76 1
77 1
78 1
79 1
80 1
81 1
82 1
83 1
84 1
85 1
86 1
87 1
88 1
89 1
90 1
91 3
92 3
93 3
94 3
95 3
96 3
97 1
98 1
99 1
100 1
101 1
102 1
103 1
104 1
105 1
106 1
107 1
108 1
109 1
110 1
111 1
112 1
113 1
114 1
115 1
116 1
117 1
118 1
119 1
120 1
121 1
122 1
123 3
124 3
125 3
126 3
127 0

```

Inputs 11, 12, and 13 correspond to characters that are sometimes considered whitespace, thus their outputs may be `0` or `4` as you desire.

**The shortest code in bytes wins.**

# Answer
# Haskell 300 bytes

This code should have no trailing newline. The function `m1` takes the input as a `Char` and returns the answer as a `Char`.

```
f1 (l1 :n1 :p1 :y1 :l2 :n2 :p2 :y2 :r3 )x1 |y1 >p1 =b1 (x1 )y2 (f1 (r3 )x1 )y1 (n1 )n2 |p2 <p1 =b1 (x1 )y1 (n1 )p2 (f1 (p2 :y2 :r3 )x1 )l2 |p2 >p1 =b1 (x1 )p1 (l2 )l1 (n2 )n1
;b1 (x1 )s1 (r1 )b1 (r2 )r3 |x1 <s1 =r1 |x1 >b1 =r2 |s1 <b1 =r3
;m1 =f1 "d0 \t4 \r0 ~d3 {d1 `d3 [d1 @d3 :d2 /d3 !d4 \n0 ?d0 "

```

I couldn't resist a challenge that someone claimed was impossible for "conventional" languages.

You may dispute whether Haskell counts, but the majority of keywords and identifiers are multiple characters and cannot be used. However, top level function definitions, lists, string literals, strict comparisons, pattern matching and branching with guards work, as long as letters come just before digits, and if symbols also come just before letters we have escape characters like `\t` and `\r`. Unfortunately the permutations that work for general programming don't allow numeric literals, so I couldn't get numbers in any useful way.

# How it works:

* The intervals of character classes are encoded in the string on the last line, with boundary characters at most of the symbol places and the results in most of the digit places, although some at the ends are padding.
* The main function is `m1`.
* `x1` is the character being analyzed.
* The `f1` function breaks up the string with list pattern matching, and has three branches: for when the boundaries are symbols larger than space, for when the boundaries are escaped control characters smaller than space, and for handling the final comparison to space itself. The names of the list pieces are mnemonic for the first branch: Letter, Number, sPace, sYmbol, Remainder.
* The `b1` function handles branching for two boundary characters `s1 < b1` at a time.

Try it online
> 38 votes

# Answer
# Retina, 113 bytes

*Letter, Number, Space, Symbol, Repeat*

```
T1 `a0 @a0 `b1	:D0
+T1 `d9 `a2
+T1 `a9	\n9 `a4
+T1 `l9 @L9 `a1
+T1 `d9 @p9 `d3
\b4
$n3
\b3
$n2
\b2
$n1
\b1
$n0
\n

```

Try it online!

Test it on itself!

Retina seems like a nice tool for this job: we can use all types of characters flexibly in stage configuration, and we have some predefined character classes that can be useful.

I think this problem could be solved with either Replacement stages or Transliteration stages; I've chosen the Transliterations because they are more flexible and they have the most useful character classes. Regarding the pattern of the source, I was forced to put symbols right before letters in order to use `\n` for newlines (I actually had a shorter solution using the more practical ¶ for newlines, but non-ascii characters are banned).

### Explanation

The first stages are transliterations. We use `+` and `1` as options to keep the pattern going but they won't affect the result of the stage. The syntax is `T`from`to` to map each character of `from` to the character in the same position in `to`. If `to` is shorter than `from`, its final character is repeated as much as needed. If `from` has repeated characters, only the first occurrence of each one is considered. Some letters correspond to character classes, e.g. `d` is equivalent to `0123456789`.

```
T1 `a0 @a0 `b   :D0

```

With this we map some characters to other characters of the same class in order to "make some room" for following transliterations. (`a`-\>`b`,`0`-\>`1`,`space`-\>`tab`,`@`-\>`;`). The final `:D0` is just a smiley :D0

```
+T1 `d9 `a2

```

We start with digits, `d` is the character class `0-9`, here we're transforming `0`-\>`a`,`1-9`-\>`2`,`space`-\>`2`: the transliterations for `0` and `space` are wrong, but those characters have been eliminated by the previous transliteration.

```
+T1 `a9 \n9 `a4

```

Whitespace, transform `a`-\>`a`,(`9`,`tab`,`\n`,`space`)-\>`4`. `9` was already removed in the previous stage.

```
+T1 `l9 @L9 `a1

```

Letters, here we use two different character classes (for lack of a more complete one): `l` for lowercase letters and `L` for uppercase letters. They all get mapped to `1`, along with some other characters which have been dealt with in the previous stages

```
+T1 `d9 @p9 `d3

```

Symbols. Since every other class has been turned into a digit, here we map all digits to themselves with `d`-\>`d`, and then all printable characters to `3` with `p`-\>`3`. Digits are also among printable characters, but the first transliteration wins.

Now we need to assign `0` to control characters, but I've found no valid way to explicitly address that class. Instead, we'll convert each digit to unary: control characters are not digits and so they are considered as the empty string, which equals `0` in unary. Unfortunately, the unary conversion command in retina is `$*`, which are two symbols near each other, so we'll instead convert "manually" using substitutions.

```
\b4
$n3
\b3
$n2
\b2
$n1
\b1
$n0

```

Our unary digit is `$n`, which is a replacement pattern for newlines. `\b` matches a "boundary", where an alphanumeric word starts or ends: in our case this will always match before any number. We are basically replacing each number `n` with a newline plus `n-1`.

```
\n

```

In the end, we count the number of newlines and get the desired result.
> 14 votes

# Answer
# Cardinal ~~2240~~ 2224 bytes

Template used LSNW

```
a%1
a:1 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a+1 a+1 a.1 x.1 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a>0 a+1 a+1 a+1 a+1 a.1 x>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a+1 a.0 x>1 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a.0 x>1 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a+1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a+1 a+1 a.0
a>1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^0 a.0

```

The code has a trailing newline.

## How it works:

This code has a lot of characters that aren't used.
% releases a pointer in all directions. 3 of them just hit the end of a line and die.
The last pointer takes in an input at the :
This input is then compared to each value from 0 to 127.

Prints:
0 for 0-8
4 for 9-12
0 for 13-31
4 for 32
3 for 33-47
2 for 48-57
3 for 58-64
1 for 65-90
3 for 91-96
1 for 97-122
3 for 123-126
0 for 127

Operations used:
J = Skip next operation if non-zero
^ = Change direction to up
\> = Change direction to left
\- = Decrement
\+ = Increment
: = Take input
% = Create pointers at start of program
x = Remove pointer
0 = Set active value of pointer to 0

Try it online
> 11 votes

# Answer
# Perl 5, 293 bytes

**291 bytes code + 2 for `-0p`.**

*I have been advised the command-line flags are free, but I've added them here for visibility, as the TIO link doesn't include `-0`, for easier testing.*

```
y 0-a 1"a 1#a 1$a 1%a 1&a 1'a 1(a 1)a 1*a 1+a 1,a 1.a 1/a 1_a 1{a 1|a 1}a 1~a 0!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 0;s 0\s
0\t
0;s 0\d
0\r
0;s 0\w
0\n
0;y 1!a 9-a 1_a 0-Z 1;s 0\w
0\u 3\u 0;s 1\S
1\u 0\u 1;s 0\t
0\u 4\u 0;s 0\r
0\u 2\u 0;s 0\n
0\u 1\u 0

```

Try it online!

This is a particularly tricky challenge to solve in almost any language, so I'm pretty happy I was able to (finally, lots of tinkering on and off for quite some time) get this working in Perl. Hopefully the additional whitespace before and after the number isn't an issue.

Selecting the sequence order was particularly tricky, but forunately `s///` and `y///` can accept any other character as a delimiter so it was possible to use letter, space, number, symbol, which allows for `s 0...0...0;` and `y 0...0...0;`.

The first thing required for the appraoch was to replace `_` with `!` so that `\w` would only match `[0-9a-zA-Z]`, then replace all whitespace (`\s`) with `\t`, all digits with `\r` and all remaining word characters (`\w`) with `\n` for easy matching later on. Then, using the `y///` operator, all remaining symbols are converted to word characters `!` to `_` and all other chars (between `9` and `a`) are shifted down 9 places, turning them into letters or numbers. These are then replaced via `\w` with `3` and the other, previously made substitutions are replaced with their numbered values.
> 7 votes

# Answer
# Whitespace, 1332 bytes

```
Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0! Y0! Y0!
Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0!
Y0!
Y0! Y0!
Y0! Y0! Y0!
Y0!
Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0! Y0!
Y0!
Y0!
Y0!
Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0! Y0!
Y0!
Y0!
Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0! Y0!
Y0!
Y0!
Y0!
Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0! Y0!
Y0!
Y0!
Y0!
Y0! Y0! Y0! Y0! Y0!
Y0! Y0! Y0! Y0!
Y0! Y0!
Y0! Y0!

```

Order is `1234`/`LNSW` (letter, digit, symbol, whitespace).

Try it online (input as integer representing the unicode of a character).

**Explanation:**

Whitespace is a stack-based language where every character except for spaces, tabs and new-lines are ignored. Here is the same program without the `YO!` (**333 bytes**):

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input(9)][S N
S _Duplicate_input(10][S N
S _Duplicate_input(32)][S N
S _Duplicate_input(33-47)][S N
S _Duplicate_input(48-57)][S N
S _Duplicate_input(58-64)][S N
S _Duplicate_input(65-90)][S N
S _Duplicate_input(91-96)][S N
S _Duplicate_input(97-122)][S N
S _Duplicate_input(123-126)][S S S T    S S T   N
_Push_9][T  S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_WHITESPACE][S S S T S T S N
_Push_10][T S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_WHITESPACE][S S S T S S S S S N
_Push_32][T S S T   _Subtract][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_WHITESPACE][N
T   T   S T N
_If_negative_Jump_to_Label_NONE][S S S T    T   S S S S N
_Push_48][T S S T   _Subtract][N
T   T   N
_If_negative_Jump_to_Label_SYMBOL][S S S T  T   T   S T S N
_Push_58][T S S T   _Subtract][N
T   T   S S N
_If_negative_Jump_to_Label_DIGIT][S S S T   S S S S S T N
_Push_65][T S S T   _Subtract][N
T   T   N
_If_negative_Jump_to_Label_SYMBOL][S S S T  S T T   S T T   N
_Push_91][T S S T   _Subtract][N
T   T   T   N
_If_negative_Jump_to_Label_LETTER][S S S T  T   S S S S T   N
_Push_97][T S S T   _Subtract][N
T   T   N
_If_negative_Jump_to_Label_SYMBOL][S S S T  T   T   T   S T T   N
_Push_123][T    S S T   _Subtract][N
T   T   T   N
_If_negative_Jump_to_Label_LETTER][S S S T  T   T   T   T   T   T   N
_Push_127][T    S S T   _Subtract][N
T   T   N
_If_negative_Jump_to_Label_SYMBOL][N
S N
S T N
_Jump_to_Label_NONE][N
S S S N
_Create_Label_WHITESPACE][S S S T   S S N
_Push_4][T  N
S T _Print_as_integer][N
N
N
_Exit][N
S S N
_Create_Label_SYMBOL][S S S T   T   N
_Push_3][T  N
S T _Print_as_integer][N
N
N
_Exit][N
S S S S N
_Create_Label_DIGIT][S S S T    S N
_Push_2][T  N
S T _Print_as_integer][N
N
N
_Exit][N
S S T   N
_Create_Label_LETTER][S S S T   N
_Push_1][T  N
S T _Print_as_integer][N
N
N
_Exit][N
S S S T N
_Create_Label_NONE][S S S N
_Push_0][T  N
S T _Print_as_integer]

```

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

Try it online.

**Program in pseudo-code:**

```
If the input is 9, 10 or 32: call function WHITESPACE()
Else-if the input is below 32: call function NONE()
Else-if the input is below 48: call function SYMBOL()
Else-if the input is below 58: call function DIGIT()
Else-if the input is below 65: call function SYMBOL()
Else-if the input is below 91: call function LETTER()
Else-if the input is below 97: call function SYMBOL()
Else-if the input is below 123: call function LETTER()
Else-if the input is below 127: call function SYMBOL()
Else (the input is 127 or higher): call function NONE()

WHITESPACE():
  Print 4
  Exit program
SYMBOL():
  Print 3
  Exit program
DIGIT():
  Print 2
  Exit program
LETTER():
  Print 1
  Exit program
NONE():
  Print 0
  (Implicit exit with error: Exit not defined)

```
> 2 votes

---
Tags: code-golf, string, number, source-layout, printable-ascii
---


title: Pretty Print Polynomials

text:
# Question
Title: Pretty Print Polynomials
# Introduction

Humans are a remarkable species, but we can be very awkward to understand sometimes—especially for computers. In particular, we seem to like writing polynomials in a very convoluted fashion with seemingly arbitrary rules.

What is the shortest program you can write to format a polynomial correctly using these rules?

# Challenge

Input

> A list of integers between -1000 and 1000 (inclusive), representing the coefficients of a polynomial, with the last entry being the coefficient of x^0 (the constant), the second last being the coefficient of x^1, etc.

Output

> A string representing this polynomial in the correctly formatted mathematical notation of humans.

## Rules:

* The sign on the leading coefficient is only shown if it is negative.

`Right: -x^2+3`

`Wrong: +x^2+3`

* Components with coefficient of 0 are not printed (except for the corner case where all coefficients are 0\*).

`Right: x^5-x^2+3`

`Wrong: x^5+0x^4+0x^3-x^2+0x+3`

* Coefficients `-1` and `+1` are to be displayed without the 1, unless they are the constant.

`Right: x^5-x^2+1`

`Wrong: 1x^5-1x^2+1`

* The exponent is only shown if it is greater than 1 and the variable is only shown if the exponent is greater than 0.

`Right: 3x^3-7x^2+2x+1`

`Wrong: 3x^3-7x^2+2x^1+1x^0`

* \*Corner case: while zero values usually result in not printing that component, if all coefficients are zero the constant 0 should be printed.

`Right: 0`

`Wrong: 0x+0`

`Wrong: (nothing)`

* This is code-golf so the winner will be the program with the fewest bytes.

# Example Input and Output

```
Input:                  Output:
      [0]                      0
      [0,0]                    0
      [0,-1,35,0]             -x^2+35x
      [5,1,7,-9]               5x^3+x^2+7x-9
      [100,0,0,-1]             100x^3-1
      [931,21,-11,1]           931x^3+21x^2-11x+1

```

I look forward to seeing your solutions. Have fun!

# EDIT:

* You can surround operations by whitespace if you wish. So `3x+5` and `3x + 5` are both fine. `3x+ 5` and `3x +5` are not.
* If you want to produce actual exponent characters (say in Tex) that is allowed as it is even closer to how humans write.
* Coefficients must appear without any decimals e.g. `9x^2` is correct, `9.0x^2` is not.

# Answer
> 10 votes
# Retina 0.8.2, 56 bytes

```
(?=( \S+)+)
x^$#1
\b0x.\d+

\b1x
x
x.1
x
 0

 -
-

+

```

Try it online! Link includes test cases. Explanation:

```
(?=( \S+)+)
x^$#1

```

Insert all of the powers of `x`, including `x^1` but not `x^0`.

```
\b0x.\d+

```

Delete all powers of `x` with zero coefficients, but not a trailing `0` (yet).

```
\b1x
x

```

Delete a multiplier of `1` (but not a constant `1`).

```
x.1
x

```

Delete the `^1` of `x^1`.

```
 0

```

Delete a constant 0 unless it is the only thing left.

```
 -
-

```

Delete the space before a `-`.

```

+

```

Change any remaining spaces to `+`s.

# Answer
> 6 votes
# JavaScript (ES6), ~~107~~ 106 bytes

```
a=>a.map(c=>c?s+=(c>0&&s?'+':_)+(!--e|c*c-1?c:c<0?'-':_)+(e?e-1?'x^'+e:'x':_):e--,e=a.length,_=s='')&&s||0

```

Try it online!

### How?

The output is built by applying the following formulas to each coefficient **c** of the input array **a\[ \]** while keeping track of the current exponent **e**.

**1st formula: plus sign**

If the coefficient is strictly positive and this is not the first term in the output expression, we append a `+`. Otherwise, we append nothing.

```
c > 0 && s ? '+' : _

```

**2nd formula: minus sign and coefficient**

If the exponent is zero or the absolute value of the coefficient is not equal to 1, we append the coefficient (which may include a leading `-`). Otherwise, we append either a `-` (if the coefficient is negative) or nothing.

```
!--e | c * c - 1 ? c : c < 0 ? '-' : _

```

**3rd formula: variable and exponent**

If the exponent is 0, we append nothing. If the exponent is 1, we append `x`. Otherwise, we append `x^` followed by the exponent.

```
e ? e - 1 ? 'x^' + e : 'x' : _

```

# Answer
> 5 votes
# Python 3, ~~279~~ ~~277~~ ~~258~~ 251 bytes

```
k=str.replace
def f(x):
 z=len(x)
 y='--'*(['-1']==[c for c in x if'0'!=c][:1])
 for i,v in enumerate(x):
  p=str(z+~i)
  if v in'-1'and~i+z:y+='+x^'+p
  elif'0'!=v:y+='+'+v+'x^'+p
 return y and k(k(k(k(y[1:],'+-','-'),'^1',''),'x^0',''),'-+','-')or 0

```

Takes input as a list of strings. This solution is not highly golfed yet. This basically works by replacing things to suit the output format, which highly increases the byte count.

Try It Online!

*Special thanks to ovs and NK1406*.

# Answer
> 5 votes
# Stax, 37 bytes

```
┴₧↕ê♦•Vªâÿσ9s╘dσ■à@@ⁿ■o─╦ñºº┌x╡ER▓ δ¿

```

Run and debug it online

Here's the unpacked, ungolfed version.

```
r{          reverse the input and map using block ...
  |c        skip this coefficient if it's falsy (zero)
  0<.+-@    sign char; e.g. '+'
  _|aYv i!+ abs(coeff)!=1 || i>0
    y$      str(abs(coeff)); e.g. '7'
    z       ""
  ?+        if-then-else, concatenate; e.g. '+7'
  "x^`i"    string template e.g. 'x^3' or 'x^0'
  iJ(T+     truncate string at i*i and trim. e.g. 'x^3' or ''
mr$         re-reverse mapped array, and flatten to string
c43=t       if it starts with '+', drop the first character
c0?         if the result is blank, use 0 instead

```

Run this one

# Answer
> 4 votes
# APL (Dyalog Classic), ~~114~~ ~~113~~ ~~109~~ ~~107~~ 106 bytes

```
{{⍵≡'':⍕0⋄⍵↓⍨'+'=⊃⍵}∊⍵{{'1x'≡2↑1↓⍵:¯1⌽1↓1⌽⍵⋄⍵}('-0+'[1+×⍺]~⍕0),∊(U/⍕|⍺),(U←⍺≠0)/(⍵>⍳2)/¨'x'('^',⍕⍵)}¨⌽⍳⍴⍵}

```

Try it online!

-4 bytes thanks to @dzaima!

This can definitely be golfed down further. This requires `⎕IO←0`

# Answer
> 4 votes
# Pari/GP, 41 bytes

```
p->concat([c|c<-Vec(Str(Pol(p))),c!="*"])

```

Try it online!

---

If an `*` between the coefficient and the variable is allowed:

# Pari/GP, 3 bytes

```
Pol

```

Try it online!

# Answer
> 3 votes
# Pip, 78 bytes

```
(RV(B."x^"._MERVg)J'+)R[`\b0[^+]+``x.0|\^1|^\++|\++$``\b1x``\++-?`][xx'x_@v]|0

```

Takes the coefficients as command-line arguments. Try it online!

Uses `ME` (map-enumerate) and `J` (join) to generate something of the form `0x^3+-1x^2+35x^1+0x^0`, and then a bunch of regex replacements to transform this into the proper format.

# Answer
> 3 votes
# Clean, 172 bytes

```
import StdEnv,Text
r=reverse
@""="0"
@a|a.[size a-1]<'0'=a+"1"=a
? -1="-"
?1=""
?a=a<+""
$l=join"-"(split"+-"(join"+"(r[?v+e\\v<-r l&e<-["","x":map((<+)"x^")[1..]]|v<>0])))

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-a`, 94 bytes

```
($_=shift@F)&&push@a,@a*!/-/>0&&'+',@F?s/\b1\b//r:$_,@F>0&&'x',@F>1&&'^'.@F while@F;say@a?@a:0

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Classic), ~~79~~ 76 bytes

```
{'^$' '\b1x' '\+?¯' '^\+'⎕r('0x-',⊂⍬)∊⍕¨(0≠⍵)⌿'+',⍵,⊖⍪((⊢↓⍨2≤⊢)↑'x^',⍕)¨⍳≢⍵}

```

Try it online!

# Answer
> 3 votes
# Wolfram Language/Mathematica, 39 bytes

```
TraditionalForm@Expand@FromDigits[#,x]&

```

Try it online!

Turns out there is a built-in to get in in the right order.

Previous solution:

## Wolfram Language/Mathematica, 93 bytes

```
StringReplace[StringRiffle[ToString/@InputForm/@MonomialList@FromDigits[#,x],"+"],"+-"->"-"]&

```

~~At least to me, this is suprisingly long for a language designed for mathematical manipulation. It seems like `Expand@FromDigits[#,x]&` should work, but the default ordering for polynomials is the reverse of what the question requires, so some extra finagling is required.~~

### Explanation

```
FromDigits[#,x]               converts input list to polynomial (technically converts to a number in base x)
MonomialList@                 gets list of terms of polynomial
InputForm/@                   converts each term to the form a*x^n
ToString/@                    then to a string version of that
StringRiffle[...,"+"]         joins using +'s
StringReplace[...,"+-"->"-"]& replaces +-'s with -'s

```

# Answer
> 3 votes
# Python 3, 161 162 bytes

*Fixed a bug thanks to ovs.*

```
l=len
lambda p:''.join(['+'*(i>0)*(c>0)+(str(c)[:-1],str(c))[abs(c)!=1or i==l(p)-1]+'x'*(i!=l(p)-1)+('^%d'%(l(p)+~i))*(i<l(p)-2)for i,c in enumerate(p)if c])or'0'

```

Expanded:

```
l=len # Alias the len function since we use it a lot
lambda p: ''.join([ # Join a list of strings
    '+'*(i>0)*(c>0) # Prepend a + if this isn't the first term and the coefficient is positive
    + (str(c)[:-1], str(c))[abs(c) != 1 or i == l(p) - 1] # If the coefficient is 1 and this isn't the last term, delete the '1' from the string representation, otherwise just use the string representation
    + 'x' * (i != l(p) - 1) # If this isn't the last term, append an x
    + ('^%d' % (l(p) + ~i)) * (i < l(p) - 2) # If this isn't one of the last two terms, append the exponent
for i, c in enumerate(p) if c]) # Iterating over each coefficient with its index, discarding the term if the coefficient is zero
or '0' # If all of the above resulted in an empty string, replace it with '0'

```

# Answer
> 3 votes
Python3: ~~150~~ 146 bytes

```
f=lambda l:''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1]for i,a in zip(range(len(l)-1,-1,-1),l)if a).lstrip('+')or '0'

```

(previous implementations):

```
f=lambda l: ''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1] for i,a in zip(range(len(l)-1,-1,-1),l) if a).lstrip('+') or '0'

```

You can *try it online*

Kudos to: @Benjamin

# Answer
> 3 votes
# C#, 237 bytes

```
c=>{var b=1>0;var r="";int l=c.Length;var p=!b;for(int i=0;i<l;i++){int n=c[i];int e=l-1-i;var o=p&&i>0&&n>0?"+":n==-1&&e!=0?"-":"";p=n!=0?b:p;r+=n==0?"":o+(e==0?$"{n}":e==1?$"{n}x":n==1||n==-1?$"x^{e}":$"{n}x^{e}");}return r==""?"0":r;}

```

# Answer
> 2 votes
# Retina 0.8.2, 113 bytes

```
\w+
a$'b$&
a( [^b ]*)*?b(\d+)
$2x^$#1
(\^1|x\^0)(?!\d)

(?<= |-|^)(1(?=x)|0[^ -]*)

([ -])*
$1
[ -]$|^

^$
0

+

```

Try it online!

I'm sure there is a lot to golf here...

# Answer
> 2 votes
# Haskell, ~~166~~ 163 bytes

```
g s|l<-length s,v:w:r<-id=<<["- +"!!(1+signum m):(id=<<[show$abs m|abs m>1||e==0]++["x"|e>0]++['^':show e|e>1])|(e,m)<-zip[l-1,l-2..]s,m/=0]=[v|v>'+']++w:r|1<3="0"

```

Try it online! Example usage: `g [0,-1,35,0]` yields `"-x^2+35x"`.

---

Previous 166 byte solution, which is slightly better readable:

```
0#n=show n
m#n=id=<<[show n|n>1]++"x":['^':show m|m>1]
m%0=""
m%n|n<0='-':m#(-n)|1<3='+':m#n
g s|l<-length s,v:m:r<-id=<<zipWith(%)[l-1,l-2..]s=[v|v>'+']++m:r|1<3="0"

```

Try it online!

# Answer
> 2 votes
# Java 8, ~~202~~ ~~176~~ ~~174~~ 173 bytes

```
a->{String r="";int j=a.length;for(int i:a)r+=i==0*j--?"":"+"+i+(j<1?"":j<2?"x":"x^"+j);return r.isEmpty()?"0":r.substring(1).replace("+-","-").replaceAll("(\\D)1x","$1x");}

```
* 26 bytes thanks to *@Nevay*.

**Explanation:**

Try it online.

```
a->{                     // Method with String-array parameter and String return-type
  String r="";           //  Result-String, starting empty
  int j=a.length;        //  Power-integer, starting at the size of the input-array
  for(int i:a)           //  Loop over the array
    r+=i==0              //   If the current item is 0
           *j--?         //   (And decrease `j` by 1 at the same time)
        ""               //    Append the result with nothing
       :                 //   Else:
        "+"              //    Append the result with a "+",
        +i               //    and the current item,
        +(j<1?           //    +If `j` is 0:
           ""            //      Append nothing more
          :j<2?          //     Else-if `j` is 1:
           "x"           //      Append "x"
          :              //     Else:
           "x^"+j);      //      Append "x^" and `j`
  return r.isEmpty()?    //  If `r` is still empty
    "0"                  //   Return "0"
   :                     //  Else:
    r.substring(1)       //   Return the result minus the leading "+",
     .replace("+-","-")  //   and change all occurrences of "+-" to "-",
     .replaceAll("(\\D)1x","$1x");}
                         //   and all occurrences of "1x" to "x"

```

# Answer
> 2 votes
# Husk, ~~44 43 41~~ 40 bytes

```
|s0Ψf¤|□ṁ`:'+f¹zμ+↓s²_&ε²¹↑□¹+"x^"s)¹m←ṡ

```

Try it online!

This feels a bit clunky; Husk is not optimized for string manipulation. I borrowed some ideas from the Stax answer.

## Explanation

```
         Implicit input, say L = [2,-3,0,-1].
         First we compute the exponents.
ṡ        Reversed indices: [4,3,2,1]
m←       Decrement each: [3,2,1,0]
         Then we format the individual terms of the polynomial.
zμ...)¹  Zip with L using two-argument lambda:
          Arguments are coefficient and index, say C = -3 and I = 2.
+"x^"s    Convert I to string and concatenate to "x^": "x^2"
↑□¹       Take first I*I characters (relevant when I = 0 or I = 1): "x^2"
_&ε²¹     Check if abs(C) <= 1 and I != 0, negate; returns -1 if true, 0 if false.
↓s²       Convert C to string and drop that many elements (from the end, since negative).
          Result: "-3"
          The drop is relevant if C = 1 or C = -1.
+         Concatenate: "-3x^2"
         Result of zipping is ["2x^3","-3x^2","x","-1"]
f¹       Keep those where the corresponding element of L is nonzero: ["2x^3","-3x^2","-1"]
         Next we join the terms with + and remove extraneous +s.
ṁ        Map and concatenate
`:'+      appending '+': "2x^3+-3x^2+-1+"
Ψf       Adjacent filter: keep those chars A with right neighbor B
¤|□       where at least one of A or B is alphanumeric: "2x^3-3x^2-1"
|s0      Finally, if the result is empty, return "0" instead.

```

# Answer
> 2 votes
# Ruby, 111 bytes

```
->a{i=a.size;s=a.map{|x|i-=1;"%+d"%x+[?x,"x^#{i}",""][i<=>1]if x!=0}*'';s[0]?s.gsub(/(?<!\d)1(?=x)|^\+/,""):?0}

```

Try it online!

Solving this in Ruby turned out to be a bit frustrating, mainly due to the fact that unlike most languages, in Ruby (almost) everything is truthy, including 0-s and empty strings, so that even a simple check for zero becomes nowhere near as short as `x?`.

I played with various methods of constructing the string, and ultimately settled on a mix of several approaches:

* Terms with 0 coefficients are dropped using a simple conditional
* `+` and `-` signs are produced by formatting syntax with forced sign: `%+d`
* The correct form or `x^i` is selected using rocket operator indexing `[...][i<=>1]`
* Leading + and unnecessary 1-s are removed by regex replacements

# Answer
> 2 votes
# Perl 6, 97 bytes

```
{$!=+$_;.map({('+'x?($_&&$++&$_>0)~.substr(--$!&&2>.abs)~(<<''x>>[$!]//'x^'~$!))x?$_}).join||'0'}

```

Try it online!

Explanation:

```
$!=+$_;

```

`$!` keeps track of the current exponent.

```
'+'x?($_&&$++&$_>0)

```

Add `+` before positive coefficients, except if it's the first non-zero one. The `$_&&` short circuit makes sure that the anonymous state variable `$` is only incremented for non-zero coefficients. The `&` junction is collapsed when coerced to Bool with `?`.

```
.substr(--$!&&2>.abs)

```

Decrement `$!`. Chop 1 or -1 coefficient unless it's constant.

```
<<''x>>[$!]//'x^'~$!

```

Special-case linear and constant terms. Using the quote-protecting `<< >>` construct is one byte shorter than the equivalent `('','x')` or `2>$!??'x'x$!!!'x^'~$!`.

```
x?$_

```

Hide zero terms, but always evaluate the preceding expression for the `--$!` side effect.

```
||'0'

```

Return `0` if all coefficients are zero.

# Answer
> 2 votes
# Python, 165 bytes

```
lambda a:"".join([("+"if c>0 and i+1<len(a)else"")+(str(c)if i==0 or abs(c)!=1 else "")+{0:"",1:"x"}.get(i,"x^"+str(i))for i,c in enumerate(a[::-1])if c][::-1])or"0"

```

# Answer
> 1 votes
## PHP, 213 Bytes

```
$p=0;for($i=count($a=array_reverse(explode(',',trim($argv[1],'[]'))))-1;$i>=0;$i--)if(($b=(float)$a[$i])||(!$i&&!$p)){$k=abs($b);echo ($b<0?'-':($p?'+':'')).((($k!=1)||!$i)?$k:'').($i>1?'x^'.$i:($i?'x':''));$p=1;}

```

Command line argument as requested by OP (single argument with brackets and commas).

Pretty print and some explanation:

```
$p = false; /* No part of the polynomial has yet been printed. */
for ($i = count($a = array_reverse(explode(',',trim($argv[1],'[]')))) - 1; $i >= 0; $i--)
{
    $b = (float)$a[$i]; /* Cast to float to avoid -0 and numbers like 1.0 */
    if (($b != 0) or (($i == 0) and !$p)) /* Print, if $b != 0 or the constant if there is no part until here. */
    {
        $k = abs($b);
        echo ($b < 0 ? '-' : ( $p ? '+' : '')); /* Sign. The first sign is suppressed (if $p is false) if $b positive. */
        echo ((($k != 1) || ($i == 0)) ? $k : '');  /* Coefficient */
        echo ($i > 1 ? 'x^' . $i : (($i != 0) ? 'x' : ''));  /* x^3, x^2, x, constant with empty string. */
        $p = true; /* Part of the polynomial has been printed. */
    }
}

```

# Answer
> 1 votes
# PowerShell, 295 bytes

```
$c=$args[0]
$p=$c.length-1
$i=0
$q=""
while($p -ge 0){$t="";$e="";$d=$c[$i];switch($p){0{$t=""}1{$t="x"}Default{$t="x^";$e=$p}}if($d-eq 0){$t=""}elseif($d-eq 1){$t="+$t$e"}elseif($d-eq-1){$t="-$t$e"}elseif($d-lt 0 -or$i -eq 0){$t="$d$t$e"}else{$t="+$d$t$e"}$q+=$t;$i++;$p--}if($q -eq""){$q=0}
$q

```

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


title: Remove duplicates from a String

text:
# Question
Title: Remove duplicates from a String
Inspired by this unassuming StackOverflow question.

The idea is simple; given a String and an array of Strings, remove any instances of words in the array (ignoring case) from the input String other than the first, along with any additional whitespace this may leave. The words must match entire words in the input String, and not parts of words.

e.g. `"A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", ["cat", "mat"]` should output `"A cat called matt sat on a mat and wore a hat A called matt sat on a and wore a hat"`

## Input

* Input can be taken as either a String, and an array of Strings or an array of Strings where the input String is the first element. These parameters can be in either order.
* The input String may not be taken as a list of space-delimited Strings.
* The input String will have no leading, trailing or consecutive spaces.
* All input will only contain characters \[A-Za-z0-9\] with the exception of the input String also including spaces.
* The input array may be empty or contain words not in the input String.

## Output

* The output can either be the return value from a function, or printed to STDOUT
* The output must be in the same case as the original String

## Test cases

```
the blue frog lived in a blue house, [blue] -> the blue frog lived in a house
he liked to read but was filled with dread wherever he would tread while he read, [read] -> he liked to read but was filled with dread wherever he would tread while he
this sentence has no matches, [ten, cheese] -> this sentence has no matches
this one will also stay intact, [] -> this one will also stay intact
All the faith he had had had had no effect on the outcome of his life, [had] -> All the faith he had no effect on the outcome of his life
5 times 5 is 25, [5, 6] -> 5 times is 25
Case for different case, [case] -> Case for different
the letters in the array are in a different case, [In] -> the letters in the array are a different case
This is a test Will this be correct Both will be removed, [this,will] -> This is a test Will be correct Both be removed

```

As this is code golf, lowest byte count wins!

# Answer
# , 84 bytes

```
function(s,w,S=el(strsplit(s," ")),t=tolower)cat(S[!duplicated(x<-t(S))|!x%in%t(w)])

```

Try it online!

Less than 100 bytes on a challenge that's not also ?

Explanation:

After we break up the string into words, we need to exclude those that are

1. duplicates and
2. in `w`

or alternatively, turning that on its head, keeping those that are

1. the first occurrence of a word OR
2. not in `w`.

`duplicated` neatly returns logical indices of those that are not the first occurrence, so `!duplicated()` returns indices of those which are first occurrences, and `x%in%w` returns logical indices for `x` of those which are in `w`. Neat.
> 9 votes

# Answer
# Java 8, ~~117~~ 110 bytes

```
a->s->{for(String x:a)for(x="(?i)(.*"+x+".* )"+x+"( |$)(.*)";s.matches(x);s=s.replaceAll(x,"$1$3"));return s;}

```

**Explanation:**

Try it online.

```
a->s->{                // Method with String-array and String parameters and String return
  for(String x:a)      //  Loop over the input-array
    for(x="(?i)(.*"+x+".* )"+x+"( |$)(.*)";
                       //   Regex to match
        s.matches(x);  //   Inner loop as long as the input matches this regex
      s=s.replaceAll(x,"$1$3"));
                       //    Replace the regex-match with the 1st and 3rd capture groups
  return s;}           //  Return the modified input-String

```

Additional explanation for the regex:

```
(?i)(.*"+x+".* )"+x+"( |$)(.*)   // Main regex to match:
(?i)                             //  Enable case insensitivity
    (                            //  Open capture group 1
     .*                          //   Zero or more characters
       "+x+"                     //   The input-String
            .*                   //   Zero or more characters, followed by a space
               )                 //  End of capture group 1
                "+x+"            //  The input-String again
                     (           //  Open capture group 2
                       |$        //   Either a space or the end of the String
                         )       //  End of capture group 2
                          (      //  Open capture group 3
                           .*    //   Zero or more characters
                             )   //  End of capture group 3

$1$3                             // Replace the entire match with:
$1                               //  The match of capture group 1
  $3                             //  concatted with the match of capture group 3

```
> 6 votes

# Answer
# MATL, ~~19~~ 18 bytes

```
"Ybtk@kmFyfX<(~)Zc

```

Inputs are: a cell array of strings, then a string.

Try it online! Or verify all test cases.

### How it works

```
"        % Take 1st input (implicit): cell array of strings. For each
  Yb     %   Take 2nd input (implicit) in the first iteration: string; or
         %   use the string from previous iteration. Split on spaces. Gives
         %   a cell array of strings
  tk     %   Duplicate. Make lowercase
  @k     %   Push current string from the array taken as 1st input. Make
         %   lowercase
  m      %   Membership: gives true-false array containing true for strings
         %   in the first input argument that equal the string in the second
         %   input argument
  F      %   Push false
  y      %   Duplicate from below: pushes the true-false array again
  f      %   Find: integer indices of true entries (may be empty)
  X<     %   Minimum (may be empty)
  (      %   Assignment indexing: write false in the true-false array at that
         %   position. So this replaces the first true (if any) by false
  ~      %   Logical negate: false becomes true, true becomes false
  )      %   Reference indexing: in the array of (sub)strings that was
         %   obtained from the second input, keep only those indicated by the
         %   (negated) true-false array
  Zc     %   Join strings in the resulting array, with a space between them
         % End (implicit). Display (implicit)

```
> 4 votes

# Answer
## Perl 5, 49 bytes

```
@B=<>;$_=join$",grep!(/^$_$/xi~~@B&&$v{+lc}++),@F

```

Try it online!

Saved 9 (!!) bytes thanks to @TonHospel!
> 3 votes

# Answer
# Pyth, 27 bytes

```
jdeMf!}r0eT@mr0dQmr0dPT._cz

```

Try it online

### Explanation

```
jdeMf!}r0eT@mr0dQmr0dPT._cz
                          z  Take the string input.
                       ._c   Get all the prefixes...
    f    eT@                 ... which end with something...
     !}         Q    PT      ... which is not in the input and the prefix...
       r0   mr0d mr0d        ... case insensitive.
jdeM                         Join the ends of each valid prefix.

```

I'm sure the 10 bytes for case insensitive check can be reduced, but I don't see how.
> 2 votes

# Answer
# Stax, 21 bytesCP437

```
åìøΓ²¬$M¥øHΘQä~╥ôtΔ♫╟

```

25 bytes when unpacked,

```
vjcm[]Ii<;e{vm_]IU>*Ciyj@

```

The result is an array. The convenient output for Stax is one element per line.

Run and debug online!

## Explanation

```
vj                           Convert 1st input to lowercase and split at spaces,
  c                          Duplicate at the main stack
   m                         Map array with the rest of the program
                                 Implicitly output
    []I                      Get the first index of the current array element in the array
       i<                    Test 1: The first index is smaller than the iteration index
                                 i.e. not the first appearance
         ;                   2nd input
          {vm                Lowercase all elements
             _]I             Index of the current element in the 2nd input (-1 if not found)
                U>           Test 2: The index is non-negative
                                 i.e. current element is a member of the 2nd input
                  *C         If test 1 and test 2, drop the current element
                                 and go on mapping the next
                    iyj@     Fetch the corresponding element in the original input and return it as the mapped result
                                 This preserves the original case

```
> 2 votes

# Answer
# Perl 6, 49 bytes

```
->$_,+w{~.words.grep:{.lc∉w».lc||!(%){.lc}++}}

```

Test it

## Expanded:

```
->              # pointy block lambda
  $_,           # first param ｢$_｣ (string)
  +w            # slurpy second param ｢w｣ (words)
{

  ~             # stringify the following (joins with spaces)

  .words        # split into words (implicit method call on ｢$_｣)

  .grep:        # take only the words we want

   {
     .lc        # lowercase the word being tested
     ∉          # is it not an element of
     w».lc      # the list of words, lowercased

     ||         # if it was one of the words we need to do a secondary check

     !          # Boolean invert the following
                # (returns true the first time the word was found)

     (
       %        # anonymous state Hash variable
     ){ .lc }++ # look up with the lowercase of the current word, and increment
   }
}

```
> 2 votes

# Answer
# Perl 5, ~~50~~ 48 bytes

Includes `+1` for `-p`

Give the target string followed by each filter word on separate lines on STDIN:

```
perl -pe '$"="|";s%\b(@{[<>]})\s%$&x!$v{lc$1}++%iegx;chop';echo
This is a test Will this be correct Both will be removed
this
will
^D
^D

```

The `chop` is only needed to fix the trailing space in case the last word gets removed

Just the code:

```
$"="|";s%\b(@{[<>]})\s%$&x!$v{lc$1}++%iegx;chop

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), 98 bytes

```
s=>a=>s.split` `.filter(q=x=>(q[x=x.toLowerCase()]=eval(`/\\b${x}\\b/i`).test(a)<<q[x])<2).join` `

```
> 1 votes

# Answer
# K4, 41 bytes

**Solution:**

```
{" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}

```

**Examples:**

```
q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat";("cat";"mat")]
"A cat called matt sat on a mat and wore a hat A called matt sat on a and wore a hat"

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["Case for different case";enlist "case"]
"Case for different"

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["the letters in the array are in a different case";enlist "In"]
"the letters in the array are a different case"

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["5 times 5 is 25";(1#"5";1#"6")]
"5 times is 25"

```

**Explanation:**

Split on whitespace, lowercase both inputs, look for matches, remove all but the first occurrence, join the string back together.

```
{" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x} / the solution
{                                       } / lambda with implicit x & y args
                                  " "\:x  / split (\:) on whitespace " "
                                x:        / save result as x
                               _          / lowercase x
                          ~/:\:           / match (~) each right (/:), each left (\:)
                      (_y)                / lowercase y
                   &:'                    / where (&:) each ('), ie indices of matches
                1_'                       / drop first of each result
              ,/                          / flatten
            y:                            / save result as y
         y@>                              / descending indices (>) apply (@) to y
      x_/                                 / drop (_) from x
 " "/:                                    / join (/:) on whitespace " "

```
> 1 votes

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

```
f=(s,a)=>a.map(x=>s=s.replace(eval(`/\\b${x}\\b */ig`),s=>i++?"":s,i=0))&&s

```

Try it online!
> 1 votes

# Answer
# JavaScript ES6, 78 Bytes

```
f=(s,a,t={})=>s.split` `.filter(w=>a.find(e=>w==e)?(t[w]?0:t[w]=1):1).join` `

```

How it works:

```
f=(s,a,t={})=> // Function declaration; t is an empty object by default
s.split` ` // Split the string into an array of words
.filter(w=> // Declare a function that, if it returns false, will delete the word
  a.find(e=>w==e) // Returns undeclared (false) if the word isn't in the list
  ?(t[w]?0 // If it is in the list and t[w] exists, return 0 (false)
    :t[w]=1) // Else make t[w] exist and return 1 (true)
  :1) // If the word isn't in the array, return true (keep the word for sure)
.join` ` // Rejoin the string

```
> 1 votes

# Answer
# Retina, ~~46~~ 37 bytes

```
+i`(^|,)((.+),.*\3.* )\3( |$)
$2
.*,

```

-14 bytes thanks to *@Neil*, and +5 bytes for a bug-fix.

Input in the format `word1,word2,word3,sentence`, because I'm not sure how to have multi-line input (where the inputs are used differently)..

**Explanation:**

Try it online.

```
+i`(^|,)((.+),.*\3.* )\3( |$)   Main regex to match:
+i`                              Enable case insensitivity
   (^|,)                          Either the start of the string, or a comma
        (                         Open capture group 2
         (                         Open capture group 3
          .+                        1 or more characters
            )                      Close capture group 3
             ,                     A comma
              .*                   0 or more characters
                \3                 The match of capture group 3
                  .*               0 or more characters, followed by a space
                     )            Close capture group 2
                      \3          The match of capture group 2 again
                        ( |$)     Followed by either a space, or it's the end of the string
$2                              And replace everything with:
                                 The match of capture group 2

.*,                             Then get everything before the last comma (the list)
                                 and remove it (including the comma itself)

```
> 0 votes

# Answer
# PowerShell v3 or later, 104 bytes

```
Param($s,$w)$w|?{$_-and$s-match($r="\b$_(?: |$)")}|%{$h,$t=$s-split$r;$s="$h$($Matches.0)$(-join$t)"};$s

```

At the cost of one byte, it can run in PS 2.0 by replacing `$Matches.0` with `$Matches[0]`.

**Long version:**

```
Param($s, $w)
$w | Where-Object {$_ -and $s -match ($r = "\b$_(?: |$)")} |    # Process each word in the word list, but only if it matches the RegEx (which will be saved in $r).
    ForEach-Object {                                            # \b - word boundary, followed by the word $_, and either a space or the end of the string ($)
        $h, $t = $s -split $r                                   # Split the string on all occurrences of the word; the first substring will end up in $h(ead), the rest in $t(ail) (might be an array)
        $s = "$h$($Matches.0)$(-join $t)"                       # Create a string from the head, the first match (can't use the word, because of the case), and the joined tail array
    }
$s                                                              # Return the result

```

**Usage**
Save as Whatever.ps1 and call with the string and the words as arguments. If more than one word needs to be passed, the words need to be wrapped in @():

```
.\Whatever.ps1 -s "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat" -w @("cat", "mat")

```

**Alternative** without file (can be pasted directly into a PS console):
Save the script as ScriptBlock (inside curly braces) in a variable, then call its Invoke() method, or use it with Invoke-Command:

```
$f={Param($s,$w)$w|?{$_-and$s-match($r="\b$_(?: |$)")}|%{$h,$t=$s-split$r;$s="$h$($Matches.0)$(-join$t)"};$s}
$f.Invoke("A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", @("cat", "mat"))
Invoke-Command -ScriptBlock $f -ArgumentList "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", @("cat", "mat")

```
> 0 votes

# Answer
# Javascript, 150 bytes

```
s=(x, y)=>{let z=new Array(y.length).fill(0);let w=[];for(f of x)(y.includes(f))?(!z[y.indexOf(f)])&&(z[y.indexOf(f)]=1,w.push(f)):w.push(f);return w}

```
> 0 votes

# Answer
# Clean, ~~153~~ ~~142~~ ~~138~~ 134 bytes

```
import StdEnv,StdLib,Text
@ =toUpperCase
$s w#s=split" "s
=join" "[u\\u<-s&j<-[0..]|and[i<>j\\e<-w,i<-drop 1(elemIndices(@e)(map@s))]]

```

Try it online!

Defines the function `$ :: String [String] -> String`, pretty much literally doing what the challenge describes. It finds and removes every occurrence after the first, for each target word.
> 0 votes

# Answer
# Red, 98 bytes

```
func[s w][foreach v w[parse s[thru[any" "v ahead" "]any[to remove[" "v ahead[" "| end]]| skip]]]s]

```

Try it online!

```
f: func [s w][
    foreach v w [                   ; for each string in the array
        parse s [                   ; parse the input string as follows:
            thru [                  ; keep everything thru:
                any " "             ; 0 or more spaces followed by
                v                   ; the current string from the array followed by
                ahead " "           ; look ahead for a space
            ]
            any [ to remove [       ; 0 or more: keep to here; then remove:
                " "                 ; a space followed by
                v                   ; the current string from the array
                ahead [" " | end]]  ; look ahead for a space or the end of the string
            | skip                  ; or advance the input by one
            ]
        ]
    ]
    s                               ; return the processed string
]

```
> 0 votes

# Answer
# Husk, 13 bytes

```
wüöVËm_Ṗ3+⁰ew

```

Takes a list of strings and a single string as arguments, in this order. Assumes that the list is duplicate-free. Try it online!

## Explanation

```
wüöVËm_Ṗ3+⁰ew  Inputs: list of strings L (explicit, accessed with ⁰), string S (implicit).
               For example, L = ["CASE","for"], s = "Case for a different case".
            w  Split S on spaces: ["Case","for","a","different","case"]
 ü             Remove duplicates wrt an equality predicate.
               This means that a function is called on each pair of strings,
               and if it returns a truthy value, the second one is removed.
  öVËm_Ṗ3+⁰e    The predicate. Arguments are two strings, say A = "Case", B = "case".
           e    Put A and B into a list: ["Case","case"]
         +⁰     Concatenate with L: ["CASE","for","Case","case"]
       Ṗ3       All 3-element subsets: [["CASE","for","Case"],["CASE","for","case"],
                                        ["CASE","Case","case"],["for","Case","case"]]
  öV            Does any of them satisfy this:
    Ë            All strings are equal
     m_          after converting each character to lowercase.
                In this case, ["CASE","Case","case"] satisfies the condition.
               Result: ["Case","for","a","different"]
w              Join with spaces, print implicitly.

```
> 0 votes

# Answer
# Min, 125 bytes

```
=a () =b a 1 get =c a 0 get " " split
(:d (b d in?) ((c d in?) (d b append #b) unless) (d b append #b) if) foreach
b " " join

```

Input is `quot` on stack with input String as first element, and a `quot` of the duplicate strings as second element, i.e.

```
("this sentence has no matches" ("ten" "cheese"))

```
> 0 votes

# Answer
# Ruby, ~~63 61 60~~ 59 bytes

```
->s,w{w.any?{|i|s.sub! /\b(#{i}\b.*) #{i}\b/i,'\1'}?redo:s}

```

Try it online!

### A shorter version that's case sensitive and fails ~every 1015 times because of randomness (37 bytes)

```
->s,w{s.uniq{|i|w.member?(i)?i:rand}}

```
> 0 votes

# Answer
# Python 3, 168 bytes

```
def f(s,W):
 s=s.split(" ");c={w:0for w in W}
 for w in W:
  for i,v in enumerate(s):
   if v.lower()==w.lower():
    c[w]+=1
    if c[w]>1:s.pop(i)
 return" ".join(s)

```

Try it online!
> 0 votes

# Answer
# AWK, 120 bytes

```
NR%2{for(;r++<NF;)R[tolower($r)]=1}NR%2==0{for(;i++<NF;$i=$(i+s))while(R[x=tolower($(i+s))])U[x]++?++s:i++;NF-=s}NR%2==0

```

Try it online!

The "remove whitespace" part made this a bit more challenging than I first thought. Setting a field to `""`, removes a field, but leaves an extra separator.

The TIO link has 28 extra bytes to allow multiple entries.

Input is given over 2 lines. The first line is the list of words and the second is the "sentence". Note that "word" and "word," are not considered identical do to the attached punctuation. Having punctuation requirements would likely make this an even more *fun* problem.
> 0 votes

# Answer
# Python 2, 140 bytes

```
from re import*
p='\s?%s'
S,A=input()
for a in A:S=sub(p%a,lambda s:s.end()==search(p%a,S,flags=I).end()and s.group()or'',S,flags=I)
print S

```

Try it online!

Explanation:

`re.sub(..)` can take as argument a function instead of replacement string. So here we have some fancy lambda. Function is called for each occurence of pattern and one object is passed to this function - matchobject. This object has information about founded occurence. I'm interested in index of this occurence, that can be retrieved by `start()` or `end()` function. Latter is shorter so it is used.

To exclude replacement of first occurence of word, I used another regex search function to get exactly firts one and then compare indexes, using same `end()`

Flag `re.I` is short version of `re.IGNORECASES`
> 0 votes

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


title: Limit your numbers by your runs

text:
# Question
Title: Limit your numbers by your runs
## Self-limiting lists

Consider a nonempty list **L** containing nonnegative integers. A *run* in **L** is a contiguous sublist of equal elements, which cannot be made longer. For example, the runs of **\[0,0,1,1,3,3,3,2,1,1\]** are **\[0,0\], \[1,1\], \[3,3,3\], \[2\], \[1,1\]**. The list **L** is *self-limiting* if for each integer **N ≥ 1**, the number of occurrences of **N** is less than or equal to the number of runs of **N-1**. The above list is not self-limiting, because there are 4 occurrences of **1**, but only one run of **0**s.

Here's an example of a self-limiting list: **\[0,0,3,4,1,0,2,1,1,0,2,1,0,0,0,1,0\]**. It has

* 5 runs of **0** and 5 occurrences of **1**,
* 4 runs of **1** and 2 occurrences of **2**,
* 2 runs of **2** and 1 occurrence of **3**,
* 1 run of **3** and 1 occurrence of **4**,
* 1 run of **4** and no occurrences of **5**,
* no occurrences of other integers.

## The task

Your task is to decide whether a list is self-limiting. More explicitly, your input shall be a nonempty list of nonnegative integers. If the list is self-limiting, your output shall be truthy; otherwise, it shall be falsy. Input and output can be in any reasonable format.

The lowest byte count in each programming language is the winner. Standard rules apply.

## Test cases

Truthy instances:

```
[0]
[1,0]
[0,1,1,0,2]
[3,1,1,0,0,2,0,0]
[5,0,4,1,3,0,2,2,0,1,1,1,0]
[0,0,1,1,0,0,1,1,0,0,2,2,0,0]
[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]
[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]
[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]
[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]

```

Falsy instances:

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

```

# Answer
> 5 votes
# Perl 6, 29 bytes

```
{bag(.grep(?*)X-1)⊆.squish}

```

Try it online!

Very nice challenge for Perl 6. Uses the subset operator on Bags (integer-weighted sets). Explanation:

```
{
    bag(           # Create bag of
        .grep(?*)  # non-zero elements,
        X- 1       # decremented by one.
    )
    ⊆              # Subset test.
    .squish        # "squish" removes repeated elements in each run.
                   # The result is implicitly converted to a bag
                   # counting the number of runs.
}

```

# Answer
> 3 votes
# Perl 5 `-p`, ~~49~~ ~~48~~ 44 bytes

```
#!/usr/bin/perl -p
$z[$_+1]+=!/^$o$/;$z[$o=$_]--}{$_="@z"!~/.-/

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), ~~92~~ 89 bytes

```
a=>a.map(n=>g(~n,n!=p&&g(p=n)),c=[j=0],p=g=n=>c[n]=-~c[n])&&!c.some((n,i)=>i-j++|n<c[~j])

```

Try it online!

### How?

The array **c\[ \]** is used to store both the number of runs and the number of integer occurrences. Runs are stored at non-negative indices and integer occurrences are stored at 1's-complement indices (**c\[-1\]** = number of **0**'s, **c\[-2\]** = number of **1**'s, etc.).

Negative indices are actually saved as *properties* of the underlying array object and **.some()** does not iterate over them.

```
a =>                        // given the input array a[]
  a.map(n =>                // for each value n in a[]:
    g(                      //   update c[]:
      ~n,                   //     increment c[~n] (# of integer occurrences)
      n != p && g(p = n)    //     if n != p, set p to n and increment c[n] (# of runs)
    ),                      //   end of c[] update
    c = [j = 0],            //   start with c = [0] and j = 0 (used later)
    p =                     //   initialize p to a non-numeric value
    g = n => c[n] = -~c[n]  //   g = helper function to increment c[n]
  )                         // end of map()
  && !c.some((n, i) =>      // for each value n at position i in c[]:
    i - j++ |               //   make sure that i == j++
    n < c[~j]               //   and n is greater than or equal to c[~j]
  )                         // end of some()

```

# Answer
> 3 votes
# Jelly, 10 bytes

```
œ-ŒgḢ€‘ƊS¬

```

Try it online!

### How it works

```
œ-ŒgḢ€‘ƊS¬  Main link. Argument: A (array)

       Ɗ    Drei; group the three links to the left into a monadic chain.
  Œg          Group consecutive, identical elements of A into subarrays.
    Ḣ€        Head each; pop the first element of each run.
      ‘       Increment the extracted integers.
            The resulting array contains n repeated once for each run of (n-1)'s.
œ-          Perform multiset subtraction, removing one occurrence of n for each
            run of (n-1)'s.
       S    Take the sum. If only 0's remain, the sum will be 0.
        ¬   Take the logical NOT, mapping 0 to 1 and positive integers to 0.

```

# Answer
> 2 votes
# Jelly, 19 bytes

```
ŒgḢ€ċÐ€ṀḶ$<ċÐ€ṀR$$Ẹ

```

Try it online!

# Answer
> 2 votes
# Python 3, 94 bytes

```
lambda a:all(sum(1for x,y in zip(a,a[1:]+[-1])if x==j!=y)>=a.count(j+1)for j in range(max(a)))

```

Try it online!

# Answer
> 2 votes
# Jelly, 17 bytes

```
ŒgḢ€ċ’}<ċ
çÐ€x⁸ẸṆ

```

Try it online!

# Answer
> 2 votes
# Japt, 21 bytes

```
x o e@ó¥ mÌè¥X ¨Uè¥XÄ

```

Test it online!

# Answer
> 2 votes
# Stax, ~~13~~ 9 bytes

Dennis found a much better algorithm. I've shamelessly ported it to stax.

```
ä╨²@┬↕OR♣

```

Run and debug it online

Unpacked, ungolfed, and commented, this is what it looks like.

```
c   copy input
:g  get run elements
{^m increment each
|-  multiset-subtract from original input
|M! get maximum from result, and apply logical not

```

Run this one

**Old Answer:**

```
║Ä|╤#╫∩▼cëózü

```

Run and debug it

It iterates over the input and checks the conditions:

* Is the element `> 0`?
* Is `occurrences(element) >= runs(element - 1)`?

If either of these conditions are true for an element, then that element is compliant. Iff all elements are compliant, the result is `1`.

Here's the unpacked, ungolfed, commented representation of the same program.

```
O           push 1 under the input
F           iterate over the input using the rest of program
  |c        skip this iteration of the value is 0
  x#        number of occurrences of this value in input (a)
  x:g _v#   number of runs of (current-1) in input (b)
  >!        not (a > b); this will be truthy iff this element is compliant
  *         multiply with running result

```

Run this one

# Answer
> 1 votes
## Haskell, 80 bytes

```
import Data.List
o#l=[1|x<-l,x==o]
f x=and[(i-1)#(head<$>group x)>=i#x|i<-x,i>0]

```

Try it online!

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


# Question
Title: How many minimum days will he take to complete N units of work?
A person has to complete `N` units of work; the nature of work is the same.

In order to get the hang of the work, he completes only **one unit of work in the first day**.

He wishes to celebrate the completion of work, so he decides to complete **one unit of work in the last day**.

He is only allowed to complete **`x`, `x+1` or `x-1` units of work in a day**, where `x` is the units of work completed on the previous day.

Your task is to create a program or function that will compute the **minimum** number of days will he take to complete `N` units of work.

### Sample Input and Ouput:

```
input -> output (corresponding work_per_day table)
-1    -> 0      []
0     -> 0      []
2     -> 2      [1,1]
3     -> 3      [1,1,1]
5     -> 4      [1,1,2,1] or [1,2,1,1]
9     -> 5      [1,2,3,2,1]
13    -> 7      [1,2,2,2,3,2,1]

```

Input may be taken through `STDIN` or as function argument, or in any appropriate way.

Output may be printed or as the result of a function, or in any appropriate way.

This is . Shortest solution wins.

# Answer
> 3 votes
# Jelly, 5 bytes

```
×4’½Ḟ

```

This uses a closed form of @LeakyNun's approach.

Try it online!

Due to a lucky coincidence,  is overloaded as `floor`/`real` for real/complex numbers. This is one of the only three overloaded atoms in Jelly.

### How it works

```
×4’½Ḟ  Main link. Argument: n (integer)

×4     Compute 4n.
  ’    Decrement; yield 4n - 1.
   ½   Square root; yield sqrt(4n - 1).
       If n < 2, this produces an imaginary number.
    Ḟ  If sqrt(4n - 1) is real, round it down to the nearest integer.
       If sqrt(4n - 1) is complex, compute its real part (0).

```

# Answer
> 4 votes
# Pyth, 8 bytes

```
tfg/*TT4

```

How it works:

```
tfg/*TT4   Q is implicitly assigned to the input.
 f         test for T=1,2,3,... returning the first successful case
   /*TT4   whether T * T / 4
  g     Q  is greater than or equal to the input (second argument implied)
t          and subtract 1 from the first successful case

```

Try it online!

In pseudo-code:

```
for(int T=1;;T++)
    if(T*T/4 >= Q)
        return T-1;

```

### bonus, 22 bytes

"should return 7 for -1"

```
+tfg/*TT4?>Q0Q-2Q1*4g1

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES2016), 24 bytes

Shortened version of the ES6 variant below thanks to @Florent and the Exponentiation Operator (currently only in Firefox nightly builds or transpilers).

```
n=>(n-1)**.5+(n+1)**.5|0

```

# JavaScript (ES6), 30 bytes

```
n=>(s=Math.sqrt)(n-1)+s(n+1)|0

```

Based upon this sequence.

```
f=n=>(s=Math.sqrt)(n-1)+s(n+1)|0

units.oninput = () => output.value = f(+units.value||0);
```

```
<label>Units: <input id="units" type="number" value="0" /></label>
<label>Days: <input id="output" type="number" value="0" disabled /></label>
```

# Answer
> 2 votes
# JavaScript, ~~32~~ 31 bytes

```
f=(q,t=1)=>q>t*t/4?f(q,t+1):t-1

```

**Ungolfed code:**

```
function f(q, t = 1) {
  return q > t * t / 4
    ? f(q, t + 1)
    : t - 1
}

```

It uses the same algorithm as Kenny Lau's anwser but it is implemented as recursive closure to save some bytes.

**Usage:**

```
f(-1)  // 0
f(0)   // 0
f(2)   // 2
f(3)   // 3
f(5)   // 4
f(9)   // 5
f(13)  // 7

```

**REPL solution, 23 bytes**

```
for(t=1;t*t++/4<q;);t-2

```

Prepend `q=` to run the snippet:

```
q=-1;for(t=1;t*t++/4<q;);t-2 // 0
q=9;for(t=1;t*t++/4<q;);t-2  // 5
q=13;for(t=1;t*t++/4<q;);t-2 // 7

```

# Answer
> 2 votes
# UGL, ~~30~~ 25 bytes

```
i$+$+dc^l_u^^$*%/%_c=:_do

```

Try it online!

Does not work for negative inputs.

### How it works:

```
i$+$+dc^l_u^^$*%/%_c=:_do
i$+$+d                     #n = 4*input-1
      c                    #i=0
       ^l_     %/%_c=:_    #while      > n:
           ^^$*            #      i**2
          u                #                i = i+1
                       do  #print(i)

```

## Previous 30-byte solution:

```
iuc^l_u^^$*cuuuu/%_u%/%_c=:_do

```

Online interpreter here.

Does not work for negative inputs.

### How it works:

```
iuc^l_u^^$*cuuuu/%_u%/%_c=:_do
iuc                             #push input; inc; i=0;
   ^l_u             %/%_c=:_    #while        > input:
       ^^$*cuuuu/%_             #      i**2/4
                   u            #                      i = i+1
                            do  #print(i)

```

# Answer
> 2 votes
## Python, 28 bytes

```
lambda n:max(4*n-1,0)**.5//1

```

Outputs a float. The `max` is there to give `0` for `n<=0` while avoiding an error for square root of negative.

# Answer
> 1 votes
# MATL, 11 bytes

```
E:t*4/G<f0)

```

Similar algorithm to @KennyLau except that rather than looping indefinitely, I loop from 1...2n to save some bytes.

**Try it Online!**

**Explanation**

```
    % Implicitly grab the input
E   % Double the input
:   % Create an array from 1...2n
t*  % Square each element
4/  % Divide each element by 4
G<  % Test if each element is less than G
f   % Get the indices of the TRUE elements in the array from the previous operation
0)  % Get the last index (the first index where T*T/4 >= n)
    % Implicitly display the result.

```

# Answer
> 0 votes
## Pyke, 8 bytes

```
#X4f)ltt

```

Try it here!

Uses same algorithm as @KennyLau

# Answer
> 0 votes
# Python, 43 bytes

```
f=lambda n,i=1:i-1if i*i>=n*4 else f(n,i+1)

```

# Answer
> 0 votes
# Java 8, ~~30~~ 24 bytes

```
n->(int)Math.sqrt(n*4-1)

```

Try it online.

No need to check if `n` is larger than 0, because Java's `Math.sqrt` returns `NaN` for negative inputs, which becomes `0` with the cast to `int` we already use for the positive inputs.

# Answer
> 0 votes
# Ruby, 30 bytes

```
->n{n<1?0:((4*n-1)**0.5).to_i}

```

Try it online!

Saving a byte here with `.to_i` instead of `.floor`.

Support for non-positive amounts of work comes at a cost of 6 bytes (`n<1?0:`).

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


title: How old is it roughly?

text:
# Question
Title: How old is it roughly?
Write a short program which takes in a positive number of seconds representing an age, and outputs an estimate of that time in English.

Your program must output the *least precise* amount of time which has passed, among the following metrics and their lengths in seconds:

```
second = 1
minute = 60
hour   = 60 * 60
day    = 60 * 60 * 24
week   = 60 * 60 * 24 * 7
month  = 60 * 60 * 24 * 31
year   = 60 * 60 * 24 * 365

```

**Examples**

```
input      : output
1          : 1 second
59         : 59 seconds
60         : 1 minute
119        : 1 minute
120        : 2 minutes
43200      : 12 hours
86401      : 1 day
1815603    : 3 weeks
1426636800 : 45 years

```

As you can see above, after the time of say, 1 day (60 * 60 * 24 = 86400 seconds), **we no longer output minute(s) or hour(s)**, but only days until we surpass the time of one week, and so on.

Consider the given length of time to be an age. For example, after 119 seconds, 1 minute has *passed*, not 2.

**Rules**

* No specification for 0 or negative inputs.
* Follow proper pluralization. Every measure greater than 1 must include an `s` following the word.
* You may not use a pre-existing library which serves the function of the entire program.
* This is a code golf, shortest program wins the internet points.
* Have fun!

# Answer
> 8 votes
# Jelly, 62 bytes

```
TṀị
“¢<<ð¢‘×\×€0¦7,31,365F⁸:µç“ɲþḣ⁹ḢṡṾDU¤µQƝṁ⁼ẹ»Ḳ¤ṭÇK;⁸Ç>1¤¡”s

```

A full program printing the result.
(As a monadic link it returns a list of an integer followed by characters)

**Try it online!**

### How?

```
TṀị - Link 1: list of integers, K; list, V  e.g. [86401,1440,24,1,0,0,0], ["second","minute","hour","day","week","month","year"]
T   - truthy indexes of K                        [1,2,3,4]
 Ṁ  - maximum                                    4
  ị - index into V                               "day"

“¢<<ð¢‘×\×€0¦7,31,365F⁸:µç“...»Ḳ¤ṭÇK;⁸Ç>1¤¡”s - Main link: integer, N  e.g. 3599
“¢<<ð¢‘                                       - list of code-page indices = [1,60,60,24,1]
        \                                     - cumulative reduce with:
       ×                                      -  multiplication = [1,60,3600,86400,86400]
             7,31,365                         - list of integers = [7,31,365]
            ¦                                 - sparse application...
           0                                  - ...to index: 0 (rightmost)
         ×€                                   - ...of: multiplication for €ach = [1,60,3600,86400,[604800,2678400,31536000]]
                     F                        - flatten = [1,60,3600,86400,604800,2678400,31536000]
                      ⁸                       - chain's left argument, N    3599
                       :                      - integer divide         [3599,59,0,0,0,0,0]
                        µ                     - start a new monadic chain, call that X
                                ¤             - nilad followed by links as a nilad:
                          “...»               -   compression of "second minute hour day week month year"
                               Ḳ              -   split at spaces = ["second","minute","hour","day","week","month","year"]
                         ç                    - call the last link (1) as a dyad - i.e. f(X,["second","minute","hour","day","week","month","year"])
                                              -                             "minute"
                                  Ç           - call the last link (1) as a monad - i.e. f(X,X)
                                              -                             59
                                 ṭ            - tack                        [59,['m','i','n','u','t','e']]
                                   K          - join with spaces            [59,' ','m','i','n','u','t','e']
                                           ”s - literal character '
                                          ¡   - repeat...
                                         ¤    - ...number of times: nilad followed by link(s) as a nilad:
                                     ⁸        -   chain's left argument, X  [3599,59,0,0,0,0,0]
                                      Ç       -   call the last link (1) as a monad - i.e. f(X,X)
                                              -                             59
                                       >1     -   greater than 1?           1
                                    ;         - concatenate                 [59,' ','m','i','n','u','t','e','s']
                                              - implicit print - smashes to print  "59 minutes"

```

# Answer
> 8 votes
# C, 194 180 144 128 characters

Thanks to @gastropher for the code reductions. I forgot that C allows for implicit parameters using K&R-style functions! Also thanks to @gmatht for the idea of putting literals inside instead of arrays. I extended that to the characters by abusing taking advantage of wide character/`char16_t` strings! The compiler doesn't seem to like `\1` in its ☺ form though.

```
f(t,c,d){for(c=7;!(d=t/L"\1<ฐ\1•▼ŭ"[--c]/(c>2?86400:1)););printf("%d %.6s%s\n",d,c*6+(char*)u"敳潣摮業畮整潨牵 慤y†敷步 潭瑮h敹牡",(d<2)+"s");}

```

Try it online!

# Original solution

I split up the arrays into separate lines to make it easier to see the rest of the solution.

```
char *n[]={"second","minute","hour","day","week","month","year"};
int o[]={1,60,3600,86400,604800,2678400,31536000};
f(int t){int c=7,d;while(!(d=t/o[--c]));printf("%d %s%s\n",d,n[c],d>1?"s":"");}

```

Try it online!

Running the divisors in order from largest to smallest, we get the coarsest unit of time. The program misbehaves if you give it 0 seconds, but as the specification explicitly excludes this value, I deem that to be acceptable.

# Answer
> 7 votes
# Perl 5, 110 bytes

```
year31536000month2678400week604800day86400hour3600minute60second1=~s:\D+:say"$% $&",$_=$%>1&&"s"if$%=$_/$':reg

```

Try it online!

# Answer
> 5 votes
# Stax, 54 bytes

```
▀♂♂┼╕Qá◙à*ä∙Φò►⌠╨Ns↔║►πîÇ∙cI≡ªb?δ♪9gΓ╕┬≥‼⌡Öå01:♪EoE╘≡ë

```

Run and debug it

Here's the unpacked, ungolfed, ascii representation of the same program.

```
                            stack starts with total seconds
c60/                        push total minutes to stack
c60/                        ... hours
c24/                        ... days
Yc7/                        ... weeks
y31/                        ... months
y365/                       ... years
L                           make a list out of all the calculated time units
`)sQP(dr'pk,oV4?_HIFD?x`j   compressed literal for singular forms of unit names
\                           zip totals with names
rF                          foreach pair of total and name (in reverse orer)
  h!C                       skip if the current total is falsey (0)
  _J                        join the total and unit name with a space
  's_1=T+                   concat 's' unless the total is one

```

Following execution, since there's no other output, the top of the stack is printed implicitly.

Run this one

# Answer
> 5 votes
# JavaScript (ES6), 131 bytes

```
n=>[60,60,24,7,31/7,365/31,0].map((v,i)=>s=n<1?s:(k=n|0)+' '+'second,minute,hour,day,week,month,year'.split`,`[n/=v,i])|k>1?s+'s':s

```

Try it online!

# Answer
> 3 votes
# Java 8, ~~197~~ ~~195~~ 157 bytes

```
n->(n<60?n+" second":(n/=60)<60?n+" minute":(n/=60)<24?n+" hour":(n/=24)<7?n+" day":n<31?(n/=7)+" week":n<365?(n/=31)+" month":(n/=365)+" year")+(n>1?"s":"")

```

-38 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it online.

```
n->               // Method with long parameter and String return-type
  (n<60?          //  If `n` is below 60:
    n             //   Output `n`
    +" second"    //   + " second"
   :(n/=60)<60?   //  Else-if `n` is below 60*60
    n             //   Integer-divide `n` by 60, and output it
    +" minute"    //   + " minute"
   :(n/=60)<24?   //  Else-if `n` is below 60*60*24:
    n             //   Integer-divide `n` by 60*60, and output it
    +" hour"      //   + " hour"
   :(n/=24)<7?    //  Else-if `n` is below 60*60*24*7:
    n             //   Integer-divide `n` by 60*60*24, and output it
    +" day"       //   + " day"
   :n<31?         //  Else-if `n` is below 60*60*24*31:
    (n/=7)        //   Integer-divide `n` by 60*60*24*7, and output it
    +" week"      //   + " week"
   :n<365?        //  Else-if `n` is below 60*60*24*365:
    (n/=31)       //   Integer-divide `n` by 60*60*24*31, and output it
    +" month"     //   + " month"
   :              //  Else:
    (n/=365)      //   Integer-divide `n` by 60*60*24*365, and output it
    +" year")     //   + " year"
   +(n>1?"s":"")  //  And add a trailing (plural) "s" if (the new) `n` is larger than 1

```

# Answer
> 2 votes
# Kotlin, ~~205~~ ~~203~~ 196 bytes

```
x->val d=86400
with(listOf(1 to "second",60 to "minute",3600 to "hour",d to "day",d*7 to "week",d*31 to "month",d*365 to "year").last{x>=it.first}){val c=x/first
"$c ${second+if(c>1)"s" else ""}"}

```

Try it online!

# Answer
> 2 votes
# APL+WIN, ~~88~~ 119 bytes

Original version missed out weeks and months as pointed out by Phil H;(

Prompts screen input of number of seconds

```
a←⌽<\⌽1≤b←⎕÷×\1 60 60 24 7,(31÷7),365÷31⋄b,(-(b←⌊a/b)=1)↓∊a/'seconds' 'minutes' 'hours' 'days' 'weeks' 'months' 'years'

```

Explanation

```
b←⎕÷×\1 60 60 24 7,(31÷7),365÷31 prompts for input and converts to years, days, hours, minutes, seconds

a←⌽<\⌽1≤b identify largest unit of time and assign it to a

a/'years' 'days' 'hours' 'minutes' 'seconds' select time unit

(-(b←⌊a/b)=1)↓∊ determine if singular if so drop final s in time unit

b, concatenate number of units to time unit from previous steps

```

# Answer
> 2 votes
# T-SQL, 306 bytes (281 bytes without I/O)

```
DECLARE @n INT=1
DECLARE @r VARCHAR(30)=TRIM(COALESCE(STR(NULLIF(@n/31536000,0))+' year',STR(NULLIF(@n/2678400,0))+' month',STR(NULLIF(@n/604800,0))+' week',STR(NULLIF(@n/86400,0))+' day',STR(NULLIF(@n/3600,0))+' hour',STR(NULLIF(@n/60,0))+' minute',STR(@n)+' second'))IF LEFT(@r,2)>1 SET @r+='s'
PRINT @r

```

# Answer
> 2 votes
# , 157 bytes

```
function(n,x=cumprod(c(1,60,60,24,7,31/7,365/31)),i=cut(n,x),o=n%/%x[i])cat(o," ",c("second","minute","hour","day","week","year")[i],"if"(o>1,"s",""),sep="")

```

Try it online!

`cut` is handy, since it splits ranges into `factor`s, which are stored internally as `integer`s, meaning we can use them as array indices as well. We can probably do something a bit more clever with the time period names, but I can't figure it out just yet.

# Answer
> 1 votes
# JavaScript (Node.js), 177 bytes

```
x=>{return d=86400,v=[[d*365,'year'],[d*31,'month'],[d*7,'week'],[d,'day'],[3600,'hour'],[60,'minute'],[1,'second']].find(i=>x>=i[0]),c=parseInt(x/v[0]),c+' '+v[1]+(c>1?'s':'')}

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~146~~ 144 bytes

```
lambda n,d=86400:[`n/x`+' '+y+'s'*(n/x>1)for x,y in zip([365*d,31*d,7*d,d,3600,60,1],'year month week day hour minute second'.split())if n/x][0]

```

Try it online!

2 bytes saved thanks to Jonathan Allan

# Answer
> 1 votes
## Batch, 185 bytes

```
@for %%t in (1.second 60.minute 3600.hour 43200.day 302400.week, 1339200.month, 15768000.year)do @if %1 geq %%~nt set/an=%1/%%~nt&set u=%%~xt
@if %n% gtr 1 set u=%u%s
@echo %n%%u:.= %

```

# Answer
> 1 votes
# PHP, 183 bytes

```
<?$a=[second=>$l=1,minute=>60,hour=>60,day=>24,week=>7,month=>31/7,year=>365/31];foreach($a as$p=>$n){$q=$n*$l;if($q<=$s=$argv[1])$r=($m=floor($s/$q))." $p".($m>1?s:"");$l=$q;}echo$r;

```

Try it online!

# Answer
> 1 votes
# Julia 0.6, 161 bytes

```
f(n,d=cumprod([1,60,60,24,7,31/7,365/31]),r=div.(n,d),i=findlast(r.>=1),l=Int(r[i]))="$l $(split("second minute hour day week month year",' ')[i])$("s"^(l>1*1))"

```

Try it online!

# Answer
> 0 votes
# Ruby, 129 bytes

```
->n{x=[365*d=24*k=3600,d*31,d*7,d,k,60,1].index{|j|0<d=n/k=j};"#{d} #{%w{year month week day hour minute second}[x]}#{d>1??s:p}"}

```

Try it online!

# Answer
> 0 votes
# Perl 6/Rakudo 138 bytes

I'm sure there's further to go, but for now

```
{my @d=(365/31,31/7,7,24,60,60);$_/=@d.pop while @d&&$_>@d[*-1];$_.Int~" "~ <year month week day hour minute second>[+@d]~($_>1??"s"!!"")}

```

Explicate:

```
{ # bare code block, implicit $_ input
    my @d=(365/31,31/7,7,24,60,60); # ratios between units
    $_ /= @d.pop while @d && $_ > @d[*-1]; # pop ratios off @d until dwarfed
    $_.Int~   # implicitly output: rounded count
        " "~  # space
        <year month week day hour minute second>[+@d]~ # unit given @d
        ($_>1??"s"!!"")  # plural
}

```

# Answer
> 0 votes
# R, 336

Working in progress

```
function(x){
a=cumprod(c(1,60,60,24,7,31/7,365/31))
t=c("second","minute","hour","day","week","month")
e=as.data.frame(cbind(table(cut(x,a,t)),a,t))
y=x%/%as.integer(as.character(e$a[e$V1==1]))
ifelse(x>=a[7],paste(x%/%a[7],ifelse(x%/%a[7]==1,"year","years")),
ifelse(y>1,paste(y,paste0(e$t[e$V1==1],"s")),paste(y,e$t[e$V1==1])))}

```

# Answer
> 0 votes
# , 246 bytes

```
f=function(x,r=as.integer(strsplit(strftime(as.POSIXlt(x,"","1970-01-01"),"%Y %m %V %d %H %M %S")," ")[[1]])-c(1970,1,1,1,1,0,0),i=which.max(r>0)){cat(r[i],paste0(c("year","month","week","day","hour","minute","second")[i],ifelse(r[i]>1,"s","")))}

```

Try it online!

This is using time formating instead of arithemtics, just for the hell of it. Maybe others could make this smaller?

---
Tags: code-golf, date
---


title: Add Rainbow Pairs

text:
# Question
Title: Add Rainbow Pairs
The rules are as follows:

* Take in a string of integers separated by spaces. Add the first and last numbers, the second and second-last numbers, and so on.
* The program must output the numbers separated by newlines.
* The program must handle negative numbers, but may not handle decimals.
* If an odd amount of integers are inputted, just print the lone integer at the end.
* This is code golf, fewest bytes wins.

Here are some test cases:

```
> input
output
more output
etc.
-------------------
> 2 2
4

> 1 2 3 4 5 6
7
7
7

> 3 4 2 6
9
6

> 1 2 3 4 5
6
6
3

> -5 3 -8 2
-3
-5

```

# Answer
# Stax, 9 8 bytes

*Thanks to Weijun Zhou for -1 bytes*

It actually conforms with the required output format!

```
Φ┴⌐Öâ9|Ö

```

Run and debug it

Here's the ungolfed ascii representation of the program.

```
L   Concatenate all inputs into list
2M  Create two equal-ish size batches, with the bigger piece first
Er  Push the two parts to the stack, and reverse the second one
LM  Put two parts back together as 2-row matrix, then transpose
m|+ For each zipped pair, print the sum on a separate line

```

Run this one
> 9 votes

# Answer
# Perl 5 `-a`, 23 bytes

```
#!/usr/bin/perl -a
say$'*s//a/+pop@F for@F

```

Try it online!

Perl is unusual in that it is valid to change an array while you are looping over it. So you can have `$_` walking from front to back while using `pop` to effectively walk from back to front while removing array elements which will stop the loop when they meet in the middle:

```
say$_+pop@F for@F

```

This however fails for an odd number of elements because in the middle both `$_` and `pop@F` are that middle element so you get twice the value.

So instead I use another odd fact of perl loops: the loop variable is not a copy of the corresponding array position but is an alias for it. If you change `$_` then you change the corresponding array element. In this case I want to both get the value of `$_` ***and*** change it to `0` so that the `pop@F` returns zero when processing the middle element. The shortest way (without needing `()`) to do that is `s//a/` which changes e.g. `6` to `a6` which evaluates to `0` in a numeric context. The part after the substitution is preserved in `$'` which will be `6` in the example. And since `s///` returns the number of substitutions (`1` in this case) the expression `s//a/*$'` will both set `$_` to zero and return the original value.

This however would require a space after `say`. So finally I use yet another perl oddity, the fact that the expression stack also uses aliases of the values and variables you are processing. Therefore `$'*s//a/` also works. When `$'` is put on the expression stack it is not set yet but when next `s//a/` is executed it changes to the old value of `$_` in place just before the multiplication is done. This is also the reason why the simpler seeming

```
say$_+($_=0)+pop@F for@F

```

does ***not*** work. The first `$_` gets changed to `0` just before the first addition. You would need to force a copy with something like

```
say "$_"+($_=0)+pop@F for@F

```

to make that work
> 8 votes

# Answer
# Python 3, 57 bytes, relaxed I/O

```
def f(a):
 try:x,*a,y=a;return[x+y]+f(a)
 except:return a

```

Try it online!

First time to see `try..except` in golfing.

## `print` version, 57 bytes

```
def f(a):
 try:x,*a,y=a;print(x+y);f(a)
 except:print(*a)

```

Try it online!

`print`ing instead of `return`ing gives the same length.

# Python 3, 73 bytes, strict I/O

```
a=*map(int,input().split()),
while len(a)>1:x,*a,y=a;print(x+y)
print(*a)

```

Try it online!

This prints an extra newline at the end if the number of elements is even.
> 5 votes

# Answer
## JavaScript ES6, 100 97 bytes

```
_=>{for(_=_.split(' ').map(Number);0<_.length;)console.log(1<_.length?_.shift()+_.pop():_.pop())}

```

https://jsbin.com/nufanenehu/edit?js,console

First golfing answer ever. Be gentle.
> 4 votes

# Answer
# 05AB1E, 7 bytes

```
#2ä`R+»

```

Try it online!

**Explanation**

```
#          # split input on spaces
 2ä        # divide into 2 parts
   `       # split separately to stack
    R      # reverse the second one
     +     # add the lists of numbers
      »    # join on newlines

```
> 4 votes

# Answer
# JavaScript (Node.js), ~~77~~ 58 bytes

```
a=>g(a.split` `)
g=a=>+a.shift()+~~a.pop()+`
`+(a+a&&g(a))

```

Try it online!

Thanks to @Neil for chopping off 17 bytes at once. Also, I found that `~~` works instead of `|0`, which removes a pair of parens.

# Original submission, 77 bytes

```
a=>g(a.split` `.map(x=>+x))
g=a=>a.shift()+(a.pop()|0)+`
`+(a.length?g(a):'')

```

Try it online!

Input as a space-delimited string, output as a newline-delimited string. First converts the input string into an array, then passes to a recursive function that generates the output string.
> 3 votes

# Answer
# Brainfuck, 61 bytes

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

```

Try it online!

This program takes a null-terminated list of base-256 ASCII numbers as input :)

**Commented Version**

```
Read input chars until \0
>>+[>,]<
Clear initial 1
[<]>->
[
  Copy two to the left
  [-<<+>>]>
  Head to right side
  [>]<
  Subtract from right side add to left side repeat
  [[<]<< +>>> [>]< - ]
  Start at next spot
  <[<]>
]
Print it all out
<<<
[<]
>[.>]

```

**Satisfying I/O requirements, 81 bytes**

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

```

In this version the input characters must be separated and the output is split by newlines.
> 3 votes

# Answer
# Jelly, 7 bytes

```
œs2U2¦S

```

Try it online!

Takes a list of integers, such as `[1, 2, 3, 4, 5]`. Outputs as an array, such as `[6, 6, 3]`.

11 bytes to conform to the strict input specifications.
> 2 votes

# Answer
# , ~~68~~ 66 bytes

```
cat(c((n=scan())[y<-1:(x=sum(n|1)/2)],rep(0,x!=x%/%1))+rev(n[-y]))

```

Try it online!

Takes input from stdin as in the examples, and prints the output on stdout. Since using `scan()` is typically shorter than defining a function and taking an array as input, this is the shortest way to take input.

Reads in data, takes the first half (rounded down) of the list, and appends a zero (if necessary), then adds it to the reverse of the second half of the list.
> 2 votes

# Answer
# J, 28 bytes

```
>.@-:@#({.|:@,:@+/@,:|.@}.)]

```

## ungolfed

```
>.@-:@# ({. |:@,:@+/@,: |.@}.) ]

```

Try it online!

My J is rusty and surely this could be improved -- suggestions encouraged. Almost all the complexity arises from the odd length case and the newline requirement. I had 22 bytes before I noticed the newline requirement:

```
>.@-:@# ({. +/@,: |.@}.) ]

```
> 2 votes

# Answer
# Python 2, 46 bytes

```
f=lambda x:x[1:]and[x[0]+x[-1]]+f(x[1:-1])or x

```

Try it online!

`x[1:]` is just a shorter way to write `len(x)>1`
> 2 votes

# Answer
# Python 3, 70 bytes

```
lambda a:[a[i]+a[~i]for i in range(len(a)//2)]+len(a)%2*[a[len(a)//2]]

```

Try it online!

+32 bytes for strict input:

# Python 3, 102 bytes

```
a=[*map(int,input().split())]
l=len(a)
for q in[a[i]+a[~i]for i in range(l//2)]+l%2*[a[l//2]]:print(q)

```

Try it online!
> 1 votes

# Answer
# Ruby \+ `-p`, 52 bytes (spec compliant)

```
a=$_.split.map(&:to_i);loop{puts a.shift+(a.pop||0)}

```

Try it online!

A full program, taking a string of space-separated integers and printing the results separated by newlines.

Normally the `-p` flag forces you to reassign the `$_` variable, as it will be implicitly printed at the end of the program. However this code terminates with an `NoMethodError` when it calls `+` on `nil` (the result of `shift`ing the head off an empty array), before that implicit print can happen.

# Ruby, 33 bytes (relaxed IO)

```
->a{puts a.shift+(a.pop||0);redo}

```

Try it online!

This lambda skips the integer parsing code, and it is able to save 2 bytes by replacing `loop{}` with `redo` since it is already inside of a repeatable block. This also terminates with `NoMethodError`.
> 1 votes

# Answer
# Perl 6 `-n`,  ~~58~~  42 bytes

```
.&{$_,{S:s/(\S+) (.*?) (\S+)?$ {say $0+($2//0)}/$1/}...''}

```

Try it

```
.say for .=words[^*/2]Z+ |.[$_-1...$_/2],0

```

Try it

---

If the input/output restrictions are relaxed **40 bytes**

```
*.[^*/2,{$_-1...$_/2}].&roundrobin».sum

```

Test it
> 1 votes

# Answer
# Java (OpenJDK 9), 76 bytes

```
a->{for(int i=0,l=a.length;i<l--;)System.out.println(i<l?a[i++]+a[l]:a[i]);}

```

Try it online!

## With strict input

# Java (JDK 10), 115 bytes

```
s->{var a=s.split(" ");for(int i=0,l=a.length;i<l--;)System.out.println(i<l?new Long(a[i++])+new Long(a[l]):a[i]);}

```

Try it online!

## Credits

* -10 bytes on strict input thanks to Kevin Cruijssen
> 1 votes

# Answer
# Haskell, ~~93~~ 80 bytes

Saved 13 bytes thanks to Laikoni!

```
f s|x<-read<$>words s=mapM print$zipWith(+)(take(div(1+length x)2)x)$reverse$0:x

```

Try it online!
> 1 votes

# Answer
# Haskell, ~~78~~ ~~72~~ ~~70~~ 67 bytes

```
mapM print.f.map read.words
f(x:r@(_:_))=(x+last r):f(init r)
f e=e

```

Try it online!

*Edits:*

* -6 bytes by using `mapM print` instead of `unlines.map show` from GolfWolf's Haskell answer.
* -2 bytes by removing `+0` which I though was necessary for type inference but wasn't. Thanks to GolfWolf for pointing out.
* -3 bytes by adding `r@(_:_)` to make the `f[x]=f[x]` pattern superfluous. Thanks again to GolfWolf.
> 1 votes

# Answer
# Clojure, 124 bytes

```
#(loop[l(map bigint(.split %" "))](println(+(first l)(or(last(rest l))0)))(if(>(count l)2)(recur(concat(butlast(rest l))))))

```

Try it online!

Ungolfed:

```
#(loop [l (map bigint (.split % " "))]
   (println (+ (first l) (or (last (rest l)) 0)))
   (if (> (count l) 2)
     (recur (concat (butlast (rest l))))))

```

An anonymous function that takes the input string and splits it. `loop` is rerun with every iteration with the "middle" items of the changing list if there are enough items left. Combining `butlast` and `rest` creates the "middle" list.
Interesting is the part where the sum is printed. Simply adding `(first l)` and `(last l)` only works for an even number of items. When an uneven number of items is passed, `first` and `last` will hit the same item. Using `rest` will remove the first item, in this case the only one, and return an empty list. Using `last` will return `nil` which is converted into zero by the `or` function.
> 1 votes

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

```
f=x=>([a,m='',b]=x.split(/ (.*) | /),b?a- -b+`
`+f(m):a)

```

Try it online!

Split the string by all the middle numbers and capture them all as a group, add the ends (coercing strings to numbers via `a- -b`, which is shorter than any alternatives I know of), and concatenate the result with a line break and `f(all captured middle numbers)` where available.
> 1 votes

# Answer
# Python 2, ~~111~~ ~~107~~ 103 bytes

```
i=map(int,input().split())
for y in[i[x]+i[-(x+1)]for x in range(len(i)/2)]+[i[x+1]]*(len(i)%2):print y

```

Try it online!

Takes input in "strict" format (space separated string of numbers) ~~and outputs a trailing newline if the count is even~~. Works because in Python 2, list comprehensions leak the last value of the variable `x` so it can be used later to identify the middle number.

# Python 2, ~~79~~ ~~75~~ 69 bytes

```
lambda i:[i[x]+i[-(x+1)]for x in range(len(i)/2)]+[i[x+1]]*(len(i)%2)

```

Try it online!

Shorter version with input and output as lists. ~~Adds an empty string to the output for even numbers.~~
> 0 votes

# Answer
# Python 3, 108 bytes

```
i=[*map(int,input().split())]
l=len(i)
for a,b in zip(i,i[:int(l/2-.5):-1]):print(a+b)
if l&1:print(i[l//2])

```

Try it online!

Non competitive, just thought it would be nice to share this zip approach :)
Too bad slicing and reversing in python is a bit finicky
> 0 votes

# Answer
# Red, 105 bytes

```
func[s][b: to-block s
l: length? b
repeat n l / 2[print b/(n) + b/(l - n + 1)]if odd? l[print b/(n + 1)]]

```

Try it online!

# Red, 91 bytes (Relaxed IO - a list ot integers)

```
func[b][l: length? b
repeat n l / 2[print b/(n) + b/(l - n + 1)]if odd? l[print b/(n + 1)]]

```

Try it online!
> 0 votes

# Answer
# **FORTH** 76 Bytes

```
: A BEGIN DEPTH 1 - ROLL + CR . DEPTH 2 <= UNTIL DEPTH 1 = IF CR . THEN ;

```

**Output:**

```
1 2 3 4 5 a
6
6
3  ok

2 2 A
4  ok

-5 3 -8 2 A
-3
-5 ok

```
> 0 votes

# Answer
# Python 2, 112 bytes

```
def f(s):
 s=[int(i)for i in s.split(' ')];s.insert(len(s)//2,0)
 for i in range(len(s)//2):print s[i]+s[-i-1]

```
> 0 votes

# Answer
# Perl 6/Rakudo 45 bytes

`Perl6 -ne`

```
{say .shift+(.pop||0) while $_}(.words.Array)

```

Super simple, shifts and pops, Perl makes the empty list (with odd count) easy with `.pop||0`.
> 0 votes

# Answer
# Python 3, 136 bytes

```
def f(x):
 x,o=[int(i) for i in x.split()],[];y=len(x)
 for i in range(int(y/2)):o+=[x[i]+x[-i-1]]
 if y%2!=0:o+=[x[int(y/2)]]
 return o

```

Try it online!
> 0 votes

# Answer
# Ruby, 67 bytes

This can probably be improved, but I'm not sure how...

```
def x(a);puts a.shift.to_i+a.pop.to_i;return if a.length==0;x a;end

```

Try it online!
> 0 votes

# Answer
# C, 128 bytes

This version is more in keeping with the terms of the challenge, but has a hard-coded maximum of 9 numbers that it can accept.

```
i[9],j,k;f(char*s){for(s=strtok(s," ");j++,s;i[j]=atoi(s),s=strtok(0," "));while(--j>=++k)printf("%d\n",i[j]+(j==k?0:i[k]));}

```

Try it online!

I let C do the tokenizing for me, which allows me to send each string directly to `atoi()`. Afterwards, I just add the mirror indexes until the start\>end.

As I couldn't get a array length and `strtok()` destroys the original string, making backtracking difficult, and I didn't want to have to `realloc()` to resize arrays, I hard-coded an array with a maximum of 9 values.

# C, 107 bytes (uses `argv`)

```
i,j,*k;f(char**s){k=(int*)s;while(s[++i])k[i]=atoi(s[i]);while(++j<=--i)printf("%d\n",k[i]+(i==j?0:k[j]));}

```

Try it online!

This version makes use of the fact that `argv` already has been tokenized; as a bonus, it doesn't have a hard-coded limit on the number of numbers! It does, however, assume that `sizeof(int)==sizeof(char*)`, which is truly evil and non-portable.
> 0 votes

# Answer
# **PHP**, 107 bytes

New to this, so please forgive my lack of correct formatting.

```
for($i=0,$a=explode(" ",$argv[1]),$c=count($a);$i<$c/2;$i++)echo$i==$c-$i-1?$a[$i]:$a[$i]+$a[$c-$i-1]."\n";

```

Try it online!
> 0 votes

# Answer
# Java (OpenJDK 8), 163 bytes

```
a->{String[] b=a.split(" ");int c=b.length;a="";for(int d=0;d<c/2;d++){a+=(Integer.parseInt(b[d])+Integer.parseInt(b[c-1-d]))+"\n";}if(c%2>0){a+=b[c/2];}return a;}

```

Try it online!

Well It’s sure not going to win me the bounty, but all in all I’m pretty happy with my work here.

**Explanation:**

```
a->{String[] b=a.split(" ");    //Create String array to get rid of the pesky spaces
int c=b.length;
a="";    //Since we now only need the array, we can reuse the original string to save a few bytes
for(int d=0;d<c/2;d++){    //Loop half(even) or half-1(odd) of the array length
  a+=(Integer.parseInt(b[d])+
   Integer.parseInt(b[c-1-d]))+    //Add the ‘rainbow pairs’ to the output string
  "\n";}    //Add a newline to each sum and end the loop
if(c%2>0){a+=b[c/2];}    //If the number of input numbers is odd, print the middle digit
return a;}    //the Output string is the Input string

```
> 0 votes

---
Tags: code-golf, number
---