title: Olympic Rings Sequence

text:
# Question
Title: Olympic Rings Sequence
## Challenge:

Given an index integer `n`, either output the `n`'th item in this sequence, or output the sequence up to and including index `n`:

```
25,25,7,28,29,20,21,22,23,14,35,26,7,28,29,20,16,29,12,15,28,21,14,17,30,13,16,29,12,15,28,21,10,6,12,18,15,11,7,13,19,17,13,9,15,21,18,14,10,16,22,19,15,11,17,23,20,16,12,18,24,21,17,13,19,25,23,19,15,21,27,24,20,16,22,28,25,21,17,23,29,16,13,9,15,21,18,14,10,16,22,20,16,12,18,24,21,17,13,19

```

## How does this sequence work?

*NOTE: In this explanation, index `n` is 1-indexed.*
Put the numbers `1` through `x` on two lines of length `n*6 - 1`, where `x` depends on the current iteration and the length of the numbers used, and then sum the digits of the `n`'th/right-most Olympic Rings of those two lines.

*The first number in the sequence is calculated as follows:*

```
The length of the lines are 5 (because 1*6 - 1 = 5):
12345
67891(0)

Then leave the digits in an Olympic Rings pattern:
1 3 5
 7 9

And sum them:
1+3+5+7+9 = 25

```

So `n=1` results in `25`.

*The second number in the sequence is calculated as follows:*

```
The length of the lines are 11 (because 2*6 - 1 = 11):
12345678910
11121314151(6)

Then leave the digits in the second/right-most Olympic Rings pattern:
      7 9 0
       4 5

And sum them:
7+9+0+4+5 = 25

```

So `n=2` results in `25`.

*The third number in the sequence is calculated as follows:*

```
The length of the lines are 17 (because 3*6 - 1 = 17):
12345678910111213
14151617181920212(2)

Then leave the digits in the third/right-most Olympic Rings pattern:
            1 2 3
             0 1

And sum them:
1+2+3+0+1 = 7

```

So `n=3` results in `7`.

*etc.*

## Challenge rules:

* When you output the `n`'th item in the sequence, you are allowed to take the input as 0-indexed instead of 1-indexed, but keep in mind that the calculations of `n*6 - 1` will then become `(n+1)*6 - 1` or `(n+1)*5 + n`.
* Single numbers of more than one digit can be split up at the end of the first line when we've reached the length `n*5 + n-1`, so it is possible that a number with 2 or more digits is partially the trailing part of line 1, and partially the leading part of line 2.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases:

Here is a paste-bin of the test cases 1-1,000, so feel free to choose any of them.

Some additional higher test cases:

```
1010:   24
1011:   24
2500:   19
5000:   23
7500:   8
10000:  8
100000: 25

```

# Answer
> 4 votes
# Husk, 16 bytes

```
ΣĊ2ṁ↑_5↑2CṁdN←*6

```

Try it online!

-3 bytes thanks to H.PWiz.

(Rushed) explanation:

```
ΣĊ2ṁ↑_5↑2CṁdN←*6⁰
Σ                 Sum
 Ċ2                Drop every second element
   ṁ↑_5             Map "take last 5 elements", then concatenate
       ↑2            Take first 2 elements
         C            Cut x into sublists of length y
          ṁdN          [1,2,3,4,5,6,7,8,9,1,0,1,1,1,2,1,3,...] (x)
             ←         Decrement (y)
              *6        Multiply with 6
                ⁰        First argument

```

# Answer
> 5 votes
## Retina, ~~70~~ ~~68~~ 62 bytes

```
.+
10**
.
$.>`
~(`.+
6*$+*
)`.(.+)
L`.{$.1}
%,-6`.

,2,9`.
*
_

```

Try it online!

### Explanation

Let's call the input **n**, and we'll use `3` as an example.

```
.+
10**

```

The `10**` is short for `10*$&*_` which replaces the input with a string of **10n** underscores.

```
.
$.>`

```

Now we replace each underscore with the length of the string up to and including that underscore. So this just results in the number from **1** to **10n** all concatenated together (**10n** is always enough to fill up two lines of the required length).

```
~(`.+
6*$+*

```

Eval! This and the next stage will generate the source code of another program, which is then run against that string of concatenated integers.

To generate that program, this stage first replaces the integers with a string of **6n** underscores (`$+` refers to the program's original input).

```
)`.(.+)
L`.{$.1}

```

Then replace those underscores with `L`.{…}`, where  is **6n-1** (the length of the lines we're looking at). So we've generated a regex, whose quantifier depends on the original input.

When this program gets eval'ed it matches chunks of length **6n-1**, of which there will be at least two. For our example input `3`, we end up with:

```
12345678910111213
14151617181920212
22324252627282930

```

Now we just need to extract the relevant digits.

```
%,-6`.

```

First, on each line (`%`) we remove all but the last five digits (`,-6`). That gives us

```
11213
20212
82930

```

Finally:

```
,2,9`.
*

```

We expand every other digit (`2`) in the first ten (`9`, this is 0-based) in unary. Those happen to be those in the Olympic Rings positions.

```
_

```

And we count the number of resulting underscores, to sum them and convert the result to decimal.

# Answer
> 3 votes
# Japt, ~~33~~ ~~32~~ ~~30~~ ~~29~~ ~~28~~ 27 bytes

Oh, this is not pretty!

Outputs the *n*th term, 1-indexed.

```
*6É
*2 õ ¬òU mt5n)¬¬ë2 ¯5 x

```

Try it

---

## Explanation

```
                         :Implicit input of integer U           :e.g., 3
*6É
*6                       :Input times 6                         :18
  É                      :Subtract 1                            :17
   \n                    :Assign the above to variable U

*2 õ ¬òU mt5n)¬¬ë2 ¯5 x
*2 õ                     :[1,U*2]                               :[1,2,3,...,33,34]
     ¬                   :Join to a string                      :"123...3334"
      òU                 :Partitions of length U                :["123...13","1415...212","22324...30","31323334"]
         m               :Map
          t5n)           :  Get last 5 characters               :["11213","20212","82930","23334"]
              ¬          :Join to a string                      :"11213202128293023334"
               ¬         :Split to an array                     :["1","1","2","1","3","2","0","2","1","2","8","2","9","3","0"],["2","3","3","3","4"]]
                ë2       :Get every second element              :["1","2","3","0","1","8","9","0","3","3"]
                   ¯5    :Get first 5 elements                  :["1","2","3","0","1"]
                      x  :Reduce by addition                    :7
                         :Implicit output of result

```

# Answer
> 3 votes
# Python 2, ~~94~~ 90 bytes

```
n=input()*6
s=''.join(map(str,range(n*2)))
print sum(map(int,s[n-5:n:2]+s[n*2-5:n*2-1:2]))

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~22~~ ~~21~~ 20 bytes

```
6*<xLJsô2£íε5£}SāÉÏO

```

Try it online!

**Explanation**

```
6*<                    # push input*6-1
   xL                  # leave it on the stack while pushing [1 ... 12*input-2]
     J                 # join the numbers to a single string
      sô               # split the string into pieces of size input*6-1
        2£             # take the first 2 such pieces
          í            # reverse each string
           ε5£}        # take the first 5 chars of each
               S       # split to a single list of digits
                ā      # push range [1 ... len(list)]
                 ÉÏ    # keep only the numbers in the list of digits which are odd in this
                   O   # sum

```

**Alternative 21 byte approach**

```
6*<©·LJƵYS24S®-ì®-(èO

```

# Answer
> 2 votes
# Jelly, 19 bytes

```
×6’µḤD€Ẏsḣ2ṫ€-4Ẏm2S

```

Try it online!

```
×6’µḤD€Ẏsḣ2ṫ€-4Ẏm2S Arguments: n (1-indexed)
×6                  Multiply by 6
  ’                 Decrement
   µ                Call that value N and start a new chain with argument N
    Ḥ               Double
      €             Create an inclusive range from 1 to 2N and call this link on it
     D               Get the decimal digits of each integer in the range
       Ẏ            Concatenate the lists of digits
        s           Split into length-N chunks
         ḣ2         Get the first two elements
            €-4     Map this link over the length-2 list with right argument -4
           ṫ         Get elements from this index onwards (supports negative indices too)
               Ẏ    Concatenate the two length-5 lists into one length-10 list
                m2  Take every second element starting from the first
                  S Sum

```

# Answer
> 2 votes
# Python 3, ~~129~~ 123 bytes

```
p=lambda r,x='',i=1:sum(map(int,str(x[6*r-2]+x[6*r-4]+x[6*r-6]+x[12*r-4]+x[12*r-6])))if len(x)>12*r-2else p(r,x+str(i),i+1)

```

Try It Online

This is pretty much messed up though, but works.

# Answer
> 2 votes
# Python 2, 97 bytes

```
n=input()*6;k=1;s=''
exec's+=`k`;k+=1;'*n*2
print sum(int(s[p])for p in(n-2,n-4,n-6,n*2-4,n*2-6))

```

Try it online!

# Answer
> 1 votes
# , 61, 58 57 bytes

```
g=.3 :'+/".,_2(2{.{.)\,_5{."1(2{.(-.6*y)]\;":&.>1+i.9*y)'

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~65 63~~ 56 bytes

```
->n{[2,4,6,4-n*=6,6-n].sum{|a|([*1..n*2]*'')[n-a].to_i}}

```

Try it online!

# Answer
> 1 votes
# Clean, ~~138~~ 101 bytes

```
import StdEnv
$n=sum(tl[toInt([c-'0'\\i<-[1..],c<-:toString i]!!(6*i+j))\\i<-[2*n-1,n-1],j<-[4,0,2]])

```

Try it online!

# Answer
> 1 votes
# Java 8, ~~138~~ ~~111~~ 109 bytes

```
n->{String s="";int r=0,i=1;for(n=n*6-1;i<3*n;s+=i++);for(i=5;i>0;r+=s.charAt(n+n*(i%2^1)-i--)-48);return r;}

```

I'll of course have to answer my own challenge. :)
I lost my initial code that I've used to create the test results in the challenge description, so I've just started over.

**Explanation:**

Try it online.

```
n->{                               // Method with integer as both parameter and return-type
  String s="";                     //  Temp String
  int r=0,                         //  Result-sum, starting at 0
      i=1;                         //  Index integer, starting at 1
  for(n=n*6-1;                     //  Replace the input with `n*6-1`
      i<3*n;                       //  Loop from 1 up to 3*n (exclusive)
      s+=i++);                     //   And append the temp-String with `i`
  for(i=5;i>0;                     //  Loop from 5 down to 0 (exclusive)
    r+=                            //   Add to the result-sum:
       s.charAt(               )-48);
                                   //    The character at index X, converted to a number,
                n+n*(i%2^1)-i--    //    with X being `n-i` (i=odd) or `n+n-i` (i=even)
  return r;}                       //  Return the result-sum

```

---
Tags: code-golf, number, sequence, arithmetic, integer
---


title: Bottom part of the Hourglass

text:
# Question
Title: Bottom part of the Hourglass
## Challenge:

**Input:** Three integers: bottom-edge length; starting amount of grains of sand; index

**Output:** Output the state of the bottom part of an hourglass at the given index, based on the given bottom-edge length and amount of grains of sand.

## Challenge rules:

* We simulate the grains of sand with digits 1-9
* We put the currently remaining amount of grains of sand at the top in the middle, following by a single character of your own choice (excluding digits, whitespaces and new-lines; i.e. `-`) on the line below it
* When the hourglass is being filled, we fill it per row, one digit at a time
* When the sand can go either left or right, we ALWAYS go right (the same applies to balancing the remaining amount of grains of sand above the hour glass)
* When we've reached 9 it's filled, and we can't fit any more sand at that specific place in the hourglass
* The amount of grains of sand left are also always rightly aligned
* Once the bottom halve of the hourglass is completely filled, or the amounts of grains of sand left reaches 0, we can't go any further, and this would be the output for all indexes beyond this point
* Both 0-indexed or 1-indexed is allowed, and please specify what you've used in your answer.
* Trailing and leading spaces and a single trailing or leading new-line are optional
* You are allowed to use any other character instead of a zero to fill up empty spaces of the bottom part of the hourglass (excluding digits, new-lines, or the character you've used as neck), if you choose to display them.
* The bottom-edge length will always be odd
* The bottom-edge length will be `>= 3`; and the amounts of grains of sand `>= 0`
* If you want you are also allowed to print all states up to and including the given index
* You can assume the (0-indexed) index will never be larger than the total amount of grains of sand (so when there are 100 grains of sand, index 100 is the maximum valid index-input).
* The first index (0 for 0-indexed; 1 for 1-indexed) will output an empty hourglass with the amount of grains of sand above it.

**Example:** Pictures (or ascii-art) say more than a thousand words, so here is an example:

Input bottom-edge length: `5`
Input amount of grains of sand: `100`
Instead of a current index, I display all steps here:

Output for all possible indexes with bottom-edge length `5` and amount of grains of sand `100`:

```
 100
  -
  0
 000
00000

  99
  -
  0
 000
00100

  98
  -
  0
 000
00110

  97
  -
  0
 000
01110

  96
  -
  0
 000
01111

  95
  -
  0
 000
11111

  94
  -
  0
 000
11211

  93
  -
  0
 000
11221

  92
  -
  0
 000
12221

  91
  -
  0
 000
12222

  90
  -
  0
 000
22222

  89
  -
  0
 000
22322

  88
  -
  0
 000
22332

  87
  -
  0
 000
23332

  86
  -
  0
 000
23333

  85
  -
  0
 000
33333

  84
  -
  0
 000
33433

  83
  -
  0
 000
33443

  82
  -
  0
 000
34443

  81
  -
  0
 000
34444

  80
  -
  0
 000
44444

  79
  -
  0
 000
44544

  78
  -
  0
 000
44554

  77
  -
  0
 000
45554

  76
  -
  0
 000
45555

  75
  -
  0
 000
55555

  74
  -
  0
 000
55655

  73
  -
  0
 000
55665

  72
  -
  0
 000
56665

  71
  -
  0
 000
56666

  70
  -
  0
 000
66666

  69
  -
  0
 000
66766

  68
  -
  0
 000
66776

  67
  -
  0
 000
67776

  66
  -
  0
 000
67777

  65
  -
  0
 000
77777

  64
  -
  0
 000
77877

  63
  -
  0
 000
77887

  62
  -
  0
 000
78887

  61
  -
  0
 000
78888

  60
  -
  0
 000
88888

  59
  -
  0
 000
88988

  58
  -
  0
 000
88998

  57
  -
  0
 000
89998

  56
  -
  0
 000
89999

  55
  -
  0
 000
99999

  54
  -
  0
 010
99999

  53
  -
  0
 011
99999

  52
  -
  0
 111
99999

  51
  -
  0
 121
99999

  50
  -
  0
 122
99999

  49
  0
 222
99999

  48
  -
  0
 232
99999

  47
  -
  0
 233
99999

  46
  -
  0
 333
99999

  45
  -
  0
 343
99999

  44
  -
  0
 344
99999

  43
  -
  0
 444
99999

  42
  -
  0
 454
99999

  41
  -
  0
 455
99999

  40
  -
  0
 555
99999

  39
  -
  0
 565
99999

  38
  -
  0
 566
99999

  37
  -
  0
 666
99999

  36
  -
  0
 676
99999

  35
  -
  0
 677
99999

  34
  -
  0
 777
99999

  33
  -
  0
 787
99999

  32
  -
  0
 788
99999

  31
  -
  0
 888
99999

  30
  -
  0
 898
99999

  29
  -
  0
 899
99999

  28
  -
  0
 999
99999

  27
  -
  1
 999
99999

  26
  -
  2
 999
99999

  25
  -
  3
 999
99999

  24
  -
  4
 999
99999

  23
  -
  5
 999
99999

  22
  -
  6
 999
99999

  21
  -
  7
 999
99999

  20
  -
  8
 999
99999

  19
  -
  9
 999
99999

```

So as example:

```
inputs: 5,100,1
output:
  99
  -
  0
 000
00100

Same example with another valid output format:
  99
  ~
  .
 ...
..1..

```

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases:

```
INPUTS: bottom-edge length, amount of grains of sand, index (0-indexed)

inputs: 5,100,1
output:
  99
  -
  0
 000
00100

inputs: 5,100,24
output:
  76
  -
  0
 000
45555

inputs: 5,100,100
output:
  19
  -
  9
 999
99999

inputs: 5,10,15
output:
  0
  -
  0
 000
22222

inputs: 3,30,20
output:
 10
 -
 0
677

inputs: 3,3,0
 3
 -
 0
000

inputs: 9,250,100
   150
    -
    0
   000
  00000
 2333332
999999999

inputs: 9,225,220
    5
    -
    4
   999
  99999
 9999999
999999999

inputs: 13,1234567890,250
  1234567640
      -
      0
     000
    00000
   0000000
  344444443
 99999999999
9999999999999

inputs: 25,25,25
             0
             -
             0
            000
           00000
          0000000
         000000000
        00000000000
       0000000000000
      000000000000000
     00000000000000000
    0000000000000000000
   000000000000000000000
  00000000000000000000000
 1111111111111111111111111

```

# Answer
# 05AB1E, ~~68~~ ~~63~~ ~~59~~ ~~57~~ 56 bytes

```
IÅÉÅ9[DOO²Q#ćD_Piˆëć<¸«¸ì]ćā<ΣÉ}2äćR¸ì˜è¸ì¯ìJDSOIα'-‚ì.C

```

Try it online!

**Explanation**

`IÅÉÅ9`
We initialize the stack with a list of list of 9's.
Each list represents a row so the length of each list is odd and the length of the last list is equal to the first input.
An input of **5** would result in `[[9], [9, 9, 9], [9, 9, 9, 9, 9]]`

`[DOO²Q#ćD_Piˆëć<¸«¸ì]`
We then iterate over these lists decrementing elements in a list until the list consists only of zeroes, then moving on to the next. We stop when the total sum equals the second input.

```
[     #              ]   # loop until
 DOO                     # the sum of the list of lists
    ²Q                   # equals the second input
        ć                # extract the first list
         D_Pi            # if the product of the logical negation of all elements is true
             ˆ           # add the list to the global list
              ë          # else
               ć<        # extract the head and decrement it
                 ¸«      # append it to the list
                   ¸ì    # and prepend the list to the list of lists

```

Now we need to unsort the final list simulating removing elements from alternating sides instead of left-to-right as we have been doing.

```
ć                   # extract the row we need to sort
 ā<                 # push a list of indices of the elements [0 ... len(list)-1]
   ΣÉ}              # sort it by even-ness
      2äćR¸ì˜       # reverse the run of even numbers
                    # the resulting list will have 0 in the middle,
                      odd number increasing to the right and
                      even numbers increasing to the left
             è      # index into our final row with this
              ¸ì¯ì  # reattach all the rows to eachother

```

Now we format the output correctly

```
J              # join list of lists to list of strings
 DSOIα         # calculate the absolute difference of sum of our triangle and the 3rd input
      '-‚ì     # pair it with the string "-" and append to the list of rows
          .C   # join by newlines and center each row

```
> 3 votes

# Answer
# Clean, ~~305~~ 289 bytes

```
import StdEnv
@[h:t]|all((==)9)h|t>[]=[h: @t]=[h]
#s=length h/2
#m=hd(sort h)+1
=[updateAt(hd[e\\e<-flatten[[s+i,s-i]\\i<-[0..s]]|h!!e<m])m h:t]
$a b c=flatlines(map(cjustify(a+1))[fromString(fromInt(b-c)),['-']:reverse(map(map(toChar o(+)48))((iterate@[repeatn(a-r)0\\r<-[0,2..a]])!!c))])

```

Try it online!
> 5 votes

# Answer
# Perl 5, 301 bytes

```
($x,$t,$u)=<>;$s=$x;$t-=$g=$t>$u?$u:$t;while($s>0){@{$a[++$i]}=((0)x$s,($")x($x-$s));$a[$i][$_%$s]++for 0..($f=$g<$s*9?$g:$s*9)-1;$g-=$f;$s-=2}say$"x(($x-length($g+=$t))/2+.5),$g,$/,$"x($x/2),'-';while(@b=@{pop@a}){for($i=1;$i<@b;$i+=2){print$b[-$i]}print$b[0];for($i=1;$i<@b;$i+=2){print$b[$i]}say''}

```

Try it online!
> 1 votes

# Answer
# Charcoal, ~~68~~ ~~63~~ 62 bytes

```
ＮθＮηＮζＦ⊘⊕θＦ⁹Ｆ⁻θ⊗ι«Ｊ⊘⎇﹪λ²⊕λ±λ±ι≔¬¬ζλ↑Ｉ⁺λＩＫＫ≧⁻λη≧⁻λζ»↑-Ｍ⊘⊖ＬＩη←Ｉη

```

Try it online! Link is to verbose version of code. Edit: Saved 5 bytes by removing the now-unnecessary index range check. Explanation:

```
ＮθＮηＮζ

```

Input the length into `q`, the number of grains of sand into `h` and the index into `z`.

```
Ｆ⊘⊕θＦ⁹Ｆ⁻θ⊗ι«

```

Loop over the `(q+1)/2` rows (from bottom to top), then 9 grains in each cell in the row, then loop over the digits in the row.

```
Ｊ⊘⎇﹪λ²⊕λ±λ±ι

```

Jump to the digit.

```
≔¬¬ζλ↑Ｉ⁺λＩＫＫ≧⁻λη≧⁻λζ»

```

If possible, distribute a grain of sand to this digit, decrementing the amount of sand and index left. If we've passed the index, this still converts spaces to zeros, filling the hourglass. The digit is printed upwards because this means that the cursor will be on the neck after the last digit.

```
↑-

```

Print the neck.

```
Ｍ⊘⊖ＬＩη←Ｉη

```

Centre and print the amount of sand remaining.
> 1 votes

---
Tags: code-golf, ascii-art, number, integer
---


title: cool untitled sequence thingy

text:
# Question
Title: cool untitled sequence thingy
Let's define **fn(k)** as the sum of the first **k** terms of the natural numbers **\[1, ∞)** where each number is repeated **n** times.

```
**k**       | **0    1    2    3    4    5    6    7    8    9**
--------+-------------------------------------------------
**f_1(k)**  | 0    1    3    6    10   15   21   28   36   45
**deltas**  |   +1   +2   +3   +4   +5   +6   +7   +8   +9
--------+-------------------------------------------------
**f_2(k)**  | 0    1    2    4    6    9    12   16   20   25
**deltas**  |   +1   +1   +2   +2   +3   +3   +4   +4   +5
--------+-------------------------------------------------
**f_3(k)**  | 0    1    2    3    5    7    9    12   15   18
**deltas**  |   +1   +1   +1   +2   +2   +2   +3   +3   +3
```

The anti-diagonals of this as a square array is similar to OEIS sequence A134546.

## Challenge

Write a **program/function** that takes **two non-negative integers n and k** and outputs **fn(k)**.

### Specifications

* Standard I/O rules **apply**.
* Standard loopholes are **forbidden**.
* Your solution **can either be 0-indexed or 1-indexed for n and/or k** but please specify which.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.

### Test cases

In these test cases, **n** is 1-indexed and **k** is 0-indexed.

```
**n   k      f<sub>n</sub>(k)**

1   2      3
2   11     36
11  14     17
14  21     28
21  24     27
24  31     38
31  0      0
```

In a few better formats:

```
1 2
2 11
11 14
14 21
21 24
24 31
31 0

1, 2
2, 11
11, 14
14, 21
21, 24
24, 31
31, 0

```

### Reference implementation

This is written in Haskell.

```
f n k = sum $ take k $ replicate n =<< [1..]

```

Try it online!

This challenge was sandboxed.

# Answer
# Ruby, ~~32 28~~ 23 bytes

```
->n,k{k.step(0,-n).sum}

```

Try it online!

### Explanation

Let's visualize the sum as the area of a triangle, for example with n=3 and k=10:

```
*
*
*
**
**
**
***
***
***
****

```

Then we sum by column instead of row: the first column is `k`, then `k-n`, `k-2n` and so on.
> 13 votes

# Answer
## Husk, 4 bytes

```
Σ↑ṘN

```

Try it online!

### Explanation

This just ends up being a direct translation of the reference implementation in the challenge:

```
   N  Start from the infinite sequence of all natural numbers.
  Ṙ   Replicate each element n times.
 ↑    Take the first k values.
Σ     Sum them.

```
> 8 votes

# Answer
# Python 2, ~~34~~ 28 bytes

```
lambda n,k:(k+k%n)*(k/n+1)/2

```

Try it online!

Thanks Martin Ender, Neil and Mr Xcoder for helping.
> 8 votes

# Answer
# Mathematica, 40 bytes

```
Tr@Sort[Join@@Range@#2~Table~#][[;;#2]]&

```

Try it online!

```
Tr[Range@(s=⌊#2/#⌋)]#+#2~Mod~#(s+1)&

```

Try it online!

# Mathematica, 18 bytes

**by Martin Ender**

```
Tr@Range[#2,0,-#]&

```

Try it online!

```
n~Sum~{n,#2,0,-#}&

```

Try it online!
> 5 votes

# Answer
# APL (Dyalog), ~~12~~ ~~10~~ 8 bytes

```
+/∘⌈÷⍨∘⍳

```

Try it online!

`n` on the left, `k` (0 indexed) on the right.
> 5 votes

# Answer
# MATL, ~~12~~ 11 bytes

```
:iY"Ys0h1G)

```

Try it online!

`k` is 0-indexed. Takes input in reverse order.

Saved 1 byte thanks to @Giuseppe
> 5 votes

# Answer
# Jelly, 5 bytes

```
Rxḣ³S

```

One more byte than @Mr.Xcoder's Jelly solution but this is my first ever submission in Jelly and I'm still confused about how the tacitness of Jelly chooses operands so I'm still satisfied. Note the order of the inputs are `k` then `n`.

**Explanation**

```
Rxḣ³S
R           Range: [1,2,...,k]
 x          Times: repeat each element n times: [1,1,1,2,2,2,...,n,n,n]
  ḣ³        Head: take the first k elements. ³ returns the first argument.
    S       Sum

```

Try it online!
> 5 votes

# Answer
# Jelly, 4 bytes

**1-indexed**

```
Ḷ:‘S

```

Try it online! or see a test suite.
> 4 votes

# Answer
# JavaScript (ES6),  ~~24~~  21 bytes

Takes input in currying syntax `(n)(k)`. Returns `false` instead of `0`.

```
n=>g=k=>k>0&&k+g(k-n)

```

### Test cases

```
let f =

n=>g=k=>k>0&&k+g(k-n)

console.log(f(1 )(2 )) // 3
console.log(f(2 )(11)) // 36
console.log(f(11)(14)) // 17
console.log(f(14)(21)) // 28
console.log(f(21)(24)) // 27
console.log(f(24)(31)) // 38
```

### How?

```
n =>             // main unamed function taking n
  g = k =>       // g = recursive function taking k
    k > 0 &&     // if k is strictly positive:
      k +        //   add k to the final result
      g(k - n)   //   subtract n from k and do a recursive call

```

This is similar to @GB's Ruby answer.

The challenge describes how to build the 'staircase' from left to right, whereas this recursive function builds it from bottom to top. With **n = 2** and **k = 11**:
> 4 votes

# Answer
# C, ~~38~~ 34 bytes

Recursive definition.

*-4 bytes thanks to Steadybox.*

```
f(n,k){return k--?1+f(n,k)+k/n:0;}

```

Try it online!

---

**32 bytes by Mr. Xcoder, G B**

```
f(n,k){return(k+k%n)*(k/n+1)/2;}

```

Try it online!
> 3 votes

# Answer
## Batch, 34 bytes

```
@cmd/cset/a(%2+%2%%%1)*(%2/%1+1)/2

```

A closed-form formula that I found. First argument `n` is 1-indexed, second argument `k` is 0-indexed.
> 3 votes

# Answer
# Python 2, 29 bytes

```
lambda n,k:sum(range(k,0,-n))

```

Try it online!

Thanks to totallyhuman for -3 bytes!

---

### Python 2, 30 bytes

```
f=lambda n,k:k>0and k+f(n,k-n)

```

Try it online!
> 3 votes

# Answer
# Haskell, 28 bytes

```
n#k|m<-k`mod`n=sum[m,m+n..k]

```

Try it online!

An approach I found just by screwing around with some range parameters. Most definitely not the shortest but it's pretty cool how there's so many different approaches.
> 3 votes

# Answer
# , ~~37~~ ~~33~~ 31 bytes

-6 bytes thanks to Giuseppe

```
function(n,k)sum(rep(1:k,,k,n))

```

Try it online!

Nothing fancy. ~~The `[0:k]` handles the case when k=0.~~
> 3 votes

# Answer
# C++, 53 bytes

Just use the formula. `n` is 1-indexed and `k` is 0-indexed.

```
[](int n,int k){return k/n*(k/n+1)/2*n+k%n*(k/n+1);};

```

Try it online!
> 2 votes

# Answer
# , 13 bytes

```
1#.]{.(#1+i.)

```

How it works:

The left argument is n, the right is k.

`i.` generates a list 0..k-1

`1+` adds one to each number of the list, yealding 1,2,...,k

`#` forms a hook with the above, so n copies of each elements of the list are copied.

`]{.` take the first n of them

`1#.` find their sum by base conversion.

Try it online!
> 2 votes

# Answer
# Retina, ~~29~~ 26 bytes

```
\d+
$*
(?=.*?(1+)$)\1
$'
1

```

Try it online! Link includes test cases and header to reformat them to its preferred input (0-indexed `k` first, 1-indexed `n` second). I was inspired by @GB's Ruby answer. Explanation:

```
\d+
$*

```

Convert to unary.

```
(?=.*?(1+)$)\1
$'

```

Match every string of `n` within `k`, and replace the match with everything after the match. This is `k-n`, `k-2n`, `k-3n`, but `n` is also after the match, so you get `k`, `k-n`, `k-2n` etc. This also matches `n`, which is simply deleted (it's no longer needed).

```
1

```

Sum the results and convert back to decimal.
> 2 votes

# Answer
# Pyth, 5 bytes

```
s%_ES

```

**Try it here!**

Port of G B's Ruby answer. A port of my Jelly one would be 6 bytes: `+s/Rvz`
> 2 votes

# Answer
# Perl 6, 39 bytes

```
->\n,\k{(0,{|($_+1 xx n)}...*)[^k].sum}

```

Test it

***n*** and ***k*** are both 1 based

## Expanded:

```
-> \n, \k { # pointy block lambda with two parameters ｢n｣ and ｢k｣

  ( # generate the sequence

    0,         # seed the sequence (this is why ｢k｣ is 1-based)

    {          # bare block lambda with implicit parameter ｢$_｣
      |(       # slip this into outer sequence
        $_ + 1 # the next number
        xx n   # repeated ｢n｣ times (this is why ｢n｣ is 1-based)
      )
    }

    ...        # keep doing that until

    *          # never stop

  )[ ^k ]      # get the first ｢k｣ values from the sequence
  .sum         # sum them
}

```
> 2 votes

# Answer
# Kotlin, 40 bytes

```
{n:Int,k:Int->Array(k,{i->i/n+1}).sum()}

```

Try it online!
> 2 votes

# Answer
# Java (OpenJDK 8), 23 bytes

```
n->k->(k+k%n)*(k/n+1)/2

```

Try it online!

Port of G B's Python 2 answer.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
FL`}){I£O

```

Try it online!

**Explanation**

```
F           # n times do
 L`         # pop top of stack (initially k), push 1 ... topOfStack
   }        # end loop
    )       # wrap stack in a list
     {      # sort the list
      I£    # take the first k elements
        O   # sum

```
> 1 votes

# Answer
# Python 2, 44 bytes

```
f=lambda n,k:sum(sorted(range(1,k+1)*n)[:k])

```

Try it online!
> 1 votes

# Answer
# Python 2, 38 bytes

```
lambda n,k:sum(i/n+1for i in range(k))

```

Try it online!
> 1 votes

# Answer
## Clojure, 54 bytes

```
#(nth(reductions +(for[i(rest(range))j(range %)]i))%2)

```

2nd argument `k` is 0-indexed, so `(f 14 20)` is 28.
> 1 votes

# Answer
# APL+WIN, 13 bytes

```
+/⎕↑(⍳n)/⍳n←⎕

```

Prompts for screen input for n and then for k. Index origin = 1.
> 1 votes

# Answer
# Japt, ~~7~~ 6 bytes

Originally inspired by GB's solution and evolved to a port!

Takes `k` as the first input and `n` as the second.

```
õ1Vn)x

```

Try it

---

## Explanation

Implicit input of integers `U=k` & `V=n`. Generate an array of integers (`õ`) from `1` to `U` with a step of `V` negated (`n`) and reduce it by addition (`x`).
> 1 votes

# Answer
# Brain-Flak, 78 bytes

```
(({}<>)<{<>(({})<>){({}[()]<(({}))>)}{}({}[()])}{}<>{}>)({<({}[()])><>{}<>}{})

```

Try it online!

I'm certain this can be done better, but it's a start.
> 1 votes

# Answer
# , 27 bytes

Anonymous function that takes `k` and `n` in that order. Creates a list of length `k` (third argument to `rep`) that is composed of `1` through `k` (first argument to `rep`), repeating each element `n` times (fourth argument to `rep`). Then takes the sum of that list.

`n` is 1-indexed and `k` is 0-indexed. Returns an error for `n<1`.

```
pryr::f(sum(rep(1:k,,k,n)))

```

Try it online!
> 1 votes

# Answer
# Befunge, 27 Bytes

```
&::00p&:10p%+00g10g/1+*2/.@

```

Try It Online

Takes k then n as input. Uses G B's answer as its mathematical basis.
> 1 votes

# Answer
# Jelly, 4 bytes

```
R÷ĊS

```

Try it online!

Takes input in order `k`, `n`. Creates an array of ints from 1 to `k`, divides each by `n` and then rounds up, and sums.
> 0 votes

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


title: Back to the Basics of Math

text:
# Question
Title: Back to the Basics of Math
## Introduction:

We all know these three basic arithmetic math tables I assume.

```
ADDITION:
 + | 1  2  3  4  5  6  7  8  9  10
----------------------------------
1  | 2  3  4  5  6  7  8  9  10 11
2  | 3  4  5  6  7  8  9  10 11 12
3  | 4  5  6  7  8  9  10 11 12 13
4  | 5  6  7  8  9  10 11 12 13 14
5  | 6  7  8  9  10 11 12 13 14 15
6  | 7  8  9  10 11 12 13 14 15 16
7  | 8  9  10 11 12 13 14 15 16 17
8  | 9  10 11 12 13 14 15 16 17 18
9  | 10 11 12 13 14 15 16 17 18 19
10 | 11 12 13 14 15 16 17 18 19 20

SUBTRACTION:
 - | 1  2  3  4  5  6  7  8  9  10
---------------------------------
1  | 0  1  2  3  4  5  6  7  8  9
2  | -1 0  1  2  3  4  5  6  7  8
3  | -2 -1 0  1  2  3  4  5  6  7
4  | -3 -2 -1 0  1  2  3  4  5  6
5  | -4 -3 -2 -1 0  1  2  3  4  5
6  | -5 -4 -3 -2 -1 0  1  2  3  4
7  | -6 -5 -4 -3 -2 -1 0  1  2  3
8  | -7 -6 -5 -4 -3 -2 -1 0  1  2
9  | -8 -7 -6 -5 -4 -3 -2 -1 0  1
10 | -9 -8 -7 -6 -5 -4 -3 -2 -1 0

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

For the sake of this challenge, division is excluded.

```

## Sequence definition:

We will follow the same steps for both a 0-indexed and 1-indexed sequence. So the resulting sequence will become `f(0)+g(1)`, `f(1)+g(2)`, etc.

* Both `f` (0-indexed) and `g` (1-indexed) start in the ADDITION table at `(1,1)`. So `f(0) = 1+1 = 2` and `g(1) = 1+1 = 2`.
* We then go to the SUBTRACTION table, and we either go `n` steps down if `n` is odd, or `n` steps to the right if `n` is even. So `f(1) = 1-2 = -1` (it went to the down, because `n=1` is odd); and `g(2) = 3-1 = 2` (it went right, because `n=2` is even).
* Then we go to the MULTIPLICATION table, and do the same: `f(2) = 3*2 = 6` and `g(3) = 3*4 = 12`.
* And then we go back to the ADDITION table again. Also, when we go beyond the borders of the 10x10 table, we wrap around from the bottom to the top, or from the right to the left. So going from `(7,9)` six steps right, will end up at `(3,9)`.

The resulting sequence will be `f(n)+g(n+1)` (with `n` being 0-indexed).

Here the first six in colors, in the order green → blue → purple → grey → red → orange:

`f` (0-indexed): `(1+1) → (1-2) → (3*2) → (3+5) → (7-5) → (7*10)`

`g` (1-indexed): `(1+1) → (3-1) → (3*4) → (7+4) → (7-9) → (3*9)`

The resulting sequence is the sum of both these sequences.

Here are the first 100 items of the 0-indexed sequence `f`:

```
2,-1,6,8,2,70,13,-4,7,7,-5,7,10,-7,70,12,-2,6,3,0,1,3,1,15,12,-3,30,10,-6,6,7,-6,21,13,-3,35,8,1,2,2,0,2,5,-2,35,17,-7,21,8,-5,6,8,-4,30,17,2,15,5,-1,1,2,-1,6,8,2,70,13,-4,7,7,-5,7,10,-7,70,12,-2,6,3,0,1,3,1,15,12,-3,30,10,-6,6,7,-6,21,13,-3,35,8,1,2,2

```

Here are the first 100 items of the 1-indexed sequence `g`:

```
2,2,12,11,-2,27,9,-5,5,6,-5,18,12,-2,28,7,2,1,11,-9,1,4,-1,28,16,-6,18,7,-4,5,7,-3,27,16,3,12,4,0,10,11,0,3,7,3,63,12,-3,6,6,-4,6,9,-6,63,11,-1,3,2,-9,10,2,2,12,11,-2,27,9,-5,5,6,-5,18,12,-2,28,7,2,1,11,-9,1,4,-1,28,16,-6,18,7,-4,5,7,-3,27,16,3,12,4,0,10,11

```

Here are the first 100 items of the result sequence:

```
4,1,18,19,0,97,22,-9,12,13,-10,25,22,-9,98,19,0,7,14,-9,2,7,0,43,28,-9,48,17,-10,11,14,-9,48,29,0,47,12,1,12,13,0,5,12,1,98,29,-10,27,14,-9,12,17,-10,93,28,1,18,7,-10,11,4,1,18,19,0,97,22,-9,12,13,-10,25,22,-9,98,19,0,7,14,-9,2,7,0,43,28,-9,48,17,-10,11,14,-9,48,29,0,47,12,1,12,13

```

## Challenge:

Given an integer `n`, output the `n`'th number of the above result sequence (which sums both the 0-indexed and 1-indexed sequences). So calculate `h(n) = f(n)+g(n+1)`.

## Challenge rules:

* The result-sequence is always 0-indexed. I know some languages are 1-indexed by default, in which case you'll have to do `n-1` right after entering the function/program so `f(n)+g(n+1)` will start at `f(0)+g(1)` (and not `f(1)+g(2)`).
* Output can be in any reasonable format, so a String or decimal with `.0` instead of an integer is allowed.
* As you may or may not have noted; in the tables above the number at the top is taken first, then the number at the left.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases (0-indexed):

```
0       4
1       1
2       18
3       19
4       0
5       97
10      -10
50      12
60      4
61      1
62      18
63      19
100     0
111     17
1000    0
1994    98
2497    1
2498    12
2499    13
2500    0

```

***Note/tip:*** *The sequences are self-repeating every 60 items.*

# Answer
> 5 votes
# 05AB1E, ~~48~~ ~~47~~ ~~43~~ 42 bytes

1-indexed.

```
¾4×SsFD2äεT%>`…+-*Nè.V}Os0NÌ‚ÂTS-‚Nƒí}˜+}\

```

Try it online! or see the Whole sequence

**Explanation**

```
¾4×S                                         # initialize stack with [0,0,0,0]
    sF                                  }    # for N in range [0 ... input-1] do:
      D                                      # duplicate
       2äε            }                      # for each pair of values
          T%>                                # get last digit of each and increment
              …+-*Nè                         # index into "+-*" with N
             `      .V                       # apply the function to our values
                       O                     # sum the pair
                        s                    # swap the list of 4 values to the top
                         0NÌ‚                # push [0, N+2]
                             ÂTS-            # bifurcate and subtract [1,0]
                                 ‚           # pair, resulting in [[0,N+2],[N+1,0]]
                                  Nƒí}       # reverse each pair N+1 times
                                      ˜+     # flatten and add to the list of values
                                               from last iteration
                                         \   # discard the final list

```

# Answer
> 6 votes
# APL (Dyalog), 77 bytes

Full program which prompts for `n`, looks up the result in the list of 60 possible results, and prints that to STDOUT.

```
¯50+⎕AV⍳'63DE2èHy£¢xKHyéE29∆y492ýNyÂCx$∆yÂO2Á£3£¢27£3éOxM∆y£CxäN3D9x$'[60|⎕]

```

Try it online!

`'``'[``]` index the string by the following:

prompt for `n`

`60|` remainder when dividing by 60

`⎕AV⍳` find **ɩ**ndices in the **A**tomic **V**ector (the character set)

`¯50+` add negative fifty

# Answer
> 5 votes
# Python 3, 89 bytes

```
lambda i:ord('HEVWD¥Z;PQ:]Z;¦WDKR;FKDo`;tU:OR;taDsPEPQDIPE¦a:_R;PU:¡`EVK:O'[i%60])-68

```

Try it online!

# Answer
> 5 votes
# JavaScript (ES6), ~~95~~ ... ~~84~~ 82 bytes

This is the best I could come up with so far without hardcoding the sequence.

*Edit: Now probably shorter than hardcoding anyway.*

```
m=>(g=(x,y=n=1)=>n>m?[x*y,x+y,n+o--&1?y-x:x-y][n%3]:g((y-o+n++)%10+1,x))(o=1)+g(1)

```

### Demo

```
let f =

m=>(g=(x,y=n=1)=>n>m?[x*y,x+y,n+o--&1?y-x:x-y][n%3]:g((y-o+n++)%10+1,x))(o=1)+g(1)

;[0, 1, 2, 3, 4, 5, 10, 50, 60, 61, 62, 63, 100, 111, 1000]
.forEach(i => {
  console.log(`a(${i}) = ${f(i)}`)
});
```

### Formatted and commented

```
m => (                              // m = input
  g = (                             // g = recursive function using:
    x, y = n = 1                    //   (x,y) = coordinates, n = counter
  ) =>                              //   and o = offset (0 or 1)
    n > m ?                         // if n is greater than the input:
      [                             //   evaluate the current cell in the current table
        x * y,                      //   both multiplication
        x + y,                      //   and addition are commutative
        n + o-- & 1 ? y - x : x - y //   but subtraction is not: we need to make sure that
      ][n % 3]                      //   x and y are set in the correct order
    :                               // else:
      g(                            //   do a recursive call to g():
        (y - o + n++) % 10 + 1,     //     updating y and using it as x; incrementing n
        x                           //     using x as y
      )                             //   end of recursive call
  )(o = 1) + g(1)                   // invoke g() with o = 1; then o = 0; return the sum

```

# Answer
> 3 votes
# Excel, 188 bytes

Hardcoded results:

```
=CHOOSE(MOD(A1,60)+1,5,2,19,20,1,98,23,-8,13,14,-9,26,23,-8,99,20,1,8,15,-8,3,8,1,44,29,-8,49,18,-9,12,15,-8,49,30,1,48,13,2,13,14,1,6,13,2,99,30,-9,28,15,-8,13,18,-9,94,29,2,19,8,-9,12)-1
```

Saved 3 bytes by adding 1 to all results in lookup, then subtracting at end. This turns `-10` into `-9` 5 times.

# Answer
> 2 votes
# PowerShell, 81 bytes (UTF-8)

```
'HEVWD¥Z;PQ:]Z;¦WDKR;FKDo`;tU:OR;taDsPEPQDIPE¦a:_R;PU:¡`EVK:O'["$args"%60]-68

```

Try it online!

Port of ovs' answer to PowerShell. Since after reading the challenge, I was going to do something similar, it's easier to just re-use the string.

# Answer
> 2 votes
# Haskell, ~~159~~ 155 bytes

**EDIT**: thanks to Laikoni for taking off 4 bytes!

```
((z(+)(a 1)$a 0)!!)
p#n=mod(p+n-1)10+1
b i=(1,1):[(p#(n*0^e),q#(n*e))|n<-[1+i..],let(p,q)=b i!!(n-1-i);e=mod n 2]
a=z uncurry o.b
o=(+):(-):(*):o
z=zipWith

```

Usage:

```
(zipWith(+)(a 1)$a 0)!!5

```

Try it online!

Explanation:

The # operator is for incrementing a coordinate by some value n and wrapping it. Notice the -1 and +1 to get it onto the range \[0..9\] so mod will work right.

The `b` function builds an infinite list of coordinates given an offset value of 0 or 1 to simulate the difference between 0 indexing and 1 indexing. `b` works by recursively iterating on the coordinates, starting with a hardcoded value of (1,1). When updating a coordinate we need to make sure we don't change it if n doesn't have the right parity so I multiply n by some value that will be 0 or 1 depending on its parity. `e` will be 0 when `n` is even and 1 otherwise and the `0^` trick can invert that for the other case.

The `a` function also takes an offset, passes it to `b` and zips the result with an infinite list cycling between the addition, subtraction and multiplication operators. The zip is performed with the `uncurry` function which breaks up the coordinate pair and applies them to the operator.

Finally we build the resulting sequence by simply zipping the lists (generated with different offsets) with the addition operator. Then we use the `(!!)` operator to turn it into a lookup function.

# Answer
> 1 votes
# Python 2, 85 bytes

```
lambda j:ord('!/0~3)*630$+$H9M.(+M:L))*"):8+).z9/$('[j%60])-29

```

Try it online!

Based off of ovs' Python 3 answer; implemented in Python 2 without using non-ASCII characters.

# Answer
> 0 votes
# Java 8, ~~191~~ 85 bytes

```
n->"HEVWD¥Z;PQ:]Z;¦WDKR;FKDo`;tU:OR;taDsPEPQDIPE¦a:_R;PU:¡`EVK:O".charAt(n%60)-68

```

-106 bytes by porting *@ovs*' Python 3 answer.

I lost my initial solution that I've used to create the test cases.. :( But the hard-coded result is way shorter anyway.
I didn't knew the sequence was repeating every 60 items until after I posted the challenge. ;)

Try it online.

---
Tags: code-golf, number, sequence, arithmetic, integer
---


title: Find Integral Roots of A Polynomial

text:
# Question
Title: Find Integral Roots of A Polynomial
**Challenge**

The challenge is to write a program that takes the coefficients of any n-degree polynomial equation as input and returns the **integral** values of x for which the equation holds true. The coefficients will be provided as input in the order of decreasing or increasing power. You can assume all the coefficients to be **integers**.

**Input And Output**

The input will be the coefficients of the equation in decreasing or increasing order of power. The degree of the equation, i.e, maximum power of x, is always 1 less than the total no of elements in the input.

For example:

```
[1,2,3,4,5] -> represents x^4 + 2x^3 + 3x^2 + 4x + 5 = 0 (degree = 4, as there are 5 elements)
[4,0,0,3] -> represents 4x^3 + 3 = 0 (degree = 3, as there are 3+1 = 4 elements)

```

Your output should be only the **distinct integral values** of x which satisfy the given equation. All the input coefficients are integers and the input polynomial **will not be a zero polynomial**. If there is no solution for the given equation, then the output is undefined.

If an equation has repeated roots, display that particular root only once. You can output the values in any order. Also, assume that the input will contain at-least 2 numbers.

**Examples**

```
[1,5,6] -> (-3,-2)
[10,-42,8] -> (4)
[1,-2,0] -> (0,2)
[1, 1, -39, -121, -10, 168] -> (-4, -3, -2, 1, 7)
[1, 0, -13, 0, 36] -> (-3, -2, 2, 3)
[1,-5] -> (5)
[1,2,3] -> -

```

Note that the equation in the second example also has the root 0.2, but it is not displayed as 0.2 is not an integer.

**Scoring**

This is , so the shortest code (in bytes) wins!

# Answer
> 6 votes
# MATL, ~~13~~ 12 bytes

```
|stE:-GyZQ~)

```

Try it online!

This uses the fact that, for integer coefficients, the absolute value of any root is strictly less than the sum of absolute values of the coefficients.

### Explanation

Consider input `[1 5 6]` as an example.

```
|    % Implicit input. Absolute value
     % STACK: [1 5 6]
s    % Sum
     % STACK: 12
t    % Duplicate
     % STACK: 12, 12
E    % Multiply by 2
     % STACK: 12, 24
:    % Range
     % STACK: 12, [1 2 ... 23 24]
-    % Subtract, elemet-wise
     % STACK: [11 10 ... -11 -12]
G    % Push input again
     % STACK: [11 10 ... -11 -12], [1 5 6]
y    % Duplicate from below
     % STACK: [11 10 ... -11 -12], [1 5 6], [11 10 ... -11 -12]
ZQ   % Polyval: values of polynomial at specified inputs
     % STACK: [11 10 ... -11 -12], [182 156 ... 72 90]
~    % Logical negation: turns nonzero into zero
     % STACK: [11 10 ... -11 -12], [0 0 ... 0] (contains 1 for roots)
)    % Index: uses second input as a mask for the first. Implicit display
     % STACK: [-3 -2]

```

# Answer
> 5 votes
# Haskell, 54 bytes

```
f l|t<-sum$abs<$>l=[i|i<-[-t..t],foldl1((+).(i*))l==0]

```

Try it online!

Brute force and synthetic division.

## Ungolfed with UniHaskell and `-XUnicodeSyntax`

```
import UniHaskell

roots    ∷ Num a ⇒ [a] → [a]
roots xs = [r | r ← -bound … bound, foldl1 ((+) ∘ (r ×)) xs ≡ 0]
             where bound = sum $ abs § xs

```

## Alternate solution, 44 bytes

*Credit to nimi.*

```
f l=[i|i<-[minBound..],foldl1((+).(i*))l==0]

```

Good luck with trying it online, as this checks *every* number in an `Int`'s range.

# Answer
> 5 votes
# Husk, ~~10~~ 9 bytes

-1 byte thanks to Zgarb

```
uSȯf¬`Bṁṡ

```

Try it online!

### Explanation

```
       ṁṡ   Concatenate together the symmetric ranges of each coefficient
            (It is guaranteed that the integer roots lie in the range [-n..n],
                        where n is the coefficient with the largest magnitude)
 Sȯf        Find all the values in that range which
    ¬       are zero
     `B     when plugged through the polynomial
            (Base conversion acts as polynomial evaluation)
u           De-duplicate the roots

```

# Answer
> 4 votes
# Python 2 \+ numpy, ~~95~~ ~~93~~ ~~91~~ ~~103~~ ~~93~~ ~~91~~ 82 bytes

-2 bytes thanks to ovs
thanks Luis Mendo for the upper/lower bounds of the roots
-10 bytes thanks to Mr. Xcoder

```
from numpy import*
def f(r):s=sum(fabs(r));q=arange(-s,s);print q[polyval(r,q)==0]

```

Try it online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~50~~ ~~47~~ ~~42~~ ~~25~~ 27 bytes

```
{}⋃Select[x/.Solve[#~FromDigits~x==0],IntegerQ]&

```

Try it online!

Update: using Luis Mendo's fact, golfed off another 3 bytes

```
Pick[r=Range[s=-Tr@Abs@#,-s],#~FromDigits~r,0]&

```

Getting sloppier with the bounds, we can reduce this 5 more bytes per @Not a tree's suggestion:

```
Pick[r=Range[s=-#.#,-s],#~FromDigits~r,0]&

```

After posting this, OP commented allowing "native polynomials", so here's a 25 byte solution that accepts the polynomial as input. This works because by default Mathematica factors polynomials over the integers, and any rational roots show up in a form like `m*x+b` that fails the pattern match.

```
Cases[Factor@#,b_+x:>-b]&

```

As @alephalpha pointed out this will fail for the case where zero is a root, so to fix that we can use the `Optional` symbol `:`

```
Cases[Factor@#,b_:0+x:>-b]&

```

This parses fine Mathematica 11.0.1 but fails and requires an extra set of parentheses around `b_:0` in version 11.2. This takes up back up to 27 bytes, plus two more after version 11.0.1. It looks like a "fix" was put in here

Try it Online!

# Answer
> 3 votes
# , ~~61~~ 59 bytes

A special thanks to @mathmandan for pointing out my (incorrect) approach could be saved, and golfed!

```
function(p)(x=-(t=p[!!p][1]):t)[!outer(x,seq(p)-1,"^")%*%p]

```

Try it online!

Takes input as a list of coefficients in *increasing* order, i.e., `c(-1,0,1)` represents `-1+0x+1x^2`.

Using the rational root theorem, the following approach very nearly works, for 47 bytes:

```
function(p)(x=-p:p)[!outer(x,seq(p)-1,"^")%*%p]

```

Try it online!

`-p:p` generates a symmetric range (with a warning) using only the first element of `p`, `a_0`. By the Rational Root Theorem, all rational roots of `P` must be of the form `p/q` where `p` divides `a_0` and `q` divides `a_n` (plus or minus). Hence, using just `a_0` is sufficient for `|a_0|>0`, as for any `q`, `|p/q|<=a_0`. However, when `a_0==0`, as then *any* integer divides `0`, and thus this fails.

However, mathmandan points out that really, in this case, this means that there's a constant factor of `x^k` that can be factored out, and, assuming `k` is maximal, we see that

```
P(x) = x^k(a_k + a_{k+1}x + ... a_n x^{n-k}) = x^k * Q(x)

```

We then apply the Rational Root Theorem to `Q(x)`, and as `a_k` is guaranteed to be nonzero by the maximality of `k`, `a_k` provides a tidy bound for the integer roots of `Q`, and the roots of `P` are the roots of `Q` along with zero, so we will have all the integer roots of `P` by applying this method.

This is equivalent to finding the first nonzero coefficient of the polynomial, `t=p[!!p][1]` and using it instead of the naive `p[1]` as the bounds. Moreover, since the range `-t:t` always contains zero, applying `P` to this range would still give us zero as a root, if indeed it is.

### ungolfed:

```
function(polynom) {
 bound <- polynom[polynom != 0][1]             #first nonzero value of polynom
 range <- -bound:bound                         #generates [-bound, ..., bound]
 powers <- outer(range,seq_along(p) - 1, "^")  #matrix where each row is [n^0,n^1,n^2,...,n^deg(p)]
 polyVals <- powers %*% polynom                #value of the polynomial @ each point in range
 return(range[polyVals == 0])                  #filter for zeros and return
}
```

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~33~~ ~~26~~ 31 bytes

Fixed an error noted by Kelly Lowder in the comments.

```
x/.{}⋃Solve[#==0,x,Integers]&

```

Try it online!

**Previous incorrect solutions:**

I just noticed that for no integer solution, the output is undefined instead of empty list; that allows to remove a few bytes.

```
x/.Solve[#==0,x,Integers]&

```

Try it online!

Now if no integer solution exists, the function returns `x`.

**Previously:**

```
x/.Solve[#==0,x,Integers]/.x->{}&

```

Try it online!

# Answer
> 2 votes
# Jelly, 8 bytes

```
ASŒRḅ@Ðḟ

```

**Try it online! or as a test-suite!**

## How?

```
ASŒRḅ@Ðḟ || Full program (monadic link).

AS        || Sum the absolute values.
  ŒR      || And create the symmetric inclusive range from its negative value.
       Ðḟ || And discard those that yield a truthy value...
     ḅ@   || When plugging them into the polynomial (uses base convertion).

```

Based off Luis' answer. An alternative.

# Answer
> 2 votes
# C (gcc), ~~127~~ ~~126~~ 123 bytes

```
x,X,j,m,p;f(A,l)int*A;{for(m=j=0;j<l;m+=abs(A[j++]));for(x=~m;X=x++<m;p||printf("%d,",x))for(p=j=0;j<l;X*=x)p+=A[l-++j]*X;}

```

Try it online!

---

# Explanation

# C (gcc), 517 bytes

```
x,X,j,m,p;                      // global integer variables
f(A,l)int*A;{                   // define function, takes in integer array pointer and length
 for(m=j=0;j<l;m+=abs(A[j++])); // loop through array, sum up absolute values
  for(x=~m;X=x++<m;             // loop through all values x in [-m, m], prime X
   p||printf("%d,",x))          // at loop's end, print x value if polynomial value is zero
    for(p=j=0;j<l;X*=x)         // loop through coefficients
     p+=A[l-++j]*X;}            // build polynomial

```

Try it online!

# Answer
> 2 votes
# Octave, ~~59~~ 49 bytes

```
@(p)(x=-(t=p(~~p)(end)):sign(t):t)(!polyval(p,x))

```

Try it online!

This is a port of my R answer. The only difference is that I have to explicitly use `sign(t)` and `end` to generate the range, and that it has `polyval` to compute the polynomial.

Takes input as a row vector of coefficients in decreasing order.

# Answer
> 2 votes
# Pari/GP, 31 bytes

```
p->[x-a|a<-factor(p)[,1],a'==1]

```

Factors the polynomial, and picks out the factors whose derivatives are 1.

Try it online!

# Answer
> 1 votes
# Java 8, ~~141~~ 140 bytes

```
a->{int l=a.length,s=0,i,r,f,p;for(int n:a)s+=n<0?-n:n;for(r=~s;r++<s;System.out.print(p==0?r+",":""))for(p=i=0,f=1;i<l;f*=r)p+=a[l-++i]*f;}

```

Inspired by *@Rod*'s Python 2 answer (his 82 bytes version).

Fun challenge! I certainly learned a lot of it when investigating about polynomials and seeing how some others here have done it.

**Explanation:**

Try it online.

```
a->{                   // Method with integer-array parameter and no return-type
  int l=a.length,      //  The length of the input-array
      s=0,             //  Sum-integer, starting at 0
      i,               //  Index integer
      r,               //  Range-integer
      f,               //  Factor-integer
      p;               //  Polynomial-integer
  for(int n:a)         //  Loop over the input-array
    s+=n<0?-n:n;       //   And sum their absolute values
  for(r=~s;r++<s;      //  Loop `r` from `-s` up to `s` (inclusive) (where `s` is the sum)
      System.out.print(p==0?r+",":""))
                       //    After every iteration: print the current `r` if `p` is 0
    for(p=i=0,         //   Reset `p` to 0
        f=1;           //   and `f` to 1
        i<l;           //   Loop over the input-array again, this time with index (`i`)
        f*=r)          //     After every iteration: multiply `f` with the current `r`
      p+=              //    Sum the Polynomial-integer `p` with:
         a[l-++i]      //     The value of the input at index `l-i-1`,
                 *f;}  //     multiplied with the current factor `f`

```

# Answer
> 0 votes
# Octave with Symbolic Package, 63 bytes

```
@(p)(s=double(solve(poly2sym(p)==0)))(s==(t=real(s))&~mod(t,1))

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
ÄOD(Ÿʒβ>

```

Try it online!

# Answer
> 0 votes
## JavaScript (ES6), 97 bytes

```
a=>[...Array((n=Math.max(...a.map(Math.abs)))-~n)].map(_=>n--).filter(i=>!a.reduce((x,y)=>x*i+y))

```

Takes coefficients in decreasing order of power and outputs results in descending order.

# Answer
> 0 votes
# Clean, ~~110~~ 91 bytes

```
import StdEnv
?p#s=sum p
=[i\\i<-[~s..s]|i<>0&&sum[e*i^t\\t<-reverse(indexList p)&e<-p]==0]

```

Try it online!

# Answer
> 0 votes
# Python 2, 89 bytes

```
def f(a):s=sum(map(abs,a));return[n for n in range(-s,s)if reduce(lambda v,c:v*n+c,a)==0]

```

Try it online!

---
Tags: code-golf, number, integer, polynomials, equation
---


# Question
Title:
# Introduction

Try to convert words to two different unicode fonts.

# Challenge

Your task is to transform your input string into the and unicode characters.

All uppercase words should become lowercase words.

* For Example: `WORD` -\>

All lowercase words should become words

* For example: `other words` -\>

All mixed case words should remain unchanged

* For example: `Mixed Case Words` -\> `Mixed Case Words`

Periods and spaces should remain unchanged.

Words are separated by spaces or periods

* For example (highlighted things are words):

> `Hello`. `This` `is` `a` `word`. `S`.`O`. `are` `these`

* Inputs: A string containing letters, spaces, and periods (`[A-Za-z .]+`)
* Output: The formatted string

As this is a golfing challenge, the lowest number of bytes wins

# Example Input and Output

Input:

> This is an example STRING that c.o.U.L.d. be INPUTTED. It can CONTAIN multiple sentences.

Output:

> This ..... . It .

# Reference

Math Sans Bold: (characters 120302 through 120327)

Math Sans: (characters 120250 through 120275)

# Answer
# QuadR, ~~45~~ 43 bytes

-2 thanks to ngn.

```
\w+
⎕UCS a+(2>≢b)×120153+84×⊃b←∪96>a←⎕UCS⍵M

```

Since TIO scrambles Unicode output from QuadR, here is a screenshot of using QuadR as an APL library in an interactive session:

---

`\w+` replace words with the result of applying the following code to them:

`⍵M` the found word
`⎕UCS` the **U**niversal **C**haracter **S**et code points of that
`a←` store that in `a`
`96>` 0 or 1 for whether 96 is greater than each of those
take just the unique; `[0]` or `[1]` or `[0,1]` or `[1,0]`
`b←` store that in `b`
pick the first from that
`84×` multiply 84 with that
`120153+` add 120153 to that
`(` multiply the following with that:
`≢b` the tally (length) of `b` (`1` if single-case, `2` if mixed-case)
`2>` 0 or 1 for whether two is greater than that (`1` if single-case, `0` if mixed-case)
`a+` the original code points added to that
`⎕UCS` convert the resulting code points back to characters
> 10 votes

# Answer
# APL (Dyalog Unicode), ~~63~~ ~~57~~ 53 bytes

-6 thanks to Erik the Outgolfer. -4 thanks to ngn.

Anonymous tacit prefix function.

```
'\w+'⎕R{⎕UCS a+(2>≢b)×120153+84×⊃b←∪96>a←⎕UCS⍵.Match}

```

Since TIO scrambles Unicode output from Dyalog APL, here is a screenshot of the code in action:

---

`'\w+'⎕R` PCRE **R**eplace words with the result of applying the following…

`{`...`}` anonymous lambda:

`⍵.Match` the found word

`⎕UCS` the **U**niversal **C**haracter **S**et code points of that

`a←` store that in `a`

`96>` 0 or 1 for whether 96 is greater than each of those

take just the unique; `[0]` or `[1]` or `[0,1]` or `[1,0]`

`b←` store that in `b`

pick the first from that

`84×` multiply 84 with that

`120153+` add 120153 to that

`(` multiply the following with that:

`≢b` the tally (length) of `b` (`1` if single-case, `2` if mixed-case)

`2>` 0 or 1 for whether two is greater than that (`1` if single-case, `0` if mixed-case)

`a+` the original code points added to that

`⎕UCS` convert the resulting code points back to characters
> 9 votes

# Answer
# Clean, ~~268~~ ~~265~~ ~~232~~ 224 bytes

As a neat bonus, this works with strings containing *any* character. Including nulls.

```
import StdLib,StdInt,StdBool,Text.Unicode,Text.Unicode.UChar
u=isUpper
l=isAlpha
$c|l c=fromInt(toInt c+120153+if(u c)84 0)=c
?[h,s:t]=[if(u h<>isLower s)($c)c\\c<-[h,s:t]]
?[h]=[$h]
@s=[y\\x<-groupBy(\a b=l a&&l b)s,y<- ?x]

```

Try it online!

Defines the function `@`, taking a `UString` and returning a `UString`
> 8 votes

# Answer
# C, 292 characters, 448 bytes (in UTF-8)

```
char*t;s,i,k;p(l){for(l=s=*t/96,i=k=strlen(t);i--;)t[i]/96-s&&++l;for(l=l-s&&write(1,t,k);!l&++i<k;)write(1,s?""+t[i]*4-388:""+t[i]*4-260,4);}f(char*s){char b[strlen(s)];for(t=b;*s;++s)*s<47?(*t=0),p(t=b),putchar(*s):(*t++=*s);*t=0;p(t=b);}

```

Try it online!

**Unrolled:**

```
char*t;
s,i,k;

p(l)
{
    for (l=s=*t/96, i=k=strlen(t); i--;)
        t[i]/96-s && ++l;

    for (l=l-s&&write(1, t, k); !l&++i<k;)
        write(1, s ? ""+t[i]*4-388
                   : ""+t[i]*4-260, 4);
}

f(char*s)
{
    char b[strlen(s)];

    for (t=b; *s; ++s)
        *s<47 ? (*t=0), p(t=b), putchar(*s) : (*t++=*s);

    *t = 0;
    p(t=b);
}

```
> 6 votes

# Answer
# Java 8, ~~221~~ ~~219~~ ~~203~~ 201 bytes

```
s->{StringBuffer r=new StringBuffer();for(String x:s.split("(?<=[\\. ])|(?=[\\. ])"))x.codePoints().forEach(c->r.appendCodePoint(c+(x.matches("[A-Z]+")?120237:x.matches("[a-z]+")?120153:0)));return r;}

```

I have to use a `StringBuffer` instead of a regular `String` to use `.appendCodePoint`, unfortunately..

**Explanation:**

Try it online.

```
s->{                           // Method with String parameter and StringBuffer return-type
  StringBuffer r=new StringBuffer();
                               //  Resulting StringBuffer
  for(String x:s.split("(?<=[\\. ])|(?=[\\. ])"))
                               //  Split by space or dot, and keep them as separate items,
                               //  and loop over all those substrings
   x.codePoints().forEach(c->  //   Inner loop over the codepoints of that substring
      r.appendCodePoint(       //    Convert int to char, and append it to the result:
        c                      //     The next codepoint of the substring
        +(x.matches("[A-Z]+")? //     If the word is fully uppercase:
           120237              //      Add 120237 to convert it to Math Sans Bold
          :x.matches("[a-z]+")?//     Else-if the word is fully lowercase:
           120153              //      Add 120153 to convert it to Math Sans
          :                    //     Else (mixed case, or a dot/space)
           0)));               //      Leave the codepoint (and thus the character) as is
  return r;}                   //  Return the resulting StringBuffer

```
> 5 votes

# Answer
# Haskell, ~~172~~ 170 bytes

```
(s#w)r=[x|all(`elem`s)w,c<-w,(x,k)<-zip r s,c==k]
t[]=[]
t w=filter(>[])[['A'..'Z']#w$[''..],['a'..'z']#w$[''..],w]!!0
f s|(a,b:c)<-span(>'.')s=t a++b:f c|1>0=t s

```

Try it online!

Fairly straightforward. The `#` operator takes the set `s` of charcters (upper or lower case) the word `w`, and the math sans set `r`. It returns the word in the math sans font if all the characters in the word are in `s` or the empty list otherwise. The `t` function takes a word and tries all three possiblities (all upper, all lower, or mixed), returning the first one that isn't empty. The `f` function finds the first word by using `span`, transforming it with `t` and concatenating it with the separator (either `.` or space) and recurring on the rest of the string. The alternate case is for if span can't find a separator; we just transform the string.

Edit: Thanks to @Laikoni for taking off 2 bytes! I'm not used to the whole "operator that takes three arguments" thing
> 4 votes

# Answer
# Jelly, 34 bytes

```
e€ØBŒg
ṁÇµŒl,Œuiị“¡ẓƬ“¡ẓġ“’×Ç+OỌµ€

```

Try it online!

Full program.
> 3 votes

# Answer
# Japt, ~~34~~ ~~33~~ ~~32~~ 31 bytes

Includes an unprintable (charcode 153) after the last `#`.

```
rV="%b%A+%b"Èc+#x#í
rVv Èc+#x#

```

Try it

---

## Explanation

```
                        :Implicit input of string U
r                       :Replace
   "%b%A+%b"            :/\b[A-Z]+\b/g
 V=                     :Assign ^that to variable V
            È           :Run each match through a function
             c          :Map over the codepoints of the current match
              +#x#í     :  Add 120237
\n                      :Assign the result of that replacement to variable U
rVv                     :Another replacement, this time with V lowercased to give us the RegEx /\b[a-z]+\b/g
    Èc+#x#              :And, again, map over the codepoints of each match, this time adding 120153 to each

```

---

## Original 32 Byte Japt v2 Solution

```
r/\b(\A+|\a+)\b/Èc_+#x#+#T*(X¶u

```

Try it

```
r                                     :Replace
 /\b(\A+|\a+)\b/                      :...all matches of this RegEx (\A=[A-Z], \a=[a-z])
                È                     :Pass each match through a function, with X being the current match
                 c_                   :Pass the codepoints of X through a function
                   +                  :Add to the current codepoint
                    #x#               :120153 (there's an unprintable after the second #)
                        +#T           :Plus 84
                           *          :  Multiplied by
                            (X¶u      :  Is X equal to its uppercase self

```
> 3 votes

# Answer
# Python 3, ~~173~~ ~~122~~ 120 bytes

```
lambda s:''.join(chr(ord(c)+120153*t.islower()+120237*t.isupper())for t in re.split(r'\b(\w+)\b',s)for c in t)
import re

```

-51 bytes from ShreevatsaR

-2 bytes from abccd

Try it online!

Splits on word boundaries (`re.split(r'\b(\w+)\b',s)`), then maps lowercase words to (`+120153*t.islower()`), and uppercase words to (`+120237*t.isupper()`), and leaves mixed-case words alone, then `join`s the words back up.

Ungolfed and un-lambda-ed:

```
def f(s):
    words = re.split(r'\b(\w+)\b', s)
    ret = ''
    for word in words:
        for char in word:
            if word.isupper():
                ret += chr(ord(c) + 120237)
            elif word.islower():
                ret += chr(ord(c) + 120153)
            else:
                ret += c
    return ret

```
> 3 votes

# Answer
# Retina, 84 bytes

```
/\b[A-Z]+\b/_(`.
ĵ$&
)T`L`ۮ-܇
/\b[a-z]+\b/_(`.
ĵ$&
)T`l`ں-ۓ
T`ÿ-߿`퟿-

```

Try it online! Explanation: Retina is a .NET application and therefore works in UTF-16 internally. Unfortunately as the Math Sans characters aren't in the BMP I can't directly transliterate them because the number of code points differs. Worse, I can't use unpaired surrogates at all. Instead, I shift the appropriate words into characters in the range `0xFF-0x7FF` which conveniently only take two bytes to encode, plus I also prefix them with the `0x135` character. Finally I map that range onto the a range that overlaps the unpaired surrogates, creating valid BMP pairs.
> 3 votes

# Answer
# JavaScript (ES6), ~~99~~ ~~114~~ 113 bytes

```
s=>s.replace(/\b([A-Z]+|[a-z]+)\b/g,e=>e.replace(/./g,f=>String.fromCodePoint(f.charCodeAt()+120153+(f<'a')*84)))

```

(Thanks to @pfg for pointing out an important flaw in my first solution.)

-1 bytes thanks to @Neil.

**Snippet:**

```
let f =

s=>s.replace(/\b([A-Z]+|[a-z]+)\b/g,e=>e.replace(/./g,f=>String.fromCodePoint(f.charCodeAt()+120153+(f<'a')*84)))

d.innerHTML=f('This is an example STRING that c.o.U.L.d. be INPUTTED. It can CONTAIN multiple sentences.');
```

```
<p id="d">
```
> 1 votes

# Answer
# 05AB1E, 33 bytes

```
€aγ€g£εÐ.u•1Ù„•*s.l•1Ùm•*+sÇ+çJ}J

```

Try it online!
> 1 votes

---
Tags: code-golf, unicode
---


# Question
Title: Partition it into as few disjoint contiguous increasing subsequences as possible
## Specification

This challenge is simple to state: your input is a non-empty array of nonnegative integers, and your task is to partition it into as few substrings as possible, such that each substring is a permutation of a consecutive integer range. More formally, if the input array is `A`, then the output is minimum number of partition of `A` into `B`(s):

* Each arrays `B` form a partition of `A` into substrings. Inductively, this means that either `B` is the singleton array containing 1 element from `A`, or the elements of `B` is a subsequence of `A`, which when sorted are contiguous like `x,x+1,x+2,..`.
* The number of arrays `B` is minimal.

## Example

Consider the input array `A = [1,2,3,4,3,5]`.
Output is `2`
One possible minimal partitions are `B = [1,2,3],[4,3,5]`. That's the only partition to 2 substrings.

`{4,3,5}` in sorted order is `{3,4,5}` which is contiguous.

## Input

An array of integers `A`.

## Output

A number, indicate the smallest number of parts `A` can be splitted to.

## Winning criteria

Your submissions will be scored in bytes, with less bytes being better.

# Answer
> 1 votes
# Kotlin, 91 bytes

```
fold(mutableListOf<Int>()){r,i->r.indexOfFirst{it<i}.let{if(it<0)r+=i else r[it]=i
r}}.size

```

## Beautified

```
fold(mutableListOf<Int>()) {r,i->
    r.indexOfFirst { it<i }.let {
        if (it<0) r+=i else r[it]=i
        r
    }
}.size

```

## Test

```
fun MutableList<Int>.f() =
fold(mutableListOf<Int>()){r,i->r.indexOfFirst{it<i}.let{if(it<0)r+=i else r[it]=i
r}}.size

fun main(args: Array<String>) {
    val i = mutableListOf(1,2,3,4,3,5)
    println(i.f())
}

```

## TIO

TryItOnline

# Answer
> 0 votes
## JavaScript (ES6), 82 bytes

```
f=(a,n=Math.min(...a),i=a.indexOf(n))=>1/a[0]?i<0?1+f(a):f(a,a.splice(i,1)[0]+1):1

```

# Answer
> 0 votes
# Haskell, 139 bytes

```
import Data.List
l=length
q(x:r)=map([x]:)(q r)++[(x:y):v|(y:v)<-q r]
q[]=[[]]
s(x:y)=x+l y==last(x:y)
f x=minimum[l y|y<-q x,all(s.sort)y]

```

# Answer
> 0 votes
# Jelly, 9 bytes

```
Œ!Iċ€1ṀạL

```

Try it online!

### How it works

```
Œ!Iċ€1ṀạL  Main link. Argument: A (array)

Œ!         Take all permutations of A.
  I        Increments; compute the forward differences of each permutation.
   ċ€1     Count the number of 1's i each array of deltas.
      Ṁ    Take the maximum.
        L  Compute the length of A.
       ạ   Take the absolute value of the difference of the maximum and the length.

```

---
Tags: code-golf, subsequence, set-partitions
---


title: Compare Two Lists by Their Maximum

text:
# Question
Title: Compare Two Lists by Their Maximum
Given two *different* lists of non-negative integers, return the list that has the highest maximum (e.g. `[4, 2], [3, 3, 1] -> [4, 2]`).

If they both have the same maximum, return the list that contains more instances of this maximum (e.g. `[4, 2, 4], [4, 3, 3, 3, 1, 3] -> [4, 2, 4]`).

If, after these comparisons, they are equal, do the same comparison but with their next highest item (e.g. `[2, 3, 4, 4], [4, 4, 3, 3, 1] -> [4, 4, 3, 3, 1]`).

If, after all these comparisons, they are still considered to be equal, output the longer list (e.g. `[4, 3, 2, 1, 0], [1, 2, 3, 4] -> [4, 3, 2, 1, 0]`).

Make your code as short as possible.

### Test Cases

```
[4, 4, 4, 4, 2, 4], [4, 4, 4, 4, 3, 2] -> [4, 4, 4, 4, 2, 4]
[0], [] -> [0]
[0, 0], [0] -> [0, 0]
[1], [0, 0] -> [1]
[4, 4, 4, 4, 4, 2], [4, 4, 4, 4, 4] -> [4, 4, 4, 4, 4, 2]
[1, 0], [0, 0, 0] -> [1, 0]

```

# Answer
# Pyth, 4 bytes

```
eo_S

```

Try it online

### Explanation

```
eo_S
 o  NQ    Order the inputs...
  _S      ... by their reversed sorted values...
e         ... and take the last.

```
> 5 votes

# Answer
# Python 2, 44 bytes

```
lambda*x:max(x,key=lambda y:sorted(y)[::-1])

```

Try it online!
> 5 votes

# Answer
# Jelly, 4 bytes

```
NÞÞṪ

```

Try it online!

### How it works

```
NÞÞṪ  Main link. Argument: [u, v] (pair of vectors)

  Þ   Sort [u, v], using the link to the left as key.
NÞ      Sort u (or v) by the negatives of its values.
        This sorts the vector in descending order.
   Ṫ  Tail; select the last, lexicographically larger vector.

```
> 4 votes

# Answer
## Haskell, ~~37~~ 35 bytes

```
import Data.Lists
argmax$sortOn(0-)

```

The input is taken as a two element list, e.g. `( argmax$sortOn(0-) ) [[4,4,4,4,2,4], [4,4,4,4,3,2]]`.

Find the element in the input list which is the maximum after sorting by negating the values (i.e. descending order).
> 2 votes

# Answer
# Clean, 42 bytes

```
import StdEnv
s=sortBy(>)
?a b|s a>s b=a=b

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES7), 52 bytes

```
(a,b,m=d=>d.map(n=>N+=1e4**n,N=0)&&N)=>m(a)>m(b)?a:b

```

This method works *without* sorting the arrays. Instead, it calculates the sum of 10,000 raised to each array's elements. The largest sum represents the array with the highest score. (This solution assumes that neither array has more than 10,000 elements.)

**Test cases**

```
let f=

(a,b,m=d=>d.map(n=>N+=1e4**n,N=0)&&N)=>m(a)>m(b)?a:b

console.log(JSON.stringify(f([4, 4, 4, 4, 2, 4], [4, 4, 4, 4, 3, 2]))); // [4, 4, 4, 4, 2, 4]
console.log(JSON.stringify(f([0], []))); // [0]
console.log(JSON.stringify(f([0, 0], [0]))); // [0, 0]
console.log(JSON.stringify(f([1], [0, 0]))); // [1]
console.log(JSON.stringify(f([4, 4, 4, 4, 4, 2], [4, 4, 4, 4, 4]))); // [4, 4, 4, 4, 4, 2]
console.log(JSON.stringify(f([1, 0], [0, 0, 0]))); // [1, 0]
console.log(JSON.stringify(f([3], [11]))); // [11]
console.log(JSON.stringify(f([4, 3, 3, 3, 1, 3], [4, 2, 4]))); // [4, 2, 4]
console.log(JSON.stringify(f([3,3],[3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]))); //[3, 3]
```
> 1 votes

# Answer
# Ruby, 33 bytes

```
->*a{a.max_by{|x|x.sort.reverse}}

```

Try it online!
> 1 votes

# Answer
# Python 2, 79 bytes

```
lambda*a:max(a,key=lambda l:sum(zip(map(l.count,s(l)),s(l)),())[::-1])
s=sorted

```

Try it online!
> 0 votes

# Answer
# Ruby 149 bytes

```
->n,m{(n+m).sort.reverse.map{|i|r=((a=n.index(i))&&m.index(i)?(b=n.count(i))==(c=m.count(i))?nil:b>c ?n:m:a ?n:m);return r if r};n.size>m.size ? n:m}

```

Try it online!
> 0 votes

# Answer
# Husk, 3 bytes

```
►Ö_

```

Try it online!

This submission basically takes a two-element list of lists as input and retrieves the maximum (), sorted by their values sorted in descending order (`Ö_`).
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
Σ{R}θ

```

Try it online!
> 0 votes

# Answer
## JavaScript (ES6), 98 bytes

```
(a,b,g=a=>[...a].sort((a,b)=>b-a),h=([a,...b],[c,...d])=>a==c?h(b,d):a<c|!(1/a))=>h(g(a),g(b))?b:a

```

`g` sorts a copy of its parameter in reverse order (since `sort` mutates the array), while `h` recursively performs the elementwise comparison of the arrays.
> 0 votes

# Answer
# Perl 6, 17 bytes

```
*.max(*.sort(-*))

```

Test it (Lambda Lambda Lambda)

* `-*` lambda that numerically negates the input
* `*.sort(-*)` lambda that uses that uses the results of applying that to compare elements
* `*.max(*.sort(-*))` lambda that finds the max of those results, and uses that to determine which input to return.
> 0 votes

# Answer
# J, 20 bytes

```
[:{.]\:[:#.[:>\:~&.>

```

Ungolfed:

```
[: {. ] \: [: #. [: > \:~&.>

```

Essentially the Pyth answer, translated unpithily into J.

Try it online!
> 0 votes

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


# Question
Title: Distance Between Two Points Travelling on a Polar Graph Chart
# Brief Problem Explanation

Write a program to find the minimum distance between two points traveling only on rays emanating from the origin and circles centered on the origin.

# Explanation of Premise

Now let's imagine we are on a plane, and on this plane we are only allowed to travel in special ways. We are allowed to travel on any ray emanating from the origin.

We can also travel on any circle centered at a circle

Now our goal is to travel from one point on this plane to another. However, we can't just travel in a simple Euclidian path, we can only do this if the points happen to fall on a ray emanating from the center.

We can travel on this one because it falls on a one of our rays.

We can also travel on circles centered at the origin.

# Examples

Now here is the challenge:

We've got to get from one point to another in the shortest path; often this is a combination of traveling on circles and rays.

This, however, it could also be traveling on two rays.

Sometimes there exist two paths that travel the minimum distance.

# Problem

Your challenge is to write a program that when given two points will give us the minimum distance between them if we follow these rules. The inputs can be given in either rectangular or polar forms and the output ought to be one number, the distance between.

# Test Cases

(with rectangular input)

```
(1,1) (1,-1) -> ~ 2.22144
(0,0) (1, 1) -> ~ 1.41421
(1,0) (-0.4161 , 0.90929) -> ~ 2
(1,1) (1, 0) -> ~ 1.19961
(1,2) (3, 4) -> ~ 3.16609

```

# Answer
# Haskell, ~~49~~ 48 bytes

```
(a!q)c r=min(q+r)$abs(q-r)+acos(cos$a-c)*min q r

```

Usage:

```
> let rect2polar (x,y)=(atan2 y x, sqrt(x^2+y^2))
> let test c1 c2=let [(a1,r1),(a2,r2)]=rect2polar<$>[c1,c2] in (a1!r1)a2 r2
> test (1,0) (-0.4161, 0.90929)
1.9999342590038496

```

Thanks to @Zgarb for saving a byte
> 5 votes

# Answer
## JavaScript (ES6), 65 bytes

```
with(Math)(r,t,s,u,v=acos(cos(t-u)))=>v<2?abs(r-s)+v*min(r,s):r+s

```

Takes polar coordinates. Uses @Angs' trick for reducing an angle to between 0 and π. For rectangular coordinates, something like this works:

```
with(Math)g=(r,t,s,u,v=acos(cos(t-u)))=>v<2?abs(r-s)+v*min(r,s):r+s
with(Math)f=(x,y,v,w)=>g(hypot(y,x),atan2(y,x),hypot(w,v),atan2(y,v))

```
> 4 votes

# Answer
# MATL, 22 bytes

```
|ttsGZ}/X/bX<*|bd|+hX<

```

Input is an array of two complex numbers.

Try it online! Or verify all test cases.

### Explanation

```
|       % Implicitly input array and take absolute value of its entries
tt      % Duplicate twice
s       % Sum. This is the length of the path that follows the two radii
GZ}     % Push input again and split into the two numbers
/X/     % Divide and compute angle. This gives the difference of the angles
        % of the two points, between -pi and pi
bX<     % Bubble up a copy of the array of radii and compute minimum
*|      % Multiply and take absolute value. This is the arc part of the
        % path that follows one arc and the difference of radii
bd|     % Bubble up a copy of the array of radii and compute absolute
        % difference. This is the other part of the second path
+       % Add. This gives the length of second path
hX<     % Concatenate and take minimum to produce the smallest length.
        % Implicitly display

```
> 3 votes

# Answer
# Ruby, 64 bytes

First, my submission. Lambda function with arguments `distance 1, angle 1, distance 2, angle2`.

```
->r,a,s,b{([d=(b-a).abs,?i.to_c.arg*4-d,2].min-2)*[r,s].min+s+r}

```

Now here's two different solutions of 66 bytes (excluding assignment `f=`) followed by my actual submission again at 64 bytes.

```
Solution 1:Using include Math, 66 bytes excluding f=
include Math;f=->r,a,s,b{[acos(cos(b-a)),2].min*[r,s].min+(s-r).abs}

Solution 2:Using complex number to define PI instead, 66 bytes excluding f=
f=->r,a,s,b{[d=(b-a).abs,?i.to_c.arg*4-d,2].min*[r,s].min+(s-r).abs}

SUBMISSION AGAIN, 64 bytes excluding f=
f=->r,a,s,b{([d=(b-a).abs,?i.to_c.arg*4-d,2].min-2)*[r,s].min+s+r}

```

The Submission is based on solution 2, but uses the identity `(s-r).abs`=`s+r-[s,r].min*2` to shorten the code by 2 bytes, hence the `-2` inside the brackets.

The other notable feature is the expression `?i.to_c.arg*4` = 2\*PI without using `include Math`. If lower precision is acceptable this can be replaced by a literal.

**Solution 2 commented in test program**

```
f=->r,a,s,b{          #r,s are distances, a,b are angles for points 1 and 2 respectively.
    [d=(b-a).abs,       #From nearer point we can take arc of length d radians perhaps crossing zero angle to the ray of the further point
    ?i.to_c.arg*4-d,    #or go the other way round which may be shorter (?i.to_c.arg*4 == 2*PI, subtract d from this.)
    2].min*             #or go through the centre if the angle exceeds 2 radians.
  [r,s].min+          #Multiply the radians by the distance of the nearer point from the origin to get the distance travelled.
  (s-r).abs           #Now add the distance to move along the ray out to the further point.
}

#test cases per question (given as complex numbers, converted to arrays of [distance,angle]+[distance,angle] (+ concatenates.)
#the "splat" operator * converts the array to 4 separate arguments for the function.
p f[*("1+i".to_c.polar + "1-i".to_c.polar)]
p f[*("0".to_c.polar + "1+i".to_c.polar)]
p f[*("1".to_c.polar + "-0.4161+0.90929i".to_c.polar)]
p f[*("1+i".to_c.polar + "1".to_c.polar)]
p f[*("1+2i".to_c.polar + "3+4i".to_c.polar)]

```

**Output**

```
2.221441469079183
1.4142135623730951
1.9999342590038496
1.1996117257705434
3.1660966740274357

```
> 2 votes

# Answer
## Mathematica 66 Bytes

This takes rectangular coordinates and can output an exact symbolic solution

```
Min[If[(m=Min[{p,q}=Norm/@#])>0,m*VectorAngle@@#,0]+Abs[p-q],p+q]&

```

Usage:

```
%/@{
{{1,1},{1,-1}},
{{0,0},{1,1}},
{{1,0},{-.4161,.90929}},
{{1,1},{1,0}},
{{1,2},{3,4}}
}

```

yields:

N@% yields:

{2.221441469, 1.414213562, 1.999934259, 1.199611726, 3.166096674}
> 2 votes

# Answer
# Python 2, ~~164~~ ~~126~~ ~~125~~ 132 bytes:

```
def A(a,b,c,d,p=3.1415926535):z=abs(a-c);M=lambda f:2*p*f*abs(b-d)/360.0;print min((a==c)*min(a+c,M(a))+(b==d)*z or'',M(a)+z,M(c)+z)

```

I am currently looking into golfing this more, though. Accepts polar coordinates. Should be called in the format `A(r1,θ1,r2,θ2)`. Outputs a floating point value accurate up to `12` significant figures.

Try It Online! (Ideone)

A simple, straightforward implementation that calculates and outputs to STDOUT the minimum value out of an array of at most 3 values containing:

1. the minimum value out of either the sum of the two lengths (`r1+r2`) or the length of the arc connecting the two points *iff* `r1==r2`;
2. the *difference* between the two distances (`abs(r1-r2)`) *iff* `θ1==θ2` (i.e. the two points are collinear);
3. if none of the previous 2 items are added, then an empty string (`''`) as apparently in Python a string is *greater than* any integer;
4. and 2 final values given from the distances traveled along a circle and a ray and vice-versa between the two points.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
MinMax@Abs@{##}.{Min[Abs[Arg@#-Arg@#2]-1,1],1}&

```

Try it online!

(beats the current 66-byte answer)

Take input as 2 complex numbers.

May have some issues if the input is symbolic. (e.g., `Cos@2 + I Sin@2`)
> 0 votes

---
Tags: code-golf, geometry, path-finding, trigonometry
---


# Question
Title: Given the names of two planets, give the distance
Using the following table (source) write some code that takes the names of two planets and returns the distance between them:

```
+-------------------+---------------+
|      Planets      | Distance (km) |
+-------------------+---------------+
| Mercury -> Venus  |      50290000 |
| Venus -> Earth    |      41400000 |
| Earth -> Mars     |      78340000 |
| Mars -> Jupiter   |     550390000 |
| Jupiter -> Saturn |     646270000 |
| Saturn -> Uranus  |    1448950000 |
| Uranus -> Neptune |    1627450000 |
| Neptune -> Pluto  |    1405380000 |
+-------------------+---------------+

```

Examples, input then output:

```
Mercury, Mars
170030000

```

```
Neptune, Jupiter
-3722670000

```

```
Earth, Earth
0

```

Note the negative sign there, as Jupiter comes before Neptune. They are also all integers.

Pluto doesn't have to be included (mostly because of a weird orbit which makes it hard to work out the distance - that distance given is my own calculation, but as Pluto is all famous now...).

By distances between planets I'm meaning orbits - I don't expect a date and working out where they are.

This is code golf, shortest code wins.

# Answer
> 24 votes
# CJam, ~~54~~ ~~51~~ 44 bytes

```
2{"X84VT:Z/3KD'Y->>6\ Ta "3/r26b93%=70be4}*-

```

Try it online in the CJam interpreter.

### Idea

We use a simple hashing function to identify all eight planets. By considering each name as the array of its code points, converting them from base 26 to integer and taking the result modulo 93 then modulo 8, **Mercury**, **Venus**, **Earth**, etc. map to **2**, **4**, **0**, **1**, **3**, **5**, **6** and **7**.

Now, we choose a point that lies 320,000 km behind Neptune and calculate the distances of all eight planets to that point. After dropping four trailing zeroes and reordering the planets so that they fit the 8 indexes from above, we obtain the array

```
[435172 427338 444341 372299 439312 307672 162777 32]

```

which, if we encode each integer in base 70, yields the following:

```
[
   [1 18 56 52] [1 17 14 58] [1 20 47 51] [1 5 68 39]
   [1 19 45 62] [  62 55 22] [  33 15 27] [       32]
]

```

Remembering that two adjacent digits `(A B)` can be replaced with `((A-1) (B+70))`, we can modify the array from above so that all integers can be encoded as printable ASCII characters:

```
["X84" "VT:" "Z/3" "KD'" "Y->" ">6\\" " Ta" " "]

```

### Code

```
2{                         e# Do twice:
  "X84VT:Z/3KD'Y->>6\ Ta " e#   Push that string.
  3/                       e#   Chop it into chunks of length 3.
  r                        e#   Read a token from STDIN.
  26b                      e#   Convert from base 26 to integer.
  93%                      e#   Take the result modulo 93.
  =                        e#   Retrieve the chunk at that index.
  70b                      e#   Convert from base 70 to integer.
  e4                       e#   Multiply by 10,000.
}*                         e#
-                          e# Subtract the two results.

```

# Answer
> 10 votes
# Python 2, ~~149~~ ~~147~~ ~~142~~ ~~138~~ ~~128~~ ~~123~~ 119 Bytes

Just uses a simple lookup to figure out which distances to use :) This defines an anonymous function, so to use it you'll need to give it a name.

*Thanks to Sp3000 for ideas that saved a bunch of bytes!*

```
lambda*x:int.__sub__(*[[0,5029,9169,17003,72042,136669,281564,444309]['MeVeEaMaJuSaUr'.find(k[:2])/2]for k in x])*~9999

```

Indented properly and ungolfed slightly for readability:

```
def f(*x):
 d=0,5029,9169,17003,72042,136669,281564,444309
 a,b=[d['MeVeEaMaJuSaUr'.find(k[:2])/2]for k in x]
 print(b-a)*10000

```

Call like so:

```
f("Mercury","Mars")    -> 170030000
f("Neptune","Jupiter") -> -3722670000L

```

# Answer
> 8 votes
# Prolog, ~~190~~ ~~174~~ 151 bytes

Thanks to Fatalize for guidance.

```
g(A,X):-sub_atom(A,2,2,_,B),member(B:X,[rc:0,nu:5029,rt:9169,rs:17003,pi:72042,tu:136669,an:281564,pt:444309]).
s(A,B,R):-g(A,X),g(B,Y),R is(Y-X)*10^4.

```

---

```
$ gprolog --consult-file src.pro
| ?- s('Mercury','Mars',R).
R = 170030000 ?
yes
| ?- s('Neptune','Jupiter',R).
R = -3722670000 ?
yes
| ?- s('Earth','Earth',R).
R = 0 ?
yes

```

# Answer
> 7 votes
# Java, ~~274~~ ~~272~~ 264 bytes (includes Pluto!)

```
  void p(String p,String l){String q="MeVeEaMaJuSaUrNePl";int w=q.indexOf(p.substring(0,2))/2,e=q.indexOf(l.substring(0,2))/2,m=1,t=e,d[]={5029,4140,7834,55039,64627,144895,162745,140538};long h=0;if(w>e){e=w;w=t;m=-1;}for(;e-->w;)h+=d[e]*1e4;System.out.print(h*m);}

```

Input/Output:

```
p("Mercury","Mars") --> 170030000
p("Mars","Mercury") --> -170030000
p("Earth","Earth")  --> 0

```

Spaced and tabbed:

```
void p(String p,String l){
    String q="MeVeEaMaJuSaUrNePl";
    int w=q.indexOf(p.substring(0,2))/2,
      e=q.indexOf(l.substring(0,2))/2,
      m=1,
      t=e,
      d[]={5029,4140,7834,55039,64627,144895,162745,140538};
    long h=0;
    if(w>e){
        e=w;
        w=t;
        m=-1;
    }
    for(;e-->w;)
        h+=d[e]*1e4;
    System.out.print(h*m);
}

```

# Answer
> 7 votes
# JavaScript (ES6), ~~115~~ 110 bytes

```
(x,y,g=k=>"Me0Ve5029Ea9169Ma17003Ju72042Sa136669Ur281564Ne444309".match(k[0]+k[1]+"(\\d*)")[1]*1e4)=>g(y)-g(x)

```

This is an anonymous function, so you will need to store it in a variable (`f=...; f("Earth", "Mercury")`) or use it as a parenthesised expression (`(...)("Earth", "Mercury")`.

That messy string is the first two letters of each planet, followed by that planet's distance from Mercury (divided by 10000, to save space). The inner function `g` does the following:

1. takes a name (`k`),
2. reduces it to the first two letters (`k[0]+k[1]`),
3. uses a regex match to find the corresponding distance from Mercury, divided by 10000 (e.g., the "Earth" regex looks like `Ea(\d*)`),
4. multiplies the value by 10000 (`1e4`) and returns the result.

By subtracting one Mercury-distance from the other, we get the distance between the planets.

# Answer
> 6 votes
# APL, ~~97~~ ~~95~~ 85 bytes

```
{1E4×-/(0 5029 9169 17003 72042 136669 281564 444309[{⍵≡'Mars':4⋄'MVEmJSUN'⍳⊃⍵}¨⍵⍺])}

```

This creates an unnamed dyadic function that takes the origin planet as the left argument and the destination planet as the right.

You can try it online!

# Answer
> 6 votes
# Python, 118 bytes

```
n=lambda x:(5029,9169,17003,72042,136669,281564,444309,0)["VeEaMaJuSaUrNe".find(x[:2])/2]*10000
f=lambda a,b:n(b)-n(a)

```

`n` is a function that returns distance from Mercury.

The string `"VeEaMaJuSaUrNe"` is the first two characters of all planet names *except Mercury*. `find` cannot find Mercury so will return -1. -1/2 is still -1 so this is the last element in the tuple, which is 0.

Simple test code:

```
test = (
    ("Mercury","Venus",50290000),
    ("Venus","Earth",41400000),
    ("Earth","Mars",78340000),
    ("Mars","Jupiter",550390000),
    ("Jupiter","Saturn",646270000),
    ("Saturn","Uranus",1448950000),
    ("Uranus","Neptune",1627450000),
    #("Neptune","Pluto",1405380000),
    ("Mercury","Mars",170030000),
    ("Neptune","Jupiter",-3722670000),
    ("Earth","Earth",0))

for a, b, expect in test:
    print a, "->", b, "=", expect
    assert f(a, b) == expect, f(a, b)

```

# Answer
> 4 votes
# J--, 226 bytes

```
main{str q="MeVeEaMaJuSaUrNePl";int w=q.indexOf(a[0].subs(0,2))/2,e=q.indexOf(a[1].subs(0,2))/2,m=1,t=e,d[]={5029,4140,7834,55039,64627,144895,162745,140538};lg h = 0;@i(w>e){e=w;w=t;m=-1;}@f(;e--^^w;)h+=d[e]*10000;echo(h*m);}
```

I don't think this counts as I was making the language while the question was out, but it was mostly a test of how small I could compress Java code. This is *totally* and *completely* based off DeadChex's answer.

Here's how to use it:

```
$ j-- planets.j-- Mercury Mars
170030000
```

# Answer
> 4 votes
# Pyth - 59 53 bytes

Encodes the distance in unicode codepoints.

```
-Fm*^T4s<CM"Ꭵာẚ훿ﱳ"x"MshrJtaN"@d14_Q

```

The name lookup is kinda cool because it loops around. Thanks to @Dennis for suggesting index 14 as a collision free lookup!

Try it here online.

# Answer
> 3 votes
## CoffeeScript, ~~183~~ 180 bytes

```
f=(a,b)->t=[d=0,5029,4140,7834,55039,64627,144895,162745];n='MeVeEaMaJuSaUrNe';t=(x=n[q='indexOf'](a[..1])/2)<(y=n[q](b[..1])/2)&&t[x+1..y]||t[y+1..x];d+=c*1e4for c in t;x>y&&-d||d

```

Unminified:

```
f = (a,b) ->
 t = [d = 0, 5029, 4140, 7834, 55039, 64627, 144895, 162745]
 n = 'MeVeEaMaJuSaUrNe'
 t = if (x = n[q='indexOf'](a[..1]) / 2) < (y = n[q](b[..1]) / 2) then t[x+1..y] else t[y+1..x];
 d += c * 1e4 for c in t
 if x > y then -d else d

```

# Answer
> 3 votes
# Haskell, ~~160~~ ~~158~~ 157 bytes

```
data P=Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune deriving Enum
d x=[0,5029,9169,17003,72042,136669,281564,444309]!!fromEnum x
x#y=(d y-d x)*10^4

```

Usage example:

```
*Main> Neptune # Jupiter
-3722670000

*Main> Mercury # Mars
170030000

```

How it works: I define a new data type `P` where the constructor names are the names of the planets. I also put it in the `Enum` class, i.e. I get a mapping to integers via `fromEnum` (in order of definition, starting with `Mercury` -\> `0`). This integer can be used as a index for the distance list.

Edit: @Kritzefitz found two bytes to save and @Alchymist another one. Thanks!

# Answer
> 3 votes
# Bash, 140 bytes

```
bc<<<"(-`sed -e 's/,/+/;s/[abd-z]//g;s/Mc/0/g;s/V/5029/g;s/E/9169/g;s/M/17003/g;s/J/72042/g;s/S/136669/g;s/U/281564/g;s/N/444309/g'`)*10^4"

```

---

```
$ bash script.sh
Mercury, Mars
170030000
$ bash script.sh
Neptune, Jupiter
-3722670000
$ bash script.sh
Earth, Earth
0

```

# Answer
> 3 votes
# Ruby, 168 bytes

```
a=ARGV.map{|e|e=='Mars'?3:%w(M V E m J S U N P).index(e[0])}
p 10000*(a[1]<=>a[0])*[5029,4140,7834,55039,64627,144895,162745,140538][a.min..a.max-1].inject(0){|r,e|r+e}

```

It's designed as a script to be run from command line, thus uses `ARGV`. Run as

```
$ ruby planets.rb Mercury Mars
170030000
$ ruby planets.rb Neptune Jupiter
-3722670000
$ ruby planets.rb Earth Earth
0
$ ruby planets.rb Mercury Venus
50290000
$ ruby planets.rb Venus Earth
41400000
$ ruby planets.rb Mercury Mercury
0
$ ruby planets.rb Pluto Pluto
0
$ ruby planets.rb Mercury Pluto
5848470000
$ ruby planets.rb Pluto Mercury
-5848470000

```

# Answer
> 2 votes
# Julia, ~~206~~ ~~203~~ 190 bytes

```
(f,t)->t==f?0:(M(p)=p=="Mars"?4:findin("MVEmJSUN",p[1])[1];T=M(t);F=M(f);(T>F?1:-1)*sum([get(Dict(zip(1:8,[5029,4140,7834,55039,64627,144895,162745,0])),i,0)for i=T>F?(F:T-1):(T:F+1)])*1000)

```

This creates an unnamed function that accepts two strings and returns an integer. To call it, give it a name.

Ungolfed + explanation:

```
function planet_distance(p_from, p_to)
    if p_from == p_to
        # Return 0 right away if we aren't going anywhere
        0
    else
        # Define a function to get the planet's order in the solar system
        M(p) = p == "Mars" ? 4 : findin("MVEmJSUN", p[1])[1]

        # Get indices for origin and destination
        ind_from = M(p_from)
        ind_to = M(p_to)

        # Define a dictionary to look up distances by index
        D = Dict(zip(1:8,[5029,4140,7834,55039,64627,144895,162745,0])

        # Determine whether the distance will be positive or negative
        # and the range over which we'll sum distances
        if ind_to > ind_from
            coef = 1
            range = ind_from:ind_to-1
        else
            coef = -1
            range = ind_to:ind_from+1
        end

        # Sum the distances between points
        coef * sum([get(D, i, 0) for i in range]) * 1000
    end
end

```

# Answer
> 2 votes
# Java, ~~257~~ 228 bytes

```
enum Z{Mercury(0),Venus(5029),Earth(9169),Mars(17003),Jupiter(72042),Saturn(136669),Uranus(281564),Neptune(444309),Pluto(584847);long r;Z(long x){r=x*10000;}static long d(String...s){return Z.valueOf(s[1]).r-Z.valueOf(s[0]).r;}}

```

`static long d(String...s){...}` solves the challenge. Input requires names of planets to match the enum's constants' names exactly. I love how java provides a string to enum conversion method for me \<3

Usage:

`Z.d("Mercury","Pluto")` returns `5848470000`

`Z.d("Pluto","Mercury")` returns `-5848470000`

`Z.d("Uranus","Neptune")` returns `1627450000`

`Z.d("Mars","Pluto")` returns `5678440000`

# Answer
> 1 votes
# C (gcc) pre-processor macro, 146 bytes

```
char*p="(3$,?2'+";D[]={0,5029,9169,17003,72042,136669,281564,444309,584847};
#define E(x)D[strchr(p,*x^x[1])-p]
#define f(s,t)(E(t)-E(s))*10000LL

```

Try it online!

Another version, courtesy of ceilingcat, using Unicode, which seems to make TiO count weirdly:

# C (gcc), 119 bytes

```
char*p="(3$,?2'+";
#define E(x)L"\0Ꭵ⏑䉫"[index(p,*x^x[1])-p]
#define f(s,t)(E(t)-E(s))*10000LL

```

Try it online!

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


title: Hexcellent Minesweeping

text:
# Question
Title: Hexcellent Minesweeping
Hexcells is a game based off of Minesweeper played on hexagons. (Full disclosure: I have nothing to do with Hexcells. In fact I don't really like the game.) Most of Hexcells rules can be pretty easily expressed in Generalized Minesweeper (Minesweeper played on an arbitrary graph). The one that is most difficult is the `{X}` and `-X-` rules.

The `{X}` rule tells us that a cell borders `X` mines and that all of these mines border each other in a continuous path. For example if we had the board:

```
  ?   ?

?  {3}  ?

  ?   ?

```

The 6 possibilities for mine placement would be

```
  *   .       .   .       .   .       .   *       *   *       *   *

*  {3}  .   *  {3}  .   .  {3}  *   .  {3}  *   .  {3}  *   *  {3}  .

  *   .       *   *       *   *       .   *       .   .       .   .

```

Your goal is to implement the rule `{3}` in generalized Minesweeper.

## Specifics

Generalized Minesweeper is Minesweeper played on an arbitrary graph. The graph has two types of vertex, an "indicator" or a "value". A value can be either on or off (a mine or a dud) however its state is unknown to the player. An indicator tells the player how many adjacent vertices are on (mines) and does not count as a mine itself.

For example the following board for Generalized Minesweeper tells us that cells A and B are either both mines or neither of them are mines.

*(In the diagram indicators are marked in gray while values are white)*

Unlike in normal minesweeper where you click values that are off to reveal indicators, there is no such mechanic in Generalized Minesweeper. A player simply determines for what states of the graph can satisfy its indicator.

Your goal is to build a structure in Generalized Minesweeper such that there are 6 specific cells that can only have states that fulfill as if they were connected with the Hexcells rule `{3}`. When you write your solution you should not have specific values in mind for value cells. (In answer to H.PWiz's question it is allowed that some value cells might be deducible from the state, but you can always improve your score by removing such cells)

## Scoring

You answers will be scored by the number of vertices in the final graph minus 6 (for the 6 inputs) with a lower score being better. If two answers tie in this metric the tie breaker will be the number of edges.

## Solvability

This problem is solvable, I have a solution to this problem and I will post it once this challenge is a week old.

# Answer
# ~~7~~ 5 vertices, ~~14~~ 10 edges

(Graph made with this online tool and paint.)

`A`-`F` are our six nodes, and `J` is a helper node. The three `1`-nodes enforce that opposite nodes are different, while the `2`-node makes sure that `A`, `C` and `E` can neither be all mines, nor all empty.

*Edit: -2 vertices thanks to CalculatorFeline and H.PWiz!*
> 15 votes

# Answer
# 44 vertices, 66 edges

First, we start with a ring of 6 value cells all connected to a 3. These cells will be the cells with the `{3}` rule.

```
  A   B
   \ /
F---3---C
   / \
  E   D

```

Then, we attach 012 sensors to the value cell pairs (AB,BC,CD,DE,EF,FA). The structure of the 012 sensor is below.

```
O   ?---1---?
 \ /       /
  2---?---1
 / \
A   B

```

A and B are the inputs to the sensor and O is the output. The ? cells are generic value cells. O will be a mine if exactly one of A and B is a mine and empty otherwise. Then, we connect a 2 node to all the sensor outputs. This ensures that there are exactly 2 pairs with exactly 1 mine, and it can be proven that the only configurations that satisfy this are the ones that satisfy `{3}`. Each sensor takes 7 nodes, so 6 sensors requires 42. Add the 3 node connected to ABCDEF and the 2 node connected to the outputs and you get 44.

This solution can also be adapted for `{1}`-`{5}` by changing the 3 node to some other value.
> 4 votes

# Answer
# 9 Vertices, 17 Edges

Where ? is a value cell, that is not one of the `6` we care about, we need the following subgraph.

```
    ___________
?  /    ?      \?
 \|    /|\     /
  3¯¯¯¯ 1 ¯¯¯¯2
  |\    |    /|
  | \ /¯|¯¯¯¯ |
  |  X  |     |
 /  / \_|___  \
A__/    B   \__C

```

My ASCII-art skill are dreadful.

With those 6 vertices set up: `ABC` can have the following states: `111`, `110`, `011`, `000`, `100`, `001`

With the cells corresponding to the following hexagon, all we then need are 3 more indicator cells `A-1-D`, `B-1-E`, `C-1-F`

```
  B  C
A      D
  F  E

```
> 3 votes

---
Tags: game, graph-theory, atomic-code-golf
---