title: Progruzzle & Colf

text:
# Question
Title: Progruzzle & Colf
Ever fancied creating cool twitter hashtags such as *#brexit* or *#brangelina*? this golf is for you.

---

Write a program that accepts two strings A & B as input and merges them according to the following algorithm:

1. let `n` be the number of vowels groups in A (e.g. `britain` has 2 vowels groups : `i` in position 3 and `ai` in position 5).
    * if n = 1 : truncate A starting at its first vowel group position (example: `bill` =\> `b`)
    * if n \> 1 : truncate A starting at its `n-1`th vowel group position (example: `programming` =\> `progr`, `britain` =\> `br`)
2. remove all consonants at the beginning of B (`jennifer` =\> `ennifer`)
3. concatenate the modified A & B

Vowels are `aeiou`; consonants are `bcdfghjklmnpqrstvwxyz`.

## Input

You can assume the input strings are lowercase and contain at least one vowel and one consonant.

## Examples

```
brad + angelina      => brangelina
britain + exit       => brexit
ben + jennifer       => bennifer
brangelina + exit    => brangelexit
bill + hillary       => billary
angelina + brad      => angelad
programming + puzzle => progruzzle
code + golf          => colf
out + go             => o

```

# Answer
# Ruby, ~~44~~ ~~43~~ 40 + 1 = 41 bytes

+1 byte for `-p` flag. Takes space-separated input on STDIN.
-1 byte thanks to Martin Ender
-2 bytes thanks to histocrat

```
sub /([aeiou]+([^aeiou]*)){,2} \g<2>/,""

```

Try it online!

## GNU sed, ~~39~~ 37 + 1 = 38 bytes

+1 byte for `-E` flag. Takes space-separated input on STDIN.
-1 byte thanks to Martin Ender

```
s/([aeiou]+[^aeiou]*){,2} [^aeiou]*//

```

Try it online!

Not posting this as a separate answer because it is literally the same solution.
> 23 votes

# Answer
# MATL, ~~31~~ 30 bytes

```
t13Y2XJmFwhdl=fql_):)itJmYsg)h

```

**Try it Online**

**Explanation**

```
t       % Implicitly grab the input and duplicate it
13Y2    % Push the string literal 'aeiouAEIOU'
XJ      % Store this in clipboard J for later use
m       % Check which characters from the input are vowels (true for vowel)
Fwh     % Prepend FALSE to this logical array
dl=     % Compute the difference and find where we went from not-vowel to vowel
f       % Find the indices of these transitions
q       % Subtract 1 to get the location of the last consonant in each transition
l_)     % Get the next-to-last one of these
:)      % Grab the first string up to this location

% Now for the second component!

it      % Explicitly grab the input and duplicate
J       % Retrieve the string literal 'aeiouAEIOU' from clipboard J
m       % Find where the vowels are (true for vowel)
Ys      % Compute the cumulative sum along the array. The result will be 0
        % for all characters before the first vowel and non-zero after
g)      % Convert to logical and use this as an index so any characters
        % after the first value are retrieved

% Now to combine them

h       % Horizontally concatenate the first and second pieces together
        % Implicitly display the result

```
> 12 votes

# Answer
# JavaScript (ES6), ~~81~~ ~~73~~ 72 bytes

*Saved 8 bytes thanks to @Jordan, 1 thanks to @DavidConrad*

```
a=>b=>a.match(/.*?(?=(?:[aeiou]+[^aeiou]*){1,2}$)/)+b.match(/[aeiou].*/)

```

Even though `.match` returns an array, `array+array` returns a string with the contents of the arrays concatenated (i.e. `[0]+[1]` returns `"01"`).

### Test snippet

```
f=a=>b=>console.log(a,"+",b,"=",a.match(/.*?(?=(?:[aeiou]+[^aeiou]*){1,2}$)/)+b.match(/[aeiou].*/))
f("brad")("angelina")
f("britain")("exit")
f("ben")("jennifer")
f("brangelina")("exit")
f("bill")("hillary")
f("angelina")("brad")
f("programming")("puzzle")
f("code")("golf")
f("progruzzle")("colf")
f("out")("go")
```

```
<input id=A value="super">
<input id=B value="chafouin">
<button onclick="f(A.value)(B.value)">Run</button>
```

Jordan's excellent Ruby solution would be 53 bytes in JS:

```
x=>x.replace(/([aeiou]+[^aeiou]*){1,2} [^aeiou]*/,"")

```
> 11 votes

# Answer
# Jelly, ~~23~~ 22 bytes

```
e€ØcT
Çµḟ‘-ị’
Ç⁸ḣ⁹ÑḢ⁹ṫ

```

**TryItOnline**

How?

```
e€ØcT    - Link 1, vowel indexes: s   e.g. "colouring"
  Øc     - yield vowels, "AEIOUaeiou"
e€       - in for each                     [0,1,0,1,1,0,1,0,0]
    T    - truthy indexes (1-based)        [2,4,5,7]

Çµḟ‘-ị’  - Link 2, n-1th or only vowel group index start - 1: s
 µ       - monadic chain separation
Ç        - call last link (1) as a monad   [2,4,5,7]
   ‘     - increment                       [3,5,6,8]
  ḟ      - filter out                      [2,4,7]
    -    - -1
     ị   - index value                     [4]
               (Jelly is 1-based and has modular indexing,
                so the last but one item is at index -1,
                and when there is only 1 item in the list it is also at index -1)
      ’  - decrement                       [3]

Ç⁸ḣ⁹ÑḢ⁹ṫ - Main link: a, b                      e.g. "colouring", "pencils"
Ç        - call last link (2) as a monad with a      [3]
 ⁸       - link's left argument, a
  ḣ      - head a[:y]                                "col"
   ⁹  ⁹  - link's right argument, b
    Ñ    - call next link (1) as a monad                          [2,5]
     Ḣ   - pop head                                               [2]
       ṫ - tail b[y-1:]                                           "encils"
         - implicit print                            "colencils"

```
> 7 votes

# Answer
## PowerShell v2+, 76 bytes

```
param($n,$m)($n-replace'([aeiou]+[^aeiou]*){1,2}$')+($m-replace'^[^aeiou]*')

```

Apparently this is a popular regex ... ;-)

Uses the `-replace` operator to pull off the appropriate pieces, then string-concatenates the results together. Adds on a `$` to the first to ensure we pull the end of the string, and adds a `^` to the second to ensure we pull off the front of the string.
> 5 votes

# Answer
## Retina, 35 bytes

```
([aeiou]+[^aeiou]*){1,2} [^aeiou]*

```

Try it online! (The first line enables a linefeed-separated test suite.)

Simply removes all matches of the regex on the first line.
> 4 votes

# Answer
# Cinnamon Gum, 23 bytes

```
0000000: 64d3 884e 4ccd cc2f 8dd5 8e8e 8330 b434  d..NL../.....0.4
0000010: b108 d92b c0d9 00                        ...+...

```

Try it online.

## Explanation

This decompresses to `d([aeiou]+[^aeiou]*)([aeiou]+[^aeiou]*)? [^aeiou]*`, which `d`eletes anything matching that regex. (Note that Jordan's golfier `d([aeiou]+[^aeiou]*){,2} [^aeiou]*` compresses to 24 bytes due to the lack of repeated elements to compress.)
> 4 votes

# Answer
# PHP, 95 Bytes

```
$t="aeiou]";echo($p=preg_filter)("#([$t+[^$t*){1,2}$#","",$argv[1]).$p("#^[^$t*#","",$argv[2]);

```

with preg\_match instead of preg\_filter 110 Bytes

```
$t="aeiou]";($p=preg_match)("#(.*?)([$t+[^$t*){1,2}$#",$argv[1],$m);$p("#[$t.*#",$argv[2],$n);echo$m[1].$n[0];

```
> 3 votes

# Answer
## Lua, 66 bytes

```
$ cat merge.lua
print(((...):gsub(("[]+[^]*[]*[^]*+[^]*"):gsub("]","aeiou]"),"")))
$ lua merge.lua brad+angelina
brangelina
$ lua merge.lua programming+puzzle
progruzzle

```
> 3 votes

# Answer
# Perl 5, 39 bytes

38, plus 1 for `-pe` instead of `-e`

```
s/([aeiou]+[^aeiou]*){1,2} [^aeiou]*//

```

Hat tip.
> 2 votes

# Answer
# Python 2, 139 bytes

```
n=lambda a,b:a[:a.index(([l for l in[[l,"!"][i!=0and a[i-1]in v]for i,l in enumerate(a)]if l in v]*2)[-2])]+b[sorted([(b+v).index(c)for c in v])[0]:]

```

This one was hard.

Check it out on repl.it
> 2 votes

# Answer
# Lithp, 65 bytes

```
#X::((replace X (regex "([aeiou]+[^aeiou]*){1,2} [^aeiou]*") ""))

```

---

This is basically a port of the JavaScript answer above, in my Lisp-ish functional programming language.

Example usage:

```
(
    % Note, you can define this as a function, or assign it to a variable
    % and use the call function instead.
    (def f #X::((replace X (regex "([aeiou]+[^aeiou]*){1,2} [^aeiou]*") "")))
    (print (f "programming puzzle"))
)

```

No online interpreter yet. I'll provide one soon. It won't be difficult, my language is written in JavaScript.

Instead, this puzzle solution is implemented as a working example for my language. It can be run with the following command:

```
node run.js l_src/progruzzle-colf.lithp

```
> 2 votes

# Answer
# Haskell, ~~111~~ 108 bytes

```
v x=elem x"aeiou"
d=dropWhile
e=d v
k=d$not.v
r=reverse
f a|c<-e.k.e.k$a,""/=c=c|1<3=e.k$a
a!b=(r.f.r)a++k b

```

This non-regex solution turned out longer than expected. Ideone it anyway.
> 2 votes

# Answer
# Jq 1.5, 45 bytes

```
gsub("([aeiou]+[^aeiou]*){1,2} [^aeiou]*";"")

```

Nothing special, just a port of msh210's perl solution to jq's PCRE.

Try it online!
> 1 votes

# Answer
# Japt, 18 bytes

```
r/\v+\V*){1,2} \V*

```

Try it online!

Direct port of short JS solution which is in turn the port of Jordan's Ruby solution.

### How it works

```
Ur/\v+\V*){1,2} \V*/

Ur    Replace on the input...
/\v+\V*){1,2} \V*/  this regex with empty string.
      \v == [AEIOUaeiou], \V == [^AEIOUaeiou], `g` flag is on by default in Japt
      so the uncompressed regex is roughly /([aeiou]+[^aeiou]*){1,2} [^aeiou]*/g.

```
> 1 votes

---
Tags: code-golf
---


title: Self-enumerating pangrams

text:
# Question
Title: Self-enumerating pangrams
# Pangrams

> The quick brown fox jumped over the lazy dog.

This is an example of a pangram - a sentence that contains every letter of the alphabet at least once.

A *self-enumerating* pangram is a sentence that fulfills the criteria to be a pangram by producing an analysis of its own letter count.

An example of achieving this is the sentence

> This pangram contains four As, one B, two Cs, one D, thirty Es, six Fs, five Gs, seven Hs, eleven Is, one J, one K, two Ls, two Ms, eighteen Ns, fifteen Os, two Ps, one Q, five Rs, twenty-seven Ss, eighteen Ts, two Us, seven Vs, eight Ws, two Xs, three Ys, & one Z.

---

# The Challenge

Produce a function with the input being the string leading into the letter inventory. In the example, the input would be "This pangram contains". The quantity of each letter must be in the written form and contribute to the displayed letter count.

---

# Rules

* Oxford comma is optional
* Use an ampersand before Z (or, for hard mode, include the ability to switch between "&" and "and" in the function)
* Every letter counts towards the total letter count
* No non-written numbers
* This is so the shortest code in bytes wins
* In hono**u**r of the married couple this weekend, the numbers are to be written in the Queen's English. e.g. `nine hundred and ninety-nine Gs` for 999 occurrences of the letter G and `nine hundred and nine Gs` for 909.
* Orders of magnitude are to be written in the standard short-scale naming convention

# Edge cases

* There are some cases where the code will get stuck in a loop - for example, if there are two Os the code will increase the count to three Os, which causes the code to count two Os again. If calculating every other letter before coming back to this can't resolve the issue, consider the input to be a false starter and output `false`, `null` or an empty string.
* If a letter has over 999 occurrences, the input should be considered a false starter.

# Test Cases

* "This pangram contains" should output the example sentence

# Answer
# Python 2, 615 bytes

```
def g(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';n,m=n/100,n%100;e,d=m/10,m%10;return' '.join([D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0)))
from random import*
X='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def f(p):
 T=set();s='';i=0
 while 1:
	Q=s.upper().count;t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.'
        if s==t:return i,t
	if t in T:t=''.join(c*max(1,t.upper().count(c)+(randint(0,6)-3)*(random()<0.25))for c in X)
	T.add(t);s=t;i+=1

```

Try it online!

The function `f` takes `p` as the string prefix; and returns a tuple of an integer representing the number of steps taken, and the autogram.

The function `g` encodes a number `1<=n<=999` to its english string; it takes up 291 bytes, roughly half the total byte count. The code

```
Q=s.upper().count
t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.'

```

encodes the string `s` into a (potentially autogram-matic) pangram `t`.

We loop over the process, hoping for the situation where we find a `t` such that `t` is an autogram (i.e., where `t==s`). ~~If~~ When we get into a loop, we randomly nudge the counts of letters in a completely ad hoc manner.

For most values of `p`, this process will time out on TIO. Typically, millions of possibilities are examined before finding a 'winning' combination.

I don't have any proof at all, but my guess is: (a) apart from an exhaustive brute force search similar to what the originator Lee Sallows describes here and implements in hardware (!), this sort of random heuristic is about as good as you can get; and (b) there will be no solutions for many (most?) initial phrases `p`.
> 7 votes

---
Tags: code-golf, string, natural-language, pangram
---


title: Is it an exercise set?

text:
# Question
Title: Is it an exercise set?
We all know that a lot of exercises only affect one half of your body, so you have to do them twice, once for each side. Such exercises have two counterparts, one for the left side and one for the right. However, there's no need to execute the two counterparts consecutively, as long as the exercises for both sides are in the same order. You may as well switch between sides in your exercise program, but it wouldn't make sense to start some exercises with one side and some with the other.

## Challenge

An *exercise part* is a list of non-zero integers, where its second half consists of the integers of the first half negated and in the same order, and the signs of the integers on each half are equal. The sign of the first half of an exercise part is its *leading side*.

An *exercise set* is zero or more exercise parts with the same leading side concatenated together.

Given a list of non-zero integers as input, determine if it is an exercise set. The integers aren't necessarily unique. The list's length isn't necessarily even.

Your solution may not use any of the standard loopholes. You may use any two different consistent values for output. This is , so the shortest solution wins.

## Examples

`[-5, -1, -7, -6, -5, 5, 1, 7, 6, 5]` is an example of an exercise part. The first half is `[-5, -1, -7, -6, -5]`, and the last half is `[5, 1, 7, 6, 5]`, which is each integer in the first half negated. Additionally, the first half's integers are all of the same sign. This exercise part's leading side is `-1`.

`[3, 6, 5, -3, -6, -5, 1, 6, 4, 3, -1, -6, -4, -3]` is an example of an exercise set. Its individual exercise parts are `[3, 6, 5, -3, -6, -5]` and `[1, 6, 4, 3, -1, -6, -4, -3]`, and they both have leading side `1`.

`[4, -4, -5, 5]`, despite only consisting of valid exercise parts, isn't an exercise set, since the first part, `[4, -4]`, has leading side `1`, while the second part, `[-5, 5]`, has leading side `-1`.

## Test cases

Valid test cases:

```
[]
[1, -1]
[1, -1, 1, -1]
[-6, 6, -5, -4, -3, 5, 4, 3]
[-1, -5, -8, 1, 5, 8, -7, -6, -5, -3, 7, 6, 5, 3]
[-1, -5, -8, 1, 5, 8, -1, 1]

```

Invalid test cases:

```
[1]
[1, -2]
[1, 2, -3, -1, -2, 3]
[1, 2, 3, -3, -1, -2]
[-1, -5, -8, 1, 5, 8, 7, 6, 5, 3, -7, -6, -5, -3]
[1, 2, 3, 5, 1, 2, 3, 5]
[1, 2, -5, 4, -6, 5, 5, -6]
[1, 2, -1, 3, -2, -3]
[1, -2, 1]
[-1, -1, 1]
[1, -1, 1]

```

# Answer
# Python 2, ~~69~~ 67 bytes

```
a,b=x=[[],[]];k=0
for n in input():x[n>0]+=n*n,n*k>0;k=n
print a==b

```

Try it online!
> 5 votes

# Answer
# Jelly, 10 bytes

```
ṁṠŒg$+2/FẸ

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 54 bytes

Optimized version, inspired by Dennis' Python answer.

Returns **0** or **1**.

```
a=>a.map(b=p=x=>b[+(x<0)]+=[x*x,p*(p=x)>0])|b[1]==b[0]

```

Try it online!

---

# Original version, 74 bytes

```
a=>a.map(x=>b[i^=p*(p=x)<0&&-~(b[i]+=0)]+=[,x*x],b=[p=0,i=0])|b[1]+0==b[0]

```

Try it online!

### How?

We store the first halves of all exercise parts in **b\[0\]** and the second halves in **b\[1\]**, switching between **b\[0\]** and **b\[1\]** each time the sign is changing. Entries are squared to get rid of the sign. We prefix each entry with a comma and suffix each part with a **0**.

There's some extra logic to handle the 'empty input' edge case at basically no cost (see the comment near the end of the source code).

```
a =>                    // given the input array a[]
  a.map(x =>            // for each x in a[]:
    b[i ^=              //   access b[i]:
      p * (p = x)       //     we keep track of the previous entry in p
      < 0 &&            //     if p and x have opposite signs:
      -~(b[i] += 0)     //       append a '0' to b[i] and update i: 0 -> 1, 1 -> 0
    ] += [, x * x],     //   append a comma followed by x² to b[i]
    b = [p = 0, i = 0]  //   start with p = 0, i = 0 and b = [0, 0]
  ) |                   // end of map()
  b[1] + 0              // this will append a '0' to b[1] if it was turned into a string
                        // or let it unchanged if it's still equal to zero (integer),
                        // which handles the 'empty input' edge case
  == b[0]               // compare the result with b[0]

```
> 3 votes

# Answer
# , 91 bytes

Inputs a whitespace-separated vector of numbers. Outputs `FALSE` for valid and `TRUE` for invalid.

```
x=scan()
y=x<0
z=rle(y)
"if"(sum(x|1),any(x[y]+x[!y],z$v==rev(z$v),z$l[!0:1]-z$l[!1:0]),F)

```

`rle` gives the run length encoding, in this case of the sequence of positive and negative values.

The *completely and totally unfair empty edge case ;)* adds a whopping 15 bytes.

Many bytes shaved off by @Giuseppe.

Here is a 92 byte version expressed as a function which is better for testing:

Try it online!
> 3 votes

# Answer
# Java 8, ~~186~~ ~~183~~ 185 bytes

```
a->{int i=a.length-1,t,j;boolean r=i%2>0,f;if(i<0)return!r;for(f=a[i]<0;i>0;){for(r&=f==(t=a[j=i])<0;j>0&&t>>>31==a[--j]>>>31;);for(t=i-j,i-=2*t;j>=0&j>i;)r&=a[j+t]==-a[j--];}return r;}

```

+2 bytes due to a bug-fix for test cases of size 3 (almost all permutations of `1` and `-1` at the end of my TIO-link).

Can definitely be golfed.. The challenge looks to-the-point, but it's pretty hard to implement. Especially the test case `[4,-4,-5,5]` was annoying to fix.. But it works now. Will golf it down from here.

Try it online.

**Explanation:**

```
a->{                   // Method with integer-array parameter and boolean return-type
  int i=a.length-1,j,  //  Index integers (`i` starting at the last index)
      t;               //  Temp integer
  boolean r=i%2>0,     //  Result-boolean, starting at true if the input-list is even
          f;           //  Flag-integer
  if(i<0)              //  If the input was empty (edge case)
    return!r;          //   Return true
  for(f=a[i]<0;        //  Set the flag-boolean to "Is the current item negative?"
      i>0;){           //  Loop down over the array
    for(r&=f==(t=a[j=i])<0;
                       //   Set `s` to the current number
                       //   And verify if the initial flag and `s` have the same sign
        j>0            //   Loop `j` from `i` down as long as `j` is larger than 0,
        &&t>>>31==a[--j]>>>31;);
                       //   and both `s` and the current item have the same sign
                       //    Decreasing `j` by 1 every iteration
    for(t=i-j,         //   Set `t` to `i-j` (amount of same signed adjacent values)
        i-=2*t;        //   Decrease `i` by two times `t`
        j>=0           //   Loop as long as `j` is larger than or equal to 0,
        &j>i;)         //   and also larger than `i`
      r&=a[j+t]==-a[j--];}
                       //    Verify if the pairs at index `j+t` and `j`
                       //    are negatives of each other
  return r;}           //  Return if `r` is still true (if all verifications succeeded)

```
> 3 votes

# Answer
# Python 2, ~~147~~ ~~130~~ ~~113~~ ~~112~~ 106 bytes

```
from itertools import*
def f(s):l=[map(abs,g)for v,g in groupby(s+[0],0 .__cmp__)];print l[1::2]==l[:-1:2]

```

Try it online!

---

Saved:

* -27 bytes, thanks to Dennis
> 2 votes

# Answer
# Retina 0.8.2, 57 bytes

```
^\b|,\b
$&=
(.)(\d+),(?=\1)
$2_
-|=

.$
$&,
^((\w+,)\2)*$

```

Try it online! Takes comma-separated input, but link includes header that processes test cases. Explanation:

```
^\b|,\b
$&=

```

Insert a marker before each positive integer.

```
(.)(\d+),(?=\1)
$2_

```

Change the commas between integers of the same sign to underscores.

```
-|=

```

Delete the remaining signs.

```
.$
$&,

```

Append a comma if the input is not empty.

```
^((\w+,)\2)*$

```

Check that the string consists of pairs of runs of the same integers.
> 2 votes

# Answer
# Brachylog, ~~18~~ 14 bytes

```
~c{ḍz{ṅᵈ¹ṡ}ᵛ}ᵛ

```

Try it online!

Saved 4 bytes thanks to @ErikTheOutgolfer.

### Explanation

```
                    Succeed if and only if:
~c                  You can deconcatenate the input list…
  {         }ᵛ      …and verify that for each of the sublists:
   ḍ                  Split it in half
    z                 Zip the elements of each half together
     {    }ᵛ          Verify that for each couple:
      ṅᵈ¹               The first integer is the negation of the second one
         ṡ              Take the sign of the first one
                      All signs should be equal in a sublist
                    All leading signs of the sublists should be equal

```
> 2 votes

# Answer
# Python 2, 111 bytes

```
x=input()
o=[];p=[]
for a,b in zip(x,x[1:]):
 if 0<a*x[0]:
	p+=a,-a
	if b*a<0:o+=p[::2]+p[1::2];p=[]
print o==x

```

Try it online!
> 1 votes

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

```
b=>eval('i=b.length-1;r=i%2;0>i&&!r;for(f=0>b[i];0<i;){for(r&=f==(s=0>b[j=i]);0<j&&s&0>b[--j]|!s&0<b[j];);t=i-j;for(i-=2*t;0<=j&j>i;)r&=b[j+t]==-b[j--]}r')

```

Try it online!

---

Inspiration was @KevinCruijssen's answer

Also thanks to him for correcting 2 test cases of mine
> 1 votes

# Answer
# Stax, 13 bytes

```
Ç¥├W╦╣∩T~≥▌╨c

```

Run and debug it
> 1 votes

# Answer
# APL (Dyalog Classic), 48 bytes

```
{0::1⋄0≠+/×¨⍵:0⋄(~0∊⊢∨2|⍳∘⍴)2{⍺≡-⍵}/⍵⊂⍨1,2≠/×¨⍵}

```

Try it online!
> 0 votes

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


title: You're on a 8 day streak!

text:
# Question
Title: You're on a 8 day streak!
Duolingo, the language learning app, has a lot of things going for it, but there is one major issue that drives me crazy. It tells me how many days in a row I've used the app with a message like **You're on a 7 day streak!** Setting aside hyphenation and whether the number should be spelled out, this works fine for most numbers, but is indisputably wrong when it says **You're on a 8 day streak!** I'm not using it to learn English but this is still unfortunate behavior for a language app.

You're going to help out the Duolingo team by writing a complete program or function that figures out whether a given number should be preceded by *a* or *an*. A number is preceded by *a* if its pronunciation in spoken English begins with a consonant or semivowel sound, and preceded by *an* if its pronunciation begins with a vowel sound. Thus the only numbers preceded by *an* are those whose pronunciation begins with *eight*, *eleven*, *eighteen*, or *eighty*.

Presumably the Duolingo dev team left this bug in because they ran out of space for more source code in the app, so you need to make this code as short as possible in the hopes they can squeeze it in.

Your code must take an integer from 0 to 2,147,483,647 and output `a` or `an`. A trailing newline is optional. For the purposes of this challenge, 1863 is read as *one thousand eight hundred and sixty-three*, not *eighteen hundred and sixty-three*.

**Test cases:**

```
0 → a
8 → an
11 → an
18 → an
84 → an
110 → a
843 → an
1111 → a
1863 → a
8192 → an
11000 → an
18000 → an
110000 → a
180000 → a
1141592 → a
1897932 → a
11234567 → an
18675309 → an

```

# Answer
> 16 votes
# Pyth, 23 bytes

```
<>n\8hz}hjsz^T3,hT18"an

```

This selects how many letters to slice off the end of `"an"` by checking whether the first letter is not an `8` and that the first digit of the number when considered in base 1000 is neither 11 nor 18. The resulting boolean is the number of characters to slice of the end.

# Answer
> 29 votes
## Python 2, 60 bytes

```
lambda n:'a'+'n'[:`n`[0]=='8'or`n`[:2]in len(`n`)%3/2*'118']

```

An anonymous function. Adds an `n` if either:

* The first digit is 8
* The first two digits are 11 or 18, and the length is 2 modulo 3.

# Answer
> 12 votes
# GNU Sed, 32

Score includes +1 for `-E` option to sed.

```
s/^8.*|^1[18](...)*$/an/
t
ca
:

```

Try it online.

* Remove groups of 3 digits from the end of each number until there is only 1 to 3 digits left
* Match any number starting with 8 or exactly 11 or 18 and change to `an`
* Change all other numbers to `a`

Thanks to @MartinBüttner for his retina approach that saved 10 bytes.

# Answer
> 11 votes
# Shell + bsd-games, 30

```
number -l|sed '/^e/{can
q};ca'

```

Input read from STDIN.

`number` converts a decimal string into words. It is then a simple matter to decide whether or not the result begins with `e`.

# Answer
> 9 votes
## Retina, 27 bytes

This isn't very different from DigitalTrauma's Retina answer, but they insisted I post this myself.

```
^8.*|^1[18](...)*$
an
\d+
a

```

Try it online.

The first regex replaces all relevant numbers with `an`, and the second replaces all remaining numbers with `a`. This works for the same bytes:

```
^8.*|^1[18](...)*$
n
^\d*
a

```

# Answer
> 6 votes
# C++, 101

This is my challenge, so this isn't meant to be a competitive answer. Just wanted to see how short I could get it in C++. String operations are just too verbose so this is done with math. I feel like there must be a way to get that condition smaller but I can't quite figure it out.

```
const char*f(int i){int n=0,d=0;for(;i;(!(d++%3)&(i==18|i==11))|i==8?n=1:0,i/=10);return n?"an":"a";}

```

# Answer
> 4 votes
## Mathematica, 53 bytes

```
If[#~IntegerName~"Words"~StringStartsQ~"e","an","a"]&

```

A solution using string processing would actually end up being longer.

# Answer
> 3 votes
## JavaScript (ES6) ~~70~~ ~~61~~ ~~46~~ 38 bytes

```
n=>/^8|^1[18](...)*$/.test(n)?'an':'a'

```

Community wiki because the current solution is so different than my original. Thanks everyone!

Demo: http://www.es6fiddle.net/iio40yep/

# Answer
> 3 votes
## PostScript, ~~119~~ 113 characters

```
10 string cvs dup 0 get 56 eq exch dup length 3 mod 2 eq{0 2 getinterval dup(11)eq exch(18)eq or or}{pop}ifelse

```

With test code:

```
/An
{
    10 string cvs dup 0 get 56 eq exch dup length 3 mod 2 eq{0 2 getinterval dup(11)eq exch(18)eq or or}{pop}ifelse
} def

/ShouldBeFalse [ 0 110 1111 1863 110000 180000 1141592 1897932 ] def
/ShouldBeTrue [ 8 11 18 84 843 8192 11000 18000 11234567 18675309 ] def

() = (ShouldBeFalse) = ShouldBeFalse {An =} forall
() = (ShouldBeTrue)  = ShouldBeTrue  {An =} forall

```

# Answer
> 2 votes
## Seriously, ~~43~~ 40 bytes

```
9⌐9τk,;;$l3@\3*╤@\(íub)$#p'8=)XkΣ'n*'a+

```

The strategy here is to only look at the 1, 2, or 3 most significant digits, by integer-dividing the input by the largest value `10^(3n)` that is less than the input.

Try it online

Explanation:

```
9⌐9τk,;;$l3@\3*╤@\(íub)$#p'8=)XkΣ'n*'a+
9⌐9τk                                    push [11, 18]
     ,;;                                 push 3 copies of input (n)
        $l                               get length of n as string (effectively floor(log(n,10)))
          3@\3*╤                         get largest 10^(3n) less than the length
                @\                       get most significant digits of n (x)
                  (í                     bring list from back, push the index of x in the list or -1 if not in list
                    ub)                  increment by 1, convert to boolean, shove to bottom
                       $#p               push first digit from n (as string)
                          '8=            push 1 if "8" else 0
                             )X          shove to bottom of stack, discard remaining digits
                               kΣ'n*     push sum of stack, push a string containing that many "n"s
                                    'a+  push "a", concatenate

```

# Answer
> 2 votes
# Retina, 34

Direct translation of my sed answer:

```
+`(.)...$
$1
^8.*|^1[18]$
an
\d+
a

```

Try it online.

One byte saved thanks to @Timwi.

# Answer
> 2 votes
# Perl 6,  ~~31~~  30 bytes

~~```
{'a'~'n'x?/^8|^1<[18]>[...]*$/} # 31 bytes

```

```
{<a an>[?/^8|^1<[18]>[...]*$/]} # 31 bytes

```

```
{<a an>[?/^8|^[11|18][...]*$/]} # 31 bytes

```~~
```
{'a'~'n'x?/^8|^1[1|8][...]*$/} # 30 bytes

```

```
{<a an>[?/^8|^1[1|8][...]*$/]} # 30 bytes

```

( Perl 6 uses `[ ]` in regexes for non-capturing `( )`, and uses `<[ ]>` for character sets )

Usage:

```
# store it in a lexical code variable for ease of use
my &code = {...}

my @a  = <0 110 1111 1863 110000 180000 1141592 1897932>;
my @an = <8 11 18 843 8192 11000 18000 11234567 18675309>;

say @a.map: &code;
say @an.map: &code;

```

```
(a a a a a a a a)
(an an an an an an an an an)

```

# Answer
> 2 votes
## PostScript, 109 bytes

```
(a)exch 10 string cvs dup[exch length 3 mod 2 eq{(11)(18)}if(8)]{anchorsearch{pop pop(an)exch}if}forall pop =

```

The code verifies if the number starts with certain prefixes. The prefix `8` is always checked (*eight*, *eighty-something*, *eight-hundreds-and*), but `11` and `18` (*eleven* and *eighteen*) are checked only when the number of digits is a multiple of 3 plus 2.

We start with a tentative result of `a` and when a prefix is found the result gets replaced with `an`. `anchorsearch` is used to avoid extracting a prefix from the string. Even if a match is found we continue verifying the rest of the prefixes – why waste 5 bytes for the `exit`? –, but because the original string gets replaced with `a` we are sure not to get any false positives.

To return the `a`-or-`an` result on the operand stack instead of printing it, remove the trailing `=` (resulting length: 107 bytes).

Test code:

```
/DO {
    ... the code above ...
} def

(Should be "a"s:)  = {0 110 1111 1863 110000 180000 1141592 1897932}     { DO } forall
(Should be "an"s:) = {8 11 18 84 843 8192 11000 18000 11234567 18675309} { DO } forall
flush

```

# Answer
> 2 votes
## PostScript (with binary tokens), 63 bytes

```
(a)’>10’¥’1’8[’>’b3’j2’={(11)(18)}if(8)]{’${’u’u(an)’>}if}’I’u=

```

The  are bytes with the value 146 (decimal), `¥` is a 165 and `$` is a 3. All others are printable 7-bit ASCII characters.

This is the same as my PostScript \[pure ASCII\] version, but uses binary tokens where this helps reduce the total length. I post it separately for 3 reasons:

* In the general case, an implementation that minimizes the ASCII code is not necessarily the same as the one minimizing the binary version. Some longer piece of ASCII PostScript code could compress better than another and its corresponding binary version be shorter.
* Binary code is not suitable everywhere, so a pure ASCII answer may be preferred even if longer.
* It wouldn’t be fair to compare the length of a pure ASCII PostScript answer with one using binary encodings.

# Answer
> 1 votes
# Pyth, ~~29~~ 31

```
?:_ec_z3"(^18$|^11$|^8)"0"an"\a

```

Reverses the string, splits it into sections of three, reverses it again, then chooses the appropriate ending.

# Answer
> 1 votes
# Python 3, ~~110~~ ~~93~~ ~~91~~ ~~76~~ ~~74~~ ~~70~~ ~~65~~ 64 bytes

Here is a long one, but a simple one.

**Edit:** Corrected with thanks to isaacg. Saved some whitespace after the comparisons. Many bytes saved thanks to Timwi, Mego, benpop and Alissa.

```
n=input();print("a"+"n"*(len(n)%3>1and n[:2]in"118"or"8"==n[0]))

```

or for the same number of bytes.

```
n=input();print("a"+"n"[:len(n)%3>1and n[:2]in"118"or"8"==n[0]])

```

Ungolfed:

```
def a():
    n=input()
    if "8"==n[:1]:
        a = "n"
    elif len(n)%3 == 2 and (n[:2] in ["11", "18"]):
        a = "n"
    else:
        a = ""
    return "a"+a

```

# Answer
> 1 votes
# Japt, ~~28~~ 27 bytes

```
'a+'npUì v ¥8ª[B18]d¥UìA³ v

```

Try it online!

### Unpacked & How it works

```
'a+'npUì v ==8||[B18]d==UìAp3  v

'a+'np  "a" + "n".repeat(...)
Uì v ==8    First digit in decimal == 8
||          or...
[B18]d      [11,18].some(...)
==UìAp3  v  == First digit in base 10**3

```

# Answer
> 1 votes
# Java 10, 102 bytes

```
n->{var N=n+"";return(n>9&&"118".contains(N.substring(0,2))&N.length()%3>1)|N.charAt(0)==56?"an":"a";}

```

Try it online.

**Explanation:**

```
n->{                  // Method with integer parameter and String return-type
  var N=n+"";         //  Input integer as String
  return(n>9&&        //  If the input has at least two digits,
    "118".contains(N.substring(0,2))
                      //  and the first two digits are "11" or "18",
    &N.length()%3>1)  //  and the length modulo-3 is 2
   |N.charAt(0)==56?  //  Or if the first digit is an '8':
     "an"             //   Return "an"
   :                  //  Else:
     "a";}            //   Return "a"

```

# Answer
> 1 votes
# 05AB1E, ~~26~~ 21 bytes

```
₄внŽ4$2ôQàI8Å?+>„ans∍

```

Try it online or verify all test cases.

**Explanation:**

```
₄в          # Convert the (implicit) input-integer to base-1000 as list
  н         # Pop and push the first integer in this list
            #  i.e. 11234567 → [11,234,567] → 11
            #  i.e. 110000 → [110,0] → 110
            #  i.e. 8192 → [8,192] → 8
   Ž4$      # Push compressed integer 1118
      2ô    # Split it into parts of size 2: [11,18]
        Q   # Check for each if it's equal to the integer
         à  # Pop and push the maximum to check if either is truthy
            #  11 → [1,0] → 1
            #  110 → [0,0] → 0
            #  8 → [0,0] → 0
I           # Push the input-integer again
 8Å?        # Check if it starts with an 8
            #  11234567 → 0
            #  110000 → 0
            #  8192 → 1
+           # Add the two checks together
 >          # Increase it by 1
            #  1+0 → 1 → 2
            #  0+0 → 0 → 1
            #  0+1 → 1 → 2
  „an       # Push string "an"
     s∍     # And shorten it to a length equal to the integer
            #  2 → "an"
            #  1 → "a"
            #  2 → "an"
            # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž4$` is `1118`.

# Answer
> 1 votes
# GNU `sed -r` \+ BSD `number`, 34 bytes

```
s/(e?).*/number &/e
s//a\1/
y/e/n/

```

First we convert to English number. Then delete everything except a possible initial `e`, and prefix with `a`. Then convert the `e` (if present) to `n`. The only golfing trick is to match the optional `e` in the first substitution, so we can reuse the pattern in the following line.

## Demo

```
for i in 0 8 11 18 84 110 843 1111 1863 8192 \
    11000 18000 110000 180000 1141592 1897932 11234567 18675309
do printf "%'10d → %s\n" $i $(./66841.sed <<<$i)
done

```

```
         0 → a
         8 → an
        11 → an
        18 → an
        84 → an
       110 → a
       843 → an
     1,111 → a
     1,863 → a
     8,192 → an
    11,000 → an
    18,000 → an
   110,000 → a
   180,000 → a
 1,141,592 → a
 1,897,932 → a
11,234,567 → an
18,675,309 → an

```

# Answer
> 1 votes
# Perl 5 `-p`, 26 bytes

```
$_=a.n x/^8|^1[18](...)*$/

```

Try it online!

# Answer
> 0 votes
## TeaScript, 35 bytes

```
[18,11,8,80]I(+xh(x.n%3¶3©?'an':'a'

```

Try it here.

### Explanation

```
               xh(x.n%3¶3           get the relevant digits from the input
                                    xh compiles to x.head which returns the
                                    first n chars of x (implicit input)
                                    ¶ ('\xb6') compiles to ||
              +                     cast the result to an integer since
                                    .includes does a strict comparison
                         ©          ('\xa9') compiles to ))
[18,11,8,80]                        array of the special cases
            I(                      I( is an alias for .includes( which
                                    returns true if the array contains the
                                    argument
                          ?'an':'a' finally, return 'an' if the array
                                    contains the number, 'a' otherwise

```

# Answer
> 0 votes
## Python 2.7, 66

```
s=`input()`
print['a','an'][s[:1]=='8'or s[:2]in len(s)%3/2*'118']

```

Obviously not as short as the `lambda` one.

# Answer
> 0 votes
# QuadS, 32 bytes

```
'a',⍵
^8.*|^1[18](...)*$
⊃⍵L/'n'

```

Try it online!

# Answer
> 0 votes
# Stax, 25 bytes

```
â-x▬♪°∞▄'δL|÷æ╪║>₧4¢ÿ·7åR

```

Run and debug it

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

```
Vk|Eh       get the first "digit" after converting to base 1000
AJ|Eh       get the first "digit" after converting to base 100
c20>9*^/    if the result is greater than 20, divide it by 10 again
"AMj"!#     is the result one of [8, 11, 18]?
^           increment by 1
.an(        keep that many characters of the string "an"

```

Run this one

# Answer
> 0 votes
# C++, ~~80~~ 79 bytes

```
[](int i){for(;i>999;i/=1e3);return i-11&&i-18&&i/100-8&&i/10-8&&i-8?"a":"an";}

```

It turned out 4 bytes shorter to explicitly test against 8xx and 8x than to have another `/=10` loop, like this:

```
[](int i){for(;i>999;i/=1e3);for(i==11|i==18?i=8:0;i>9;i/=10);return i-8?"a":"an";}

```

## Demo

```
#include <locale>
#include <cstdio>
int main(int argc, char**argv)
{
    auto const f =
        [](int i){for(;i>999;i/=1e3);return i-11&&i-18&&i/100-8&&i/10-8&&i-8?"a":"an";}
    ;

    std::locale::global(std::locale{""});
    for (int i = 1;  i < argc;  ++i) {
        auto const n = std::stoi(argv[i]);
        printf("%'10d → %s\n", n, f(n));
    }
}

```

```
         0 → a
         8 → an
        11 → an
        18 → an
        84 → an
       110 → a
       843 → an
     1,111 → a
     1,863 → a
     8,192 → an
    11,000 → an
    18,000 → an
   110,000 → a
   180,000 → a
 1,141,592 → a
 1,897,932 → a
11,234,567 → an
18,675,309 → an

```

# Answer
> 0 votes
# Whitespace, 243 bytes

```
[S S S T    T   S S S S T   N
_Push_97_a][T   N
S S _Print_as_character][S S S T    N
_Push_1][S N
S _Duplicate_1][S N
S _Duplicate_1][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S S T N
_Create_Label_LOOP][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S S _Add][S N
T   _Swap_top_two][S N
S _Duplicate][S S S T   T   S S T   S S N
_Push_100][T    S S T   _Subtract][N
T   T   T   N
_If_negative_jump_to_Label_TWO_DIGITS][S S S T  S ST    S N
_Push_10][T S T S _Integer_division][N
S N
S T N
_Jump_to_Label_LOOP][N
S S T   N
_Create_Label_TWO_DIGITS][S N
S _Duplicate][S S S T   S S S N
_Push_8][T  S S T   _Subtract][N
T   S S S N
_If_zero_jump_to_Label_PRINT_n][S N
S _Duplicate][S S S T   S T T   N
_Push_11][T S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_2_MOD_3][S N
S _Duplicate][S S S T   S S T   S N
_Push_18][T S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_2_MOD_3][S S S T    S ST    S N
_Push_10][T S T S _Integer_division][S N
S _Duplicate][N
T   S N
_If_0_jump_to_Label_EXIT][N
S N
T   N
_Jump_to_Label_TWO_DIGITS][N
S S S N
_Create_Label_2_MOD_3][S N
T   _Swap_top_two][S S S T  T   N
_Push_3][T  S T T   _Modulo][S S S T    S M
_Push_2][T  S S T   _Subtract][N
T   T   N
_If_negative_jump_to_Label_EXIT][N
S S S S N
_Create_Label_PRINT_n][S S S T  T   S T T   T   S N
_Push_110_n][T  N
S S _Print_as_character][N
S S N
_Create_Label_EXIT]

```

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

Try it online (with raw spaces, tabs and new-lines only).
Program stops with an error: No exit found.

**Explanation in pseudo-code:**

```
Print "a"
Integer input = STDIN as integer
Integer counter = 1
Start LOOP:
  counter = counter + 1
  If(input < 100)
    Jump to function TWO_DIGITS
  input = input integer-divided by 10
  Go to next iteration of LOOP

function TWO_DIGITS:
  If(input == 8)
    Jump to function PRINT_n
  If(input == 11 or input == 18)
    Jump to function 2_MOD_3
  input = input integer-divided by 10
  If(input == 0)
    Exit program
  Recursive call to TWO_DIGITS

function 2_MOD_3:
  If(counter modulo-3 != 2)
    Exit program
  Jump to function PRINT_n

function PRINT_n:
  Print "n"
  Exit program

```

# Answer
> -1 votes
# Perl, ~~71~~ ~~55~~ 49 bytes

```
$_=<>;$_=/^8/||/^1[18]/&&length%3==1?'an':'a';say

```

I knew the ternary operator would help one day...

Let me break this down.

* `$_=<>` accepts a number as input.
* The big `$_=...` block will set the value of `$_` after it's used.
    + `...?...:...` is the ternary operator. If the condition (first argument) is true, it returns the second argument. Otherwise, it returns the third.
    + `/^8/||(/^1[18]/&&length%3==2)` checks to see if the number starts with 8 or begins with 11 or 18 (`1[18]` accepts either) and has a length mod 3 of 2.
    + If that's true, `$_` is set to `an`. Otherwise, it's set to `a`.
* It then prints out the contents of `$_` (either `a` or `an`) with `say`.

**Changes**

* Saved 16 bytes thanks to msh210.
* Saved 6 bytes by removing parens and using defaults.

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


title: Running Merge Conflict

text:
# Question
Title: Running Merge Conflict
When using a tool such as git to merge two files, a conflict could be detected and added to the result of the merge.

A merge of these two files:

my file:

```
Common line of code 1
Common line of code 2
my lines
Common line of code 3
Common line of code 4

```

their file:

```
Common line of code 1
Common line of code 2
their lines
Common line of code 3
Common line of code 4

```

would result in:

```
Common line of code 1
Common line of code 2
<<<<<<< Mine
my lines
=======
their lines
>>>>>>> Theirs
Common line of code 3
Common line of code 4

```

See Conflict Marker Lines

Resolving this conflict with *Mine* would create this file:

```
Common line of code 1
Common line of code 2
my lines
Common line of code 3
Common line of code 4

```

Resolving this conflict with *Theirs* would create this file:

```
Common line of code 1
Common line of code 2
their lines
Common line of code 3
Common line of code 4

```

The objective of this challenge is to write a source file that contains a conflict and still compiles/executes.

Write a source file which:

1. contains one valid, two-way, conflict marked by the proper patch conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) Mine and Theirs file descriptors after the markers are optional.
2. compiles/executes without errors/warnings if the markers remain a part of the source
3. compiles/executes without errors/warnings if the conflict is resolved by using *mine*
4. compiles/executes without errors/warnings if the conflict is resolved by using *theirs*
5. outputs "Hello Conflict" when compiling/executing the conflicted file
6. outputs "Hello Mine" when compiling/executing the mine version
7. outputs "Hello Theirs" when compiling/executing the theirs version

The markers should be located in the source file in such a way that kdiff3 recognizes the conflict.

Standard loopholes are forbidden.

The shortest code wins.

Score is the length of the conflicted source

# Answer
# Jelly, 51 bytes

```
<<<<<<<
“½&;»
“£<Ø»
=======

“8ẉI»
>>>>>>>
“¢5Ṛ»;2£

```

Try it online!

## Explanation

The conflict markers here are positioned so that one of three lines becomes the second line of the program after the conflict is resolved; this will be a constant, named . The second line of the original program encodes the string `" Conflict"` (in Jelly's compressed notation); the third line encodes the string `" Mine"` (this will become the second line if the conflict is resolved as mine); the sixth line encodes the string `" Theirs"` (and will become the second line if the conflict is resolved as theirs).

The main program is always the last line, no matter how many lines before it are deleted. It takes the compressed encoding of `"Hello"`, and appends (`;`) the value of  to it, thus producing the desired output.
> 2 votes

# Answer
## JavaScript (ES6), ~~102~~ ~~94~~ ~~93~~ 90 bytes

```
console.log('Hello',(a=`
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict`.split`
`)[6]||a[1])

```

If the conflict has been resolved, then there is no sixth line, so it prints the now first line instead. Edit: Saved 3 bytes thanks to @nderscore.
> 13 votes

# Answer
# Brachylog, ~~68~~ ~~67~~ 66 bytes

```
"Hello "wċ₂↰₁w∨"Conflict"w
<<<<<<<
"Mine"
=======
"Theirs"
>>>>>>>

```

Try it online!

Try the `"Hello Mine"` version here

Try the `"Hello Theirs"` version here

### Explanation

Thankfully, `<<<<<<<`, `=======` and `>>>>>>>` are all valid rule definitions in Brachylog. They respectively mean:

* Input is less than an implicit varible, itself less than..., etc., itself less than the output.
* All elements of the input are equal, and all elements of the input are equal, and..., and Input = Output
* Same as the first but greater than instead.

If we remove conflicts, we end up with `"Mine"` or `"Theirs"` on the second line, which means they become predicate number 1. Calling that predicate with `↰₁` on the first line will unify its input and output with `Mine` / `Theirs`, which we then print with `w`.

If we call `↰₁` on the conflicted file, we end up calling `<<<<<<<`. We therefore call that predicate with a string as input (using `ċ₂` \- coerce to string). `<` will fail with a string as input. We then put a disjunction `∨"Conflict"w` in the main predicate which states that if predicate 1 fails, then we print `Conflict` instead. `↰₁` with a string as input won't fail for the `"Mine"` or `"Theirs"` lines because they are strings.
> 10 votes

# Answer
# PHP, ~~74~~ 65 bytes

Note: uses IBM-850 encoding

```
Hello<?='
<<<<<<<
2:<?PU_~
=======
+;73"&_~
>>>>>>>
'^~ıÇ¼¡Ñ»¬áü;

```

Store to a file and run like this:

```
php -nf conflict.php

```

# Explanation

```
Hello       # Print "Hello"
<?='        # Print result of expression
<<<<<<<     # String with merge conflict
2:<?PU_~
=======
+;73"&_~
>>>>>>>
'
^           # XOR that string with...
~ıÇ¼¡Ñ»¬áü; # ... this string, negated.

```

The binary XOR results in either of the following 3:

```
'
<<<<<<<
' ^ ~'ıÇ¼¡Ñ»¬áü'
==> ' Conflict'
--------------------------------------------------------------------------
'
2:<?PU_~' ^ ~'ıÇ¼¡Ñ»¬áü'
==> ' Mine' (right padded with nul bytes)
--------------------------------------------------------------------------
'
+;73"&_~' ^ ~'ıÇ¼¡Ñ»¬áü'
==> ' Theirs' (right padded with nul bytes)

```

# Tweaks

* Saved 9 bytes by using binary logic on strings
> 9 votes

# Answer
# Pip, 61 bytes

```
"Hello ".("Conflict
<<<<<<<
Mine
=======
Theirs
>>>>>>>
"^n7)

```

Try it online!

Everything between `""` is a string. We split the large string on newlines (`"..."^n`) and take the 7th element with cyclical indexing (`(___7)`). For the conflicted version, there are seven lines, so index 7 is equivalent to index 0 and we get `Conflict`. For the resolved versions, there are three lines, so index 7 is equivalent to index 1 and we get `Mine`/`Theirs`. Then concatenate `"Hello "` to the front and autoprint.
> 7 votes

# Answer
## Batch, ~~133~~ 129 bytes

```
@set s=Theirs
@goto t
<<<<<<<
:t
@set s=Mine
@goto m
=======
:m
@set s=Conflict
@goto t
>>>>>>>
:t
:m
echo Hello %s%

```

Explanation: The `goto` statement goes to the next label it can find. In the case of the conflict, this just ends up skipping the conflict markers, and `s` gets its final value. In the case of resolving with Mine, the gotos have no effect, but the last `set` no longer exists, so the result is Mine. In the case of resolving with Theirs the inital `goto` bypasses the remaining `set` so the result is its initial value. Edit: Saved 4 bytes thanks to @DLosc.
> 6 votes

# Answer
## Python 2, ~~88~~ 87 bytes

```
print 'Hello','''
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict'''.split('\n')[1::5][-1]

```

Prints the sixth or (now) first line as appropriate.
> 4 votes

# Answer
# .COM opcode, 77 bytes

```
0000h: B4 09 BA 17 01 CD 21 BA 1F 01 80 3E 1F 01 3C 75 ; ......!....>..<u
0010h: 03 BA 44 01 CD 21 C3 48 65 6C 6C 6F 20 24 0A 3C ; ..D..!.Hello $.<
0020h: 3C 3C 3C 3C 3C 3C 0A 4D 69 6E 65 24 0A 3D 3D 3D ; <<<<<<.Mine$.===
0030h: 3D 3D 3D 3D 0A 54 68 65 69 72 24 0A 3E 3E 3E 3E ; ====.Their$.>>>>
0040h: 3E 3E 3E 0A 43 6F 6E 66 6C 69 63 74 24          ; >>>.Conflict$

        org 100h
        mov ah, 9
        mov dx, str1
        int 21H
        mov dx, str2
        cmp [str2], byte '<'
        jne $+5
        mov dx, str3
        int 21H
        ret

str1    db 'Hello $', 10
str2    db '<<<<<<<', 10
        db 'Mine$', 10
        db '=======', 10
        db 'Their$', 10
        db '>>>>>>>', 10
str3    db 'Conflict$'

```

If a space after `<<<<<<<` allowed, 75 bytes

```
0000h: B4 09 BA 0D 01 CD 21 BA 1E 01 CD 21 C3 48 65 6C ; ......!....!.Hel
0010h: 6C 6F 20 24 0A 3C 3C 3C 3C 3C 3C 3C 20 0A 43 6F ; lo $.<<<<<<< .Co
0020h: 6E 66 6C 69 63 74 24 4D 69 6E 65 24 0A 3D 3D 3D ; nflict$Mine$.===
0030h: 3D 3D 3D 3D 0A 2A 2A 2A 2A 2A 2A 2A 2A 54 68 65 ; ====.********The
0040h: 69 72 24 0A 3E 3E 3E 3E 3E 3E 3E                ; ir$.>>>>>>>

        org 100h
        mov ah, 9
        mov dx, str1
        int 21H
        mov dx, str2
        int 21H
        ret

str1    db 'Hello $', 10
        db '<<<<<<< ', 10
str2    db 'Conflict$'
        db 'Mine$', 10
        db '=======', 10
        db '********Their$', 10
        db '>>>>>>>'

```
> 3 votes

# Answer
# Retina, 57 bytes

```

Hello
$
<<<<<<<
Mine
=======
Theirs
>>>>>>>
<+
Conflict
```

Try it online!

Try the "Mine" version

Try the "Theirs" version

**Explanation of Conflict program**

As is often the case with Retina, this program contains many replace stages.

```

Hello
```

Replace the empty/non-existent input with `Hello`.

```
$
<<<<<<<

```

Replace the end of the working string with `<<<<<<<`

```
Mine
=======

```

Replace `Mine` with `=======`. Since `Mine` doesn't appear anywhere in the working string, this does nothing.

```
Theirs
>>>>>>>

```

Replace `Theirs` with `>>>>>>>`. Same deal as with `Mine`; `Theirs` doesn't appear, so the replacement does nothing.

```
<+
Conflict

```

Replace a sequence of `<` with `Conflict`. We added `<<<<<<<` to the end of the string on the first replacement, so the working string becomes `Hello Conflict`, which is implicitly output at the end of the program.

**Explanation of Mine/Theirs programs**

When the conflict is resolved, the code will look like this:

```

Hello
$
Mine
<+
Conflict
```

```

Hello
```

Same as before, starting with the string `Hello`.

```
$
Mine

```

Now instead of appending `<<<<<<<` to `Hello`, we append `Mine`.

```
<+
Conflict

```

Next, we replace a sequence of `<` with `Conflict`. But there are no `<`s in the string, so nothing happens.

The working string, `Hello Mine`, is implicitly output. The "Theirs" program works the same way.
> 2 votes

# Answer
# OIL, ~~88~~ ~~80~~ 77 bytes

```
4
2
Hello
10
Conflict
16
16
8
4
11
3
<<<<<<<
Mine
=======
Theirs
>>>>>>>
4
4

```

`4` `2` is printing line 2 (`Hello`), `10` tests whether line 0 (`4`) is identical with line 16 (the one that contains a `4` when the conflict exists) and jumps to either line 16 or line 8 depending on the result. If it existed, `4` `4` prints line 4 (`Conflict`). If it didn't, `4` `11` prints either `Mine` or `Theirs`, depending on what was merged, and `3` exits.
> 1 votes

# Answer
# Java 145 Bytes

```
()->{String s = "Hello ";/*
<<<<<<<
*/s+="Mine";/*
=======
*/s+="Theirs";/*
>>>>>>>
*/if(s.length()>15)s="Hello Conflict";System.out.println(s);}

```

Java has no multiline strings so some Comment trickery was needed
> 1 votes

# Answer
# Bash, 76 bytes

**Golfed**

```
sed 's/^/Hello /;s/<\+/Conflict/;q'<<E
<<<<<<<
Mine
=======
Theirs
>>>>>>>
E

```

**How it works**

Uses here doc, to feed the source text to *sed*.

*Sed* will prepend the first line it read with "Hello ", replace the `<<<<<<<` string by "Conflict" and then quit (`q`).

Try It Online !
> 1 votes

# Answer
# ES6 (Javascript), ~~83~~, 82 bytes

**Golfed**

```
alert("Hello "+((T=`\
<<<<<<<
Mine
=======
Theirs
>>>>>>>
`)[1]>"<"?T:"Conflict"))

```

**Try It**

```
alert("Hello "+((T=`\
<<<<<<<
Mine
=======
Theirs
>>>>>>>
`)[1]>"<"?T:"Conflict"))

alert("Hello "+((T=`\
Mine
`)[1]>"<"?T:"Conflict"))

alert("Hello "+((T=`\
Theirs
`)[1]>"<"?T:"Conflict"))
```
> 1 votes

# Answer
# C (GCC), 110 bytes

Function submission.

```
f(){char*s[]={0,"Mine","Theirs","Conflict"};printf("Hello %s",s[/*
<<<<<<<
*/1/*
=======
*/+2/*
>>>>>>>
*/]);}

```

Approach inspired by masterX244's Java solution.

## TIOs
> 1 votes

# Answer
# Java 8, 108 bytes

This is a lambda accepting empty input and returning nothing.

```
n->System.out.print("Hello "+",Mine,Theirs,Conflict".split(",")[/*
<<<<<<<
*/1/*
=======
*/+2/*
>>>>>>>
*/])

```

Try It Online

Approach inspired by masterX244's Java solution.
> 1 votes

# Answer
## Perl 5, 68 bytes

Updated after realising that the version with 6 of each delimiter works as intended, but with the actual 7 delimiters, it doesn't... Oops...

```
say"Hello ",q
<<<<<<<
!Mine!;0
=======
!Theirs!;0
>>>>>>>
&&Conflict

```

Try the conflict online!

Try mine online!

Try itheirs online!
> 1 votes

---
Tags: code-golf, restricted-source, source-layout
---


title: Binary tree rotations

text:
# Question
Title: Binary tree rotations
Balanced binary search trees are essential to guarantee *O(log n)* lookups (or similar operations). In a dynamic environment where a lot of keys are randomly inserted and/or deleted, trees might degenerate to linked lists which are horrible for lookups. Thus there are various kinds of self-balancing binary trees that counteract this effect (such as AVL trees or splay trees). These trees are based on different kinds of rotations that re-balance the tree.

## Rotations

In this challenge we'll only look at single right-rotations, such a rotation (left-rotation would be symmetric) looks like this:

```
    5            3
   / \          / \
  3   6   =>   1   5
 / \              / \
1   4            4   6

```

If any of the leaves `1`,`4` or `6` had left or right sub-trees a rotation would simply keep them there. If this is a subtree of a larger tree, we'd simply "cut it off" at the node `5` and "re-attach" the rotated tree (now node `3`) to that node.

## Challenge

Given a binary search tree1 and a key right-rotate the tree on that node as described above. The key provided in the above example would be `5`.

## Rules and I/O

* you may use any type for keys as long as there is a bijection between the keys of your choice and those of the test cases
* you may choose any representation for binary trees as long there's no ambiguity (eg. `[3,[]]` is ambiguous unless otherwise specified) and it's natural for your language of choice
* since the input will always be a binary search tree there are no duplicate keys
* you may assume that the key is contained in the tree
* you may assume that node containing the key has a left child
* you may **not** assume a right subtree under the provided key
* you may **not** assume that the tree is unbalanced before the rotation
* you may **not** assume that the tree is balanced after the rotation
* you may use any default I/O method
* your submission may be a function returning the tree or full program printing the solution

## Test cases

These examples represent a tree as follows

* if it's a leaf: `[]`
* if it's a tree with key `x` and both subtrees are leaves: `[x]`
* if it's a tree with key `x` and subtrees `left` `right`: `[x,left,right]`

The first example is the one provided in the section **Rotations**. If for some reason you need a graphical representation of them, here2 you go.

```
5 [5,[3,[1],[4]],[6]]  ->  [3,[1],[5,[4],[6]]]
5 [5,[3,[1],[4]],[]]  ->  [3,[1],[5,[4],[]]]
5 [5,[3,[],[4]],[6]]  ->  [3,[],[5,[4],[6]]]
5 [5,[3,[1],[]],[]]  ->  [3,[1],[5]]
4 [8,[4,[2,[1],[3]],[6,[5],[7]]],[12,[10,[9],[11]],[14,[13],[15]]]]  ->  [8,[2,[1],[4,[3],[6,[5],[7]]]],[12,[10,[9],[11]],[14,[13],[15]]]]
8 [10,[8,[6,[4,[2,[],[3]],[5]],[7]],[9]],[11]]  ->  [10,[6,[4,[2,[],[3]],[5]],[8,[7],[9]]],[11]]
10 [10,[8,[6,[4,[2,[],[3]],[5]],[7]],[9]],[11]]  ->  [8,[6,[4,[2,[],[3]],[5]],[7]],[10,[9],[11]]]
9 [6,[3,[2],[5]],[9,[8],[12,[11],[15,[14],[]]]]]  ->  [6,[3,[2],[5]],[8,[],[9,[],[12,[11],[15,[14],[]]]]]]
7 [7,[5,[3,[1],[4]],[6]],[8]]  ->  [5,[3,[1],[4]],[7,[6],[8]]]
15 [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]  ->  [17,[9,[5,[2,[0],[4]],[8]],[13,[11,[10],[12]],[15,[14],[16]]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]
21 [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]  ->  [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[19,[18],[21,[20],[24,[22],[25]]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]

```

---

1: meaning that for any node all the keys in the left subtree will be smaller than that key and all the keys in the right subtree are greater than it

2: to prevent link-rot, I embedded them as a comment

# Answer
> 8 votes
# Haskell, ~~93~~ ~~92~~ ~~84~~ ~~83~~ 82 bytes

```
data B=B[B]Int|L
k!B[l@(B[x,y]a),r]n|k<n=B[k!l,r]n|k>n=B[l,k!r]n|1>0=B[x,B[y,r]k]a

```

Thanks to @BMO, @alephalpha and @Laikoni for a byte each and @nimi for eight bytes!

Try it online!

# Answer
> 6 votes
# Vim, 25 bytes

Takes the input in the buffer - space separated key and tree. The tree is expected to be represented as follows:

* leaf: `[]`
* node with key `k`, left child `<left>` and right child `<right>`: `[ k <left><right>]`

Not the spaces around the key `k` which are important, such that the solution works for arbitrary trees.

```
"adw/ <C-r>a⏎3dw%l"apr[%xl%i]

```

Try it online!

### Explanation

```
"adw                           " delete the key and trailing space, keep in register a
    / <C-r>a⏎                  " move cursor to the key surrounded with spaces
             3dw               " remove key and [ (move left node to top)
                %l             " move cursor to the right subtree
                  "ap          " insert key there
                     r[        " insert a [ (appending subtree to key)
                       %       " move to the end of new left subtree
                        x      " remove ] (fix parentheses)
                         l%    " move to the end of new right subtree
                           i]  " insert ] (fix parentheses)

```

### Preview

Here's a preview of the first test case, generated with this script by Lynn:

# Answer
> 3 votes
# Wolfram Language (Mathematica), 30 bytes

```
#2/.a_~b_~c_~#~d_:>b[a,c~#~d]&

```

Try it online!

A tree represented as follows:

* if it's a leaf: `$` (you can replace it by any value which is not a key)
* if it's a tree with key `x` and subtrees `left` `right`: `x[left,right]`

For example, the tree in the first test case is represented by `5[3[1[$,$],4[$,$]],6[$,$]]`.

### Explanation:

```
#2                                the second input
  /.                              replace
    a_~b_~c_~#~d_                 #[b[a,c],d], where # is the first input
                 :>               by
                   b[a,c~#~d]     b[a,#[c,d]]
                             &    define a function

```

# Answer
> 3 votes
# Common Lisp, 146 bytes

```
(defun r(k a)(cond((not a)a)((=(car a)k)`(,(caadr a),(cadadr a)(,(car a),(car(cddadr a)),(caddr a))))(t`(,(car a),(r k(cadr a)),(r k(caddr a))))))

```

Try it online or verify all the testcases!

A tree is represented as follows:

* an empty tree is represented as `nil` (or equivalently in Common Lisp as the empty list `()`)
* a non-empty tree is represented as a list of three elements `(node left-subtree right-subtree)` (so a leaf `L` is represented as `(L nil nil)`).

# Answer
> 2 votes
# JavaScript (Node.js), 70 bytes

```
n=>f=a=>n-a[0]?(a[i=n<a[0]?1:2]=f(a[i]),a):(i=a[1],a[1]=i[2],i[2]=a,i)

```

Try it online! Link includes test cases. All nodes must have left and right entries but they can be `[]` indicating no subtree on that side. As an abbreviation the test suite uses `l(N)` to indicate that `N` is a leaf and `l(N,L)` to indicate that `N` has a left subtree `L` but no right subtree both on input and output.

# Answer
> 2 votes
# Python 2, 85 bytes

```
R=lambda T,k:k in T and T[1][:2]+[[T[0],T[1][2],T[2]]]or T[:1]+[R(i,k)for i in T[1:]]

```

Try it online!

Input format:

* Tree: `[KEY, LEFT_SUBTREE, RIGHT_SUBTREE]`
* Leaf: `[]`

# Answer
> 2 votes
# Jelly, 24 bytes

```
ñ
Ḣ,1ịṪƊṭ@ṪṭḢð{Ḣ;ç€ɗ¹¡i?

```

Try it online!

Warning: Normally, the top line shouldn't exist, and the bottom line should have a `ß`, not a `ç`. However, clever chain tricks and `ß` don't go well together, due to `ß`'s variable arity. Technically, I could have still omitted the top line, but then the result would have had to be a full program, since otherwise it would have to be able to be incorporated as its own line inside any program, which isn't possible unless you're lucky. This means that, unfortunately, the output would've had an ambiguous representation, because, when you submit a full program, what gets actually output counts, and not what the result technically is before the program closes. So, in order to not make a mess with both recursion and proper string representation, I've decided to submit a 2-line function, where the top line's job is just to call the bottom one. The consequence? A huge waste of 2 precious and valuable bytes. In Jelly's (and Dennis's, as well as every other contributor's) defense, the language is still under active development, and is now experiencing a big wave of new features.

---
Tags: code-golf, graph-theory, data-structures, binary-tree
---


title: Beginners 10x10 multiplication matrix

text:
# Question
Title: Beginners 10x10 multiplication matrix
I was looking for a very easy task to look how short of a code can be produced on a beginners exercise.

The goal is to produce a simple table that looks like this common java/c# code is about 4 lines. So get your golfing-languages ready ;) Try to align the matrix in any way it is readable.

```
1 2 3    .. 10

2 4 6    .. 20

3 6 9    .. 30

. . .    .. .

10 20 30 .. 100

```

**EDIT:** The first answer below shows a propper alignment and solution

# Answer
> 3 votes
# MATL, 5 bytes

```
10:&*

```

Try it online!

```
10:    % Range: [1,2,3,4,5,6,7,8,9,10]
   &*  % Multiply the range by itself transposed, with broadcasting.

```

Outputs:

```
 1   2   3   4   5   6   7   8   9  10
 2   4   6   8  10  12  14  16  18  20
 3   6   9  12  15  18  21  24  27  30
 4   8  12  16  20  24  28  32  36  40
 5  10  15  20  25  30  35  40  45  50
 6  12  18  24  30  36  42  48  54  60
 7  14  21  28  35  42  49  56  63  70
 8  16  24  32  40  48  56  64  72  80
 9  18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90 100

```

# Answer
> 2 votes
# Ruby, ~~48 45~~ 44 bytes

```
1.upto(10){|x|puts"%4d"*10%[*x.step(100,x)]}

```

Try it online!

-3 bytes thanks to manatwork then -1 thanks to Kirill L.

But I still think there must be a better way.

# Answer
> 1 votes
# Jelly, 5 bytes

```
⁵×þ`G

```

Try it online!

Prints the following text:

```
  1   2   3   4   5   6   7   8   9  10
  2   4   6   8  10  12  14  16  18  20
  3   6   9  12  15  18  21  24  27  30
  4   8  12  16  20  24  28  32  36  40
  5  10  15  20  25  30  35  40  45  50
  6  12  18  24  30  36  42  48  54  60
  7  14  21  28  35  42  49  56  63  70
  8  16  24  32  40  48  56  64  72  80
  9  18  27  36  45  54  63  72  81  90
 10  20  30  40  50  60  70  80  90 100

```

Another 5-byter.

# Answer
> 1 votes
# Octave, ~~18~~ 17 bytes

*1 byte saved thanks to @StewieGriffin*

```
disp((x=1:10)'*x)

```

Try it online!

Or, as @maxb points out: more readable, same length:

```
x=1:10;disp(x'*x)

```

# Answer
> 1 votes
# , 32 bytes

```
write(format((x=1:10)%o%x),1,10)

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~64~~ 55 bytes

```
i=1
exec"print'%4d'*10%tuple(range(i,11*i,i));i+=1;"*10

```

Try it online!

# Answer
> 0 votes
# Brainfuck, 1147 bytes

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

```

Try it online!

Thanks for Jo King for this solution !

## Old answer, 1164 bytes

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

```

Try it online!

Oh god, this ended up way longer than I expected.

Here is how i did it :

```
Store values 48 ('0'), 32 (space) and 10 (new line)
+++++[>+++++[>++>+<<-]>>+>++<<<<-]>>-->++<
Print 1st line
+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<--------.-.>>.<<
Print 2nd line
++.>..<++.>..<++.>..<++.>..<-------.-.>.<+.+.>.<-.+++.<.>---.+++++.<.>-----.+++++++.<.>------.--.>>.<<
Etc.
+++.>..<+++.>..<+++.>..<--------.+.>.<-.++++.>.<----.+++++++.>.<------.-.>.<+.++.>.<--.+++++.>.<----.---.>>.<< Etc.
++++.>..<++++.>..<-------.+.>.<-.+++++.>.<----.--.>.<++.++.>.<--.++++++.>.<-----.-.>.<+.+++.>.<--.----.>>.<<
+++++.>..<----.-.>.<+.++++.>.<---.--.>.<++.+++.>.<--.---.>.<+++.++.>.<-.----.>.<++++.+.>.<.-----.>>.<<
++++++.>..<-----.+.>.<-.+++++++.>.<------.++.>.<-.---.>.<+++.+++.>.<--.--.>.<++.++++.>.<---.-.>.<++.------.>>.<<
+++++++.>..<------.+++.>.<--.-.>.<+.++++++.>.<-----.++.>.<-.--.>.<++.+++++.>.<----.+.>.<.---.>.<++++.-------.>>.<<
++++++++.>..<-------.+++++.>.<----.++.>.<-.-.>.<++.----.>.<++++.++++.>.<---.+.>.<.--.>.<+++.-----.>.<++++++.--------.>>.<<
+++++++++.>..<--------.+++++++.>.<------.+++++.>.<----.+++.>.<--.+.>.<.-.>.<++.---.>.<++++.-----.>.<++++++.-------.>.<++++++++.---------.>>.<<
+.-.>.<++.--.>.<+++.---.>.<++++.----.>.<+++++.-----.>.<++++++.------.>.<+++++++.-------.>.<++++++++.--------.>.<+++++++++.---------.>.<+.-..

```

# Answer
> 0 votes
# APL+WIN, 9 bytes

```
n∘.×n←⍳10

```

Try it online! Courtesy of Dyalog Classic

Outer product multiplication of a vector of integers 1 to 10

# Answer
> 0 votes
## Batch, 177 bytes

```
@echo off
for /l %%i in (1,1,10)do call:r %%i
exit/b
:r
set s=
for /l %%j in (1,1,10)do set/an=%1*%%j&call:c
echo %s%
:c
set n= %n%
if "%n:~3%"=="" goto c
set s=%s%%n%

```

# Answer
> 0 votes
# , 9 bytes

```
*/~1+i.10

```

Try it online!

# Answer
> 0 votes
# Red, 56 bytes

```
repeat n 10[repeat m 10[prin pad rejoin[n * m]4]print""]

```

Try it online!

# Answer
> 0 votes
# CJam, ~~24~~ 23 bytes

```
A,:)_m*{:*"%4d"e%}%A/:n

```

Try it online!

Alternative without pretty printing:

```
A,:)_m*{:*}%A/:p

```

# Answer
> 0 votes
# JavaScript (Node.js), 79 bytes

```
(_=[...".........."])=>_.map((a,i)=>Array.from({length:10},(v,k)=>(k+1)*(i+1)))

```

Try it online!

---
Tags: code-golf, kolmogorov-complexity, matrix
---


title: Divide them all

text:
# Question
Title: Divide them all
A Math.SE user have a funny game explained as such:

> 1. Pick a random positive integer X.
> 2. Add +1, 0, -1 to make it divisible by 3Keep track of how much you've added and subtracted. That is your "score"..
> 3. Divide by 3 to create a new X.
> 4. Repeat steps 2 and 3 until you reach one.

I'm expecting the shortest code to give the correct score and the decomposition (as a list of the following values \[+1;0;-1\]) given an integer input.

```
Input => Expected score => Expected decomposition #explanation
12 => -1 => 0-1 #(12/3 => (4 - 1) / 3 = 1
                             ^^^
25 => 0 => -1+10  (25 - 1) / 3 => (8 + 1) / 3 => (3 + 0) / 3 => 1
                      ^^^            ^^^            ^^^

9320 => -1 => +1+1-10-1+1-1-1 #(9320 + 1) / 3 => (3107 + 1) / 3 => (1036 - 1) / 3 => (345 + 0) /3 => (115 - 1) / 3 => (38 + 1) / 3 => (13 - 1) / 3 => (4 - 1) / 3
                                     ^^^               ^^^               ^^^              ^^^             ^^^             ^^^             ^^^            ^^^

```

# Answer
> 2 votes
# JavaScript (ES6), 46 bytes

Returns an array where:

* the last term is the sum
* all preceding terms are the decomposition

```
f=(n,s=0)=>n-1?[k=1-++n%3,...f(n/3|0,s+k)]:[s]

```

Try it online!

# Answer
> 1 votes
# Python 3, 53 bytes

Credit to Mr.Xcoder

```
f=lambda i,*s:i>1and f(-~i//3,*s,1--~i%3)or[s,sum(s)]

```

Try it online!

# Python 2, 55 bytes

```
f=lambda i,s=[]:i>1and f(-~i/3,s+[1--~i%3])or[s,sum(s)]

```

Try it online!

# Python 2, 58 bytes

```
i,s=input(),[]
while~-i:s+=1--~i%3,;i=-~i/3
print s,sum(s)

```

Try it online!

Returns list with decomposition and sum of it

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


title: Zero sum in python 2.7

text:
# Question
Title: Zero sum in python 2.7
Write a function in Python 2.7 that takes a list of integers as an argument. It should return True or False depending on whether there are any 2 integers in the argument list that sum to zero. \[4,-4,9,6,5\]

> > True

\[6,5,-3,2\]

> > False

# Answer
# Python 2, 32 bytes

```
lambda a:any(-n in a for n in a)

```

**Try it online!**
> 3 votes

# Answer
# , 23 bytes

```
function(x)any(-x%in%x)

```

Try it online!

If full programs are allowed:

### , 21 bytes

```
any((x=scan())%in%-x)

```

Try it online!
> 0 votes

---
Tags: python, c
---