title: Calculate your Icy Tower Score

text:
# Question
Title: Calculate your Icy Tower Score
Do you know Icy Tower ? Here is a gameplay example of what i'm talking about

The game concept is simple : you play as Harold the Homeboy, and your goal is to jump from floors to floors to go as high as possible without falling and getting off-screen ( the camera goes higher following you or at a speed that gets faster over time, and does not go down ).

If you get off-screen ( fell or camera was too fast for you to keep up ), it's game over, and then you get a score.

Your task is to write a program/function/whatever that calculates the score based on a input.

### How to calculate the score :

The formula is simple : \\$Score = 10 * LastFloor + Sum(ValidComboList.TotalFloorJumped^2)\\$

### What is a valid combo ?

You have to jump from floors to floors to go as high as possible. Sometimes, you will the to the floor \\$F+1\\$

But sometimes, if you go fast enough ( faster = higher jumps ), you will do a multi-floor jump, and skip some floors between. A combo is a sequence of multi-floors jump. To be considered as a multi-floor jump, you need to skip at least 1 floor, meaning you need to get to the floor \\$F+x\\$ where \\$x \>= 2\\$

See that you always jump to \\$x \>= 2\\$, jumps to lower floors with floors skipped between are not considered valid

A combo ends when :

* You jump to the floor \\$F+x\\$ where \\$(x \< 0) | (x == 1)\\$
* You wait more than about 3 seconds on the same floor ( in the gameplay video, you can see on the left a "timing bar", and the combo ends if it gets empty )
* You get off-screen ( falling or not jumping fast enough )

In this challenge, to simplify a bit, we will consider that, when the input indicates a "jump to the same floor \\$F+0\\$" means that the 3 second timeout is passed, so the two rules will be simplified in one :

"You jump to the floor \\$F+x\\$ where \\$x\<2\\$

A valid combo ( a combo that will be used for the score calculation ) :

* The number of multi-floor jumps \\$N \>= 2\\$
* The combo MUST NOT end with going off-screen. If you go off-screen, the combo is invalid and won't included in the score. Said in another way : The combo must be followed by a jump to another floor or by waiting about 3 seconds.

In this challenge, since we consider that jumping to the same floor is waiting 3 seconds, the rules to make a valid combo is "You must jump to another floor"

Since you need at least 2 multi-floor jumps to make a combo, the number of total floor jumped is higher than 4

### The input

The input will be a "list" of integers ( or STDIN input ) which represents the sequence of floor jumped on. For example, the start to the video linked previously in the post will look like :

```
[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 54]

```

for the first floors. The start floor is ommited. This input end on floor 54 meaning he went off-screen just after that, without getting to another floor, so there's the game over ( this was not the case in the video since he went to the floor 232, so the array accurately representing the sequence would end with 232 at the end )

Here, with this input, you must output \\$829\\$, because :

\\$Score = 10 * 54 + 12^2 + 8^2 + 9^2\\$ Because the last floor Harold was on is the floor number 54, and he made 3 valid combos :

* First combo of 4 multi-floor jumps with a total of 12 floors jumped in that combo
* Second combo of 2 multi-floor jumps with a total of 8 floors jumped in that combo
* The last combo of 2 multi-floor jumps with a total of 9 floors jumped in that combo

## Test cases :

`[] => Undefined Behavior`

`[5]` =\> \\$50\\$

`[4 0 5 6 8 10 10]` =\> \\$10\*10 + 4^2 = 116\\$ **Correction applied**

`[4 0 5 6 6 6 6 8 10 10]` =\> \\$10\*10 + 4^2 = 116\\$ ( Here, Harold just waited 9 seconds. No combo to validate, but still a legitimate input ) **Correction applied**

`[5 7 10 10 11 9 14 17 15 16]` =\> \\$10\*16 + 10^2 + 8^2 = 324\\$

`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 54]` =\> \\$10 * 54 + 12^2 + 8^2 + 9^2 = 829\\$

`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 56]` =\> \\$10 * 54 + 12^2 + 8^2 + 9^2 = 849\\$

`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 55]` =\> \\$10 * 55 + 12^2 + 8^2 + 9^2 = 839\\$ ( harold waited 3 seconds to validate the combo )

`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55]` =\> \\$10 * 55 + 12^2 + 8^2 = 758\\$ ( because harold went off-screen without confirming the combo)

If you want, you can condsider that the input always starts with zero ( since the game start at floor 0 ), if this is the case, say it in your answer

## Rules :

Edit : Correction applied on some test cases

# Answer
> 5 votes
# Japt, ~~28~~ ~~27~~ 24 bytes

*-1 byte from @kamil \<3, -3 from @Shaggy :o. These guys are genius*

```
ä- ô>2n)¯J lÉ mx x²+A*Uo

```

Try it online! or Test it all

---

# Japt, 28 bytes, prev approach

*Naive Way*.

**Important** Input should start with 0 to work correctly (in some cases)

```
o *A+UóÈÄ¦Y©Y>XÃl>2 ®ä- xÃxp

```

Try it online! or Test it all

# Answer
> 2 votes
# JavaScript (ES7), 72 bytes

```
a=>a.map(v=>(v-p>1?r=c++?r:p:t+=(c>1)*(c=0,p-r)**2,p=v),t=c=p=0)&&t+p*10

```

Try it online!

### Commented

```
a =>                  // a[] = input array
  a.map(v => (        // for each value v in a[]:
      v - p > 1 ?     //   if the difference with the previous floor is greater than 1:
        r = c++ ?     //     increment the combo counter c; if c was not equal to 0:
          r           //       leave r unchanged
        :             //     else:
          p           //       set r (reference floor) to the previous floor p
      :               //   else:
        t +=          //     update t only ...
          (c > 1) * ( //     ... if we have a multi-floor jump combo of at least 2 jumps
            c = 0,    //     reset c to 0
            p - r     //     compute the total number of floors jumped in the combo
          ) ** 2,     //     square it and add it to t
      p = v           //   set the previous value p to v
    ),                //
    t = c = p = 0     //   start with t = c = p = 0
  ) &&                // end of map()
  t + p * 10          // add the final floor multiplied by 10 to t

```

# Answer
> 2 votes
# J, 54 bytes

```
[:((10*{:)+1#.[:}:]((2<#)*[:*:{:-{.);.1~1,2>2-~/\])0&,

```

Try it online!

May add explanation later. For now here's an ungolfed and a parsed version:

### ungolfed

```
[: ((10 * {:) + 1 #. [: }: ] ((2 < #) * [: *: {: - {.);.1~ 1 , 2 > 2 -~/\ ]) 0&,

```

### parsed

```
┌──┬─────────────────────────────────────────────────────────────────────────────────────────────────────────┬───────┐
│[:│┌─────────┬─┬───────────────────────────────────────────────────────────────────────────────────────────┐│┌─┬─┬─┐│
│  ││┌──┬─┬──┐│+│┌─┬──┬────────────────────────────────────────────────────────────────────────────────────┐│││0│&│,││
│  │││10│*│{:││ ││1│#.│┌──┬──┬────────────────────────────────────────────────────────────────────────────┐│││└─┴─┴─┘│
│  ││└──┴─┴──┘│ ││ │  ││[:│}:│┌─┬────────────────────────────────────────┬───────────────────────────────┐││││       │
│  ││         │ ││ │  ││  │  ││]│┌────────────────────────────────────┬─┐│┌─┬─┬─────────────────────────┐│││││       │
│  ││         │ ││ │  ││  │  ││ ││┌─────────────────────────────┬──┬─┐│~│││1│,│┌─┬─┬───────────────────┐││││││       │
│  ││         │ ││ │  ││  │  ││ │││┌───────┬─┬─────────────────┐│;.│1││ │││ │ ││2│>│┌─┬─────────────┬─┐│││││││       │
│  ││         │ ││ │  ││  │  ││ ││││┌─┬─┬─┐│*│┌──┬──┬─────────┐││  │ ││ │││ │ ││ │ ││2│┌─────────┬─┐│]││││││││       │
│  ││         │ ││ │  ││  │  ││ │││││2│<│#││ ││[:│*:│┌──┬─┬──┐│││  │ ││ │││ │ ││ │ ││ ││┌─────┬─┐│\││ ││││││││       │
│  ││         │ ││ │  ││  │  ││ ││││└─┴─┴─┘│ ││  │  ││{:│-│{.││││  │ ││ │││ │ ││ │ ││ │││┌─┬─┐│/││ ││ ││││││││       │
│  ││         │ ││ │  ││  │  ││ ││││       │ ││  │  │└──┴─┴──┘│││  │ ││ │││ │ ││ │ ││ ││││-│~││ ││ ││ ││││││││       │
│  ││         │ ││ │  ││  │  ││ ││││       │ │└──┴──┴─────────┘││  │ ││ │││ │ ││ │ ││ │││└─┴─┘│ ││ ││ ││││││││       │
│  ││         │ ││ │  ││  │  ││ │││└───────┴─┴─────────────────┘│  │ ││ │││ │ ││ │ ││ ││└─────┴─┘│ ││ ││││││││       │
│  ││         │ ││ │  ││  │  ││ ││└─────────────────────────────┴──┴─┘│ │││ │ ││ │ ││ │└─────────┴─┘│ ││││││││       │
│  ││         │ ││ │  ││  │  ││ │└────────────────────────────────────┴─┘││ │ ││ │ │└─┴─────────────┴─┘│││││││       │
│  ││         │ ││ │  ││  │  ││ │                                        ││ │ │└─┴─┴───────────────────┘││││││       │
│  ││         │ ││ │  ││  │  ││ │                                        │└─┴─┴─────────────────────────┘│││││       │
│  ││         │ ││ │  ││  │  │└─┴────────────────────────────────────────┴───────────────────────────────┘││││       │
│  ││         │ ││ │  │└──┴──┴────────────────────────────────────────────────────────────────────────────┘│││       │
│  ││         │ │└─┴──┴────────────────────────────────────────────────────────────────────────────────────┘││       │
│  │└─────────┴─┴───────────────────────────────────────────────────────────────────────────────────────────┘│       │
└──┴─────────────────────────────────────────────────────────────────────────────────────────────────────────┴───────┘

```

# Answer
> 1 votes
# C++, ~~202~~ ~~190~~ ~~188~~ ~~187~~ ~~184~~ ~~181~~ ~~177~~ ~~170~~ ~~166~~ 164 bytes

```
int f(int*a,int l){int r=a[l-1]*10,i=0,j,k,s;for(;i<l;i++)for(j=l;s=j-->i;s&&j-i>1&&~j+l?r+=(a[i]-a[j])*(a[i]-a[i=j]),j=l:0)for(k=j;k-i;)s*=a[k--]-a[k]>1;return r;}

```

Try it online!

Input must begin with 0.

-11 bytes thanks to @ceilingcat

---
Tags: code-golf
---


# Question
Title: Convert to and from the backwards-factorial number base
I wanted to ask this question: Convert to and from the factorial number system but I'm a couple of years too late!

So, instead you must convert to and from the ~~lairotcaf~~ backwards-factorial number base! The way it works is that the first digit is always `0`, the maximum value of the next digit is `1`, then `2` and so on. If a number has *n* digits, then each place value is given by *n*!/*i*! where *i* is the digit position starting at `1` on the **left**. The highest digit position is on the **right**. This means that each length uses different place values!

There is a unique shortest way to represent each number, which is what you must output for a decimal number input. If an input number starts with a `0`, convert it to decimal. If it starts with any other digit, convert it to the backwards-factorial number base.

`0` is both valid and the same number in both bases. In the test data no input value will use, or produce a number with a digit higher than `9`. Note that the shortest representation of some numbers starts with multiple `0`s.

```
Digit position:   1   2   3   4   5   6
Place value:    720 360 120  30   6   1
                  0   0   2   2   3   3
                  0   0 240+ 60+ 18+  3=321

```

This is the shortest way to represent `321` because removing a digit makes the highest number possible only `119` (5! - 1).

Test data:

```
Input:      Output:
0           0
1           01
002         2
3           010
011         4
5           012
0012        6
21          0121
0130        24
01000       60
01234       119
001000      120
321         002233
011235      563
0010330     987
4321        0120252
54321       000325536
654321      0010135621
0112351713  2838883
7654321     00102603574

```

This is so the fewest bytes wins!

# Answer
> 1 votes
## ES6, ~~135~~ 108 bytes

```
s=>s<"1"?[...s].reduce((t,d,i)=>+d+t*++i):eval("for(i=j=k=1;i<=s;i*=++j);for(r='';k<=j;k++)r+=s%i/(i/=k)|0")

```

Converting from backwards-factorial is nice and easy. Converting to it... not so nice. I found a 119-byte version that doesn't use `eval`:

```
s=>s<"1"?[...s].reduce((t,d,i)=>+d+t*++i):(i=j=k=1,g=_=>s<i||g(i*=++j),g(),[...Array(j)].map(_=>s%i/(i/=k++)|0).join``)

```

# Answer
> 0 votes
# Perl 6, 71 bytes

```
{{/^0/??.comb.reduce(* *-+^++$+*)!![R~] .polymod(+.polymod(1..*)...2)}}

```

Try it online!

# Answer
> 0 votes
# Jelly, 36 bytes

```
⁵R!>³¬TUŻ‘PƤµ³%Ḋ:ṖUŻṾ€
Jṙ1PÐƤḋV€µÇ¬?

```

Try it online!

### How it works

```
⁵R!>³¬TUŻ‘PƤµ³%Ḋ:ṖUŻṾ€  Aux. link (monad). Integer -> string
⁵R!           [1..10]!
   >³¬T       All indices of above <= input
       UŻ‘    Reverse, prepend 0, increment
          PƤ  Product of each prefix
            µ           Re-focus on the above
             ³%Ḋ:Ṗ      Input % (next base value) // (own base value)
                  UŻṾ€  Reverse, prepend zero, map each digit to string

Jṙ1PÐƤḋV€µÇ¬?  Main link (monad). String -> integer || Integer -> string
         µÇ¬?  If input is string, apply the link on the left;
               otherwise, apply the aux. link
Jṙ1        List of indices rotated once to the left
   PÐƤ     Product of each suffix
      ḋV€  Convert each input char to digit, and dot product with above

```

Uses some tricks from my own Jelly answer for factorial base challenge.

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


title: Alignment of a string

text:
# Question
Title: Alignment of a string
This is similar to the alignment used in word.

### Task

3 inputs: A 1 line string, a positive integer `k`, and direction (left or middle or right)

Your job is to insert new lines(`\n`) and spaces in the string such that every line has `k` characters in it and aligned to the direction given.

### Rules

The words must not be split(unless their length is greater than `k`)

Direction can be taken as any 3 unique characters(must be mentioned).

Any format and order of input is valid(must be mentioned).

Input will only have alphabetical characters of any case(and spaces).

There will not be any trailing or leading spaces in the input and will have only 1 space between words.

Output can be either a string on one line as is in examples or multiple lines.

**If the direction is left:**

There should not be any spaces in left of the line and only 1 space between words.

**If the direction is right:**

There cannot be any spaces to the right of the line and only 1 space between words.

**If the direction is middle:**

There cannot be any spaces to the left or right of a line and an equal number of spaces between words on one line. In case the word length is shorter than `k` and only 1 word can fit in 1 line, then spaces on the right is allowed. If more than 2 words can fit in one line but they cannot be divided keeping number of spaces equal, words will shift to next line to keep number of spaces equal.

### Test Cases

```
input: 'Hello World',6,right
output: ' Hello\n World'

input: 'Hello World',7,left
output: 'Hello  \nWorld  '

input: 'Hello World',7,middle
output: 'Hello  \nWorld  '

input: 'This is a test case',5,middle
output: 'This \nis  a\ntest \ncase '

input: 'This is a test case',5,left
output: 'This \nis a \ntest \ncase '

input: 'For example',1,left
output: 'F\no\nr\ne\nx\na\nm\np\nl\ne' #The space is removed as the next word is in a newline.

input: 'Hello Worlds How are you',5,left
output: 'Hello\nWorld\ns How\nare  \nyou  '

input: 'qwert asdfghjkl zxcvbnm',7,middle
output: 'qwert  \nasdfghj\nkl      \nzxcvbnm'

input: 'ab abcdefg',6,middle
output: 'ab    \nabcdef\ng     '

input: 'This is code golf so shortest code wins',10,middle
output: 'This    is\ncode  golf\nso        \nshortest  \ncode  wins'

input: 'Credit to Jo for this case',13,middle
output: 'Credit     to\nJo  for  this\ncase         '

```

**This is code-golf so shortest code wins**

# Answer
# Perl 6, ~~195 186 177~~ 132 bytes

*-41 bytes thanks to nwellnhof!*

```
{->\b,\c{$!={!c*(b-$0.comb)/($0-1||1)+1};S:g{[(\S+)[\s|$]<?{b>=$0.ords&&.$!%%1}>]+|(\S**{b})}=$0.join(' 'x.$!).fmt("%{b*c||-b}s
")}}

```

Try it online!

Anonymous code block that takes input curried, e.g. `f('text')(length, direction)`. Uses the values `-1,0,1` as left, middle and right respectively.
> 3 votes

# Answer
# Python 2, ~~245~~ ~~243~~ ~~237~~ ~~225~~ 221 bytes

```
import re
s,k,d=input()
s=filter(bool,re.split('(\w{%d})| '%k,s))
while s:l,s=max((j,s[i:])for i in range(len(s)+1)for x in range(d&1or k)for j in[(-~x*' ').join(s[:i])]if[k,0][d|(i<2)]<=len(j)<=k);print'%*s'%(-(d|1)*k,l)

```

Try it online!

Takes `left, middle, right` as `1,0,-1`
> 2 votes

---
Tags: code-golf, typography
---


title: Outline words with their letters

text:
# Question
Title: Outline words with their letters
For the purposes of the current challenge to "outline" a word means to surround it successively with its own letters, starting with the last one, and finally to replace the original word in the center with spaces:

```
       oooooo
       onnnno
on ->  on  no
       onnnno
       oooooo

```

## Task:

Given a list of words, consisting only of lowercase and/or uppercase English letters, outline each word and display all the resulting blocks next to each other horizontally, separated by a column of single space, vertically aligned at the centers of the blocks.

You can write a full program, or a function.

## Input:

A list of words, or if you prefer - a space- or other symbol- delimited string

## Output:

The ASCII representation of the blocks for the outlined words. Leading/trailing whitespaces are permitted.

## Test cases:

```
Input 1: ["code", "golf"] (or "code golf")
Output 1:

    cccccccccccc gggggggggggg
    cooooooooooc goooooooooog
    coddddddddoc gollllllllog
    codeeeeeedoc golfffffflog
    code    edoc golf    flog
    codeeeeeedoc golfffffflog
    coddddddddoc gollllllllog
    cooooooooooc goooooooooog
    cccccccccccc gggggggggggg

Input 2: ["I", "am", "just", "a", "man"]  (or "I am just a man")
Output 2:

           jjjjjjjjjjjj
           juuuuuuuuuuj     mmmmmmmmm
    aaaaaa jussssssssuj     maaaaaaam
III ammmma justtttttsuj aaa mannnnnam
I I am  ma just    tsuj a a man   nam
III ammmma justtttttsuj aaa mannnnnam
    aaaaaa jussssssssuj     maaaaaaam
           juuuuuuuuuuj     mmmmmmmmm
           jjjjjjjjjjjj

```

## Winning criteria:

The shortest code in bytes in each language wins. I will greatly appreciate if you comment/explain your code and approach.

# Answer
> 7 votes
# Canvas, ~~22~~ 20 bytes

```
ｌ ＊；±２１＊｛；ｌ└＊ｅ⟳｝ ］ｒ⤢

```

Try it here!

Explanation:

```
{                 ]    map over the inputs
 l *                     array of length spaces - the canvas of the current word
    ;                    get the word back on top
     ±                   reverse it
      21*                repeat each character twice
         {      }        for each character
          ;l└              push the height of the item below (the canvas)
             *             repeat the character that many times vertically
              e            and encase the canvas in that char column
               ⟳           and rotate it clockwise for encasing the next time
                 ∙      push another space as the separator of words
                   r   center the words
                    ⤢  and transpose the final output (as everything was built vertically)

```

# Answer
> 5 votes
# Charcoal, 35 bytes

```
ＦＡ«≔ＬιθＭθ↑Ｆθ«Ｂ⁻×³θ⊗κ⊕⊗⁻θκ§ικ↘»Ｍ⊕⊗θ→

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＡ«

```

Loop over the input list.

```
≔Ｌιθ

```

Get the length of the current word.

```
Ｍθ↑

```

Move to the top left corner of the resulting outline.

```
Ｆθ«

```

Loop once for each character.

```
Ｂ⁻×³θ⊗κ⊕⊗⁻θκ§ικ

```

Draw a box of the appropriate height, width and character.

```
↘»

```

Move to the top left corner of the next box.

```
Ｍ⊕⊗θ→

```

Move to the next outline.

# Answer
> 4 votes
# Haskell, <sup>~~188~~ ~~183~~ ~~174~~ ~~171~~</sup> 167 bytes

~~-9~~ -13 bytes thanks to Laikoni.

```
e=[]:e
c#a=k c<$>k(c<$a!!0)a
k c s=c:s++[c]
f w=foldr(#)[p w]w
p=(' '<$)
s w=unlines.map unwords.foldr(zipWith(:))e$until(\a->all((p a>=).p)$f<$>w)(k=<<p.head)<$>f<$>w

```

Try it online!

# Answer
> 3 votes
# Pyth, ~~34~~ 33 bytes

```
Jsm+;uCjR*2HG_.iddm\ dQjCm.[lJd;J

```

Try it online.

Dumps out a whole bunch of extra whitespace, but that's allowed by the challenge.

### Explanation

* `m``Q` does the following for each word `d` in the input `Q`:

+ `m\ d` maps the word with `x => " "`, essentially creating the list `[" ", ..., " "]` with as many items as the word has letters.
    + `.idd` interleaves the word with itself, repeating the word's letters twice. `_` reverses this string. `word` becomes `ddrrooww`.
    + `u` starts with `G` = the array of spaces, and applies the following with each letter in the interleaved string in `H`:
        - `*2H` repeats the character twice.
        - `jR``G` puts each string in `G` between the pair of characters.
        - `C` swaps rows and columns. When these three steps are done twice with the same character in `H`, this outlines the lines in `G` with that character.
    + We now have the columns for the outlined word `d`. `+;` prepends a space column.
* `s` flattens the array of columns for each word, and `J` saves it in the variable `J`.
* `m``J` does the following for each column of the output:
    + `.[lJd;` pads both sides of the column with spaces so that the length of the column is equal to the number of columns. This is always sufficient padding to make the columns align vertically.
* `C` turns the columns to rows and `j` joins the rows with newlines.

### Alternative solution, 33 bytes

```
j.tsm.[L\ l+dsQ+;uCjR*2HG_.iddm\

```

Try it online.

Note that there is a trailing space. Mostly the same algorithm, except only pads columns on the top and then transposes with space fill.

# Answer
> 3 votes
# , 189 bytes

```
function(x,S=32,`+`=rbind,`*`=cbind)cat(intToUtf8(Reduce(`+`,Map(function(s,K=utf8ToInt(s),o=S-!K){for(i in rev(K))o=i+i*o*i+i
for(j in(0:(max(nchar(x))-nchar(s)))[-1])o=S*o*S
o+S},x))+10))

```

Try it online!

A collaboration between digEmAll and myself in chat.

```
function(x){
 S <- 32			# space
 `+` <- rbind			# alias for rbind
 `*` <- cbind			# alias for cbind
 outlineWord <- function(s){	# function to construct the outline for each word
  chars <- utf8ToInt(s)		# convert to code points
  output <- S - !chars		# replace each char with 32 (space)
  for(i in rev(chars))
   o <- i + i * o * i + i	# o <- rbind(i,cbind(i,o,i),i)
  for(j in(0:(max(nchar(x))-nchar(s)))[-1])
   o <- S * o * S		# pad with spaces
   o + S}			# return with an additional row of spaces between words
 outlines <- Map(outlineWord,x)	# apply outlineWord to each element of x
 outlines <- Reduce(`+`,outlines)# reduce by rbind
 outlines <- outlines+10	# add row of newlines
 cat(intToUtf8(outlines))	# convert back to strings and print
}

```

# Answer
> 1 votes
# APL (Dyalog Classic), ~~57~~ ~~51~~ 50 bytes

```
{⍉⊃⍪/,/((⊢-⌈/)≢¨⍵)⌽↑{⍪¨↓0 1↓⍕,∘⍉∘⌽⍣4/⍵,⊂⍉⍪¯1/⍵}¨⍵}

```

Try it online!

# Answer
> 1 votes
# Stax, ~~26~~ 25 bytes

```
¢π‼○MªΘ└ƒ∩┘?◙↕)fY╨nu⌂E┴6X

```

Run and debug it

# Answer
> 1 votes
# 05AB1E, 46 bytes

```
εg©;ò<Uyηε¤®∍«®>∍}yð«©ª®Xиª˜».º.∊}¶«».C.B€SζJ»

```

Not too happy about it, but I'm glad it's working.

Try it online or verify all test cases.

**Explanation:**

```
ε                             # Map `y` over the (implicit) input-list
 g                            #  Take the length of the current item
  ©                           #  Store it in the register (without popping)
   ;                          #  Halve it
    ò                         #  Ceil and cast to integer at the same time
     <                        #  Decrease it by 1
      U                       #  Pop and store it in variable `X`
 yη                           #  Take the prefixes of the current string `y`
   ε       }                  #  Map over these prefixes:
    ¤                         #   Take the last character of the string
     ®×                       #   Increase it to a size equal to the length from the register
       «                      #   Append it to the current prefix
        ®>                    #   Take the length from the register, and add 1
          ∍                   #   Shorten the string to that size
 y                            #  Push the string `y` again
  ð«                          #  Append a space
    ©                         #  Store it in the register (without popping)
     ª                        #  Append it at the end of the list of modified prefixes
      ®                       #  Push the string with space from the register again
       Xи                     #  Repeat it `X` amount of times
         ª                    #  Append them to the list
          ˜                   #  Flatten to remove the empty appended list if `X` was 0
           »                  #  Join by newlines
            .º.∊              #  Intersect mirror both horizontally and vertically
                }             # Close outer map
                 ¶«           # Append a newline after each (for the space delimiters)
                   »          # Join everything by newlines
                    .C        # Centralize it horizontally
                              # (too bad a centralize vertically isn't available..)
                      .B      # Split on newlines again
                        €S    # Convert each line to a list of characters
                          ζ   # Zip, swapping rows/columns (with space filler by default)
                           J  # Join the loose characters of every line to a string again
                            » # Join the lines by newlines (and output implicitly)

```

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


title: FreeChat Online

text:
# Question
Title: FreeChat Online
## FreeChat Online

It is 1985, and you are a humble Russian potato farmer. Sadly, your glorious homeland is going through a time of crisis and it needs **your** help! The KGB, with the "assistance" of your wife and children, has convinced you to build their up-and-coming government *FreeChat Online* service for high ranking soviet officials. Luckily, the Russian government has provided you with several items seized through routine surveillance of the US's technological innovations—a cutting edge Macintosh XL, and the prototype source code for LucasArts's *Habitat*, an advanced communication service with cutting edge graphics. Your task is simple: create a few modifications for the Russian government…

Due to Communism's tendency to coalesce toward collectivistic cultures, the Russian government wants this chat to embody their perfect world—one without silly notions of self or individualism. Alas, Macintosh compatibility leads you astray. Due to problems in the prototype, every other sentence in the chat buffer is corrupted, except for the ending period. Lucky for you, the Russian people make classification easy for you.

**CHALLENGE**: For a String `s` in the input, there are 1 or more sentences, separated by `". "`(period, TWO spaces) The 2nd, 4th, 6th, and so on sentences are corrupted. The last sentence may have nothing, `"."`, `". "`, or `". "` as its end. Here's some examples of an input:

`"L'etat c'est moi (I am the state) - King Louis XIV"`

|----------------one sentence, ended by nothing--------------|

`"Hello World. GojdGojog. How are you. "`

|--three sentences, one corrupted, ended by `". "`--|

`"Hi. gfhyG. My favorite food is Baseball. jijhojh. Foobar. "`

|---------------Five sentences, two corrupted, ended by `". "`-----------|

You must process this string, replacing any capitalized word besides the first word of a sentence, words in parentheses *(no nested, but there can be multiple sets in a sentence)*, or corrupted sentences with the string `"The State"`.

**Examples**:

`"L'etat c'est moi (I am the state) - King Louis XIV"`

---\>`"L'etat c'est moi (I am the state) - The State The State The State"`

`"Hello World. GojdGojog. How are you. "`

---\>`"Hello The State. GojdGojog. How are you. "`

`"Hi. gfhyG. My favorite food is Baseball. jijhojh. Foobar. "`

---\>`"Hi. gfhyG. My favorite food is The State. jijhojh. Foobar. "`

**Rules**:

1. Standard Loopholes are prohibited
2. ASCII Text Input
3. If the input doesn't match the specifications set above, do whatever you please with the output!
4. This is code-golf, so the shortest(valid)answer (in each language) wins!
5. Bonus points for a one-liner (Not really tho, just cool points)

# Answer
> 4 votes
# Retina 0.8.2, 77 bytes

```
(?<=^(([^.]*)\. +([^.]*)\. +)*[^ .][^.]*)(?<!\([^)]*)[A-Z][A-Za-z]*
The State

```

Try it online! Link includes test cases. Explanation:

```
(?<=^(([^.]*)\. +([^.]*)\. +)*[^ .][^.]*)

```

Only match in the middle of alternate sentences.

```
(?<!\([^)]*)

```

Don't match inside parentheses.

```
[A-Z][A-Za-z]*

```

Match words beginning with uppercase letters.

```
The State

```

Replace them as desired.

# Answer
> 3 votes
# Java 10, 164 bytes

```
s->{var S=s.split(".  ",-1);for(int l=S.length,i=0;i<l;)System.out.print((i%2<1?S[i].replaceAll("(?!^)[A-Z]\\w*(?<!\\([^)]*)","The State"):S[i])+(++i<l?".  ":""));}

```

Try it online.

**Explanation:**

```
s->{                       // Method with String as both parameter and return-type
  var S=s.split(".  ",-1); //  Split the input by ".  " to get the list of sentences
                           //  (the -1 is in case the input ends in a trailing ".  ")
  for(int l=S.length,      //  Amount of sentences
      i=0;i<l;)            //  Loop `i` in the range [0, amount_of_sentences):
    System.out.print(      //   Print (without newline):
     (i%2<1?               //    If `i` is even:
       S[i]                //     Print the sentence,
        .replaceAll(       //      After we've replaced all
          "(?!^)           //       (except the very first)
           [A-Z]\\w*       //       capitalized words,
           (?<!\\([^)]*)"  //       that are not within parenthesis
          "The State")     //      With "The State"
      :                    //    Else:
       S[i])               //     Print the sentence as is
            +(++i<l?       //    And if it's not the last iteration:
               ".  "       //     Append ".  "
              :            //    Else:
               ""));}      //     Append nothing more

```

# Answer
> 2 votes
# Perl 6, 91 bytes

```
{S:g/\s<:Lu><-[.\s]>+<?{!grep {$/.prematch.comb($_)%2},'.  ',/\(|\)/,/\.\s$/}>/ The State/}

```

Try it online!

Regex based solution.

### Explanation:

```
 S:g/                  # Do a global substitution
     \s<:Lu><-[.\s]>+  # On all words starting with capital letters
               <?{                                        }>  # Where:
                  !grep {                       } # None of:
                                                 ,'.  '   # Sentence terminators
                                                 ,/\(|\)/ # Parenthesises
                                                 ,/\.\s$/ # Is first word of sentence?
                                    .comb($_)%2   # Have an odd amount of matches
                         $/.prematch              # From the string before
                                                           / The State/  # And replace

```

---
Tags: code-golf, regular-expression
---


title: Cut-Off The Matrix

text:
# Question
Title: Cut-Off The Matrix
### Task

Given is a square matrix of any dimension and any integer `n`.

Output all possible matrices(without duplicates) by removing columns and rows from the input matrix such that the determinant of these new matrices is `n`.

### Rules

Output should include original if determinant of original is `n`.

Output should be all the chopped off matrices. In case no output matrix is possible, return 0 or None or anything similar.

The input matrix will be at least of size 2x2 and all elements will be integers.

If `n=1` empty matrix must also be in the output.

### Test Cases

```
inputs:
[[1,0,5],
[1,0,5],
[1,2,4]],2

[[1, 3, 5],
[1, 3, 5],
[1, 45, 4]],0

[[1, 22, 5, 4],
[1, 3, 5, 5],
[1, 45, 4, 6],
[3, 4, 1, 4]],5

[[1, 22, 5, 4],
[1, -32, 51, 5],
[1, 45, 9, 0],
[3, 4, -1, -6]],-54

[[1, 22, 5, 4],
[1, -32, 51, 5],
[1, 45, 9, 0],
[3, 4, -1, -6]],1

outputs:
[[[2]], [[1, 0], [1, 2]]]

[[[1, 3], [1, 3]], [[1, 5], [1, 5]], [[3, 5], [3, 5]], [[1, 3, 5], [1, 3, 5], [1, 45, 4]]]

[[[5]], [[5, 4], [5, 5]]]

[[[1, 22], [1, -32]], [[9, 0], [-1, -6]]]

[[], [[1]], [[1, 4], [1, 5]]]

```

**The shortest code wins.**

# Answer
> 5 votes
# Jelly, ~~20~~ 16 bytes

```
ZŒPZœcLƊ€ẎQÆḊ⁼¥Ƈ

```

Try it online!

Challenge finished. Unfortunately, my brain wasn't in its best mood, so Dennis pushed it until I finally managed to get here (you can see how it went). ~1 hour.

# Answer
> 4 votes
# JavaScript (ES6), ~~246~~ ~~238~~ ~~196~~ 192 bytes

*Credits: the function \\$D\\$ is derived from this answer by edc65.*

Takes input as `(integer)(matrix)`. Prints the results to the console.

```
d=>g=m=>(F=(a,i)=>a.filter(_=>i--),m.map((_,i)=>m.map((_,j)=>g(F(m,i).map(r=>F(r,j))))),D=m=>m+m?m.reduce((n,[r],i)=>n+(i&1?-r:r)*D(F(m,i).map(r=>F(r,0))),0):1)(m)-d||g[m]||console.log(g[m]=m)

```

Try it online!

## How?

### Removing rows and columns

The helper function \\$F\\$ creates a copy of a given array \\$a\\$ with the \\$i^\text{th}\\$ item removed (0-indexed).

```
F = (a, i) => a.filter(_ => i--)

```

### Computing the determinant

The recursive function \\$D\\$ computes the determinant of a matrix \\$m\\$, using Laplace expansion.

```
D = m =>                       // m = matrix
  m + m ?                      // if the matrix is not empty:
    m.reduce((n, [r], i) =>    //   for each value r at (0, i):
      n                        //     take the previous sum n
      + (i & 1 ? -r : r)       //     using the parity of i, either add or subtract r
      * D(                     //     multiplied by the result of a recursive call:
        F(m, i)                //       using m with the i-th row removed
        .map(r => F(r, 0))     //       and the first column removed
      ),                       //     end of recursive call
      0                        //     start with n = 0
    )                          //   end of reduce()
  :                            // else (the matrix is empty):
    1                          //   determinant = 1

```

*Example:*

$$m=\begin{bmatrix}\color{red}1&\color{red}2&\color{red}3\\\color{green}4&\color{green}5&\color{green}6\\\color{blue}7&\color{blue}8&\color{blue}9\end{bmatrix}$$

First iteration:

$$|m|= \color{red}1\times\left|\begin{bmatrix}\color{green}5&\color{green}6\\\color{blue}8&\color{blue}9\end{bmatrix}\right| -\color{green}4\times\left|\begin{bmatrix}\color{red}2&\color{red}3\\\color{blue}8&\color{blue}9\end{bmatrix}\right| +\color{blue}7\times\left|\begin{bmatrix}\color{red}2&\color{red}3\\\color{green}5&\color{green}6\end{bmatrix}\right|$$

which eventually leads to:

$$1\times(5\times9-8\times6)-4\times(2\times9-8\times3)+7\times(2\times6-5\times3) = 0$$

### Main function

We recursively remove rows and columns from the original matrix \\$m\\$ and invoke \\$D\\$ on all resulting matrices, printing those whose determinant is equal to the expected value \\$d\\$.

```
d =>                           // d = expected determinant value
  g = m =>                     // g = recursive function taking the matrix m,
    (                          //     also used to store valid matrices
      m.map((_, i) =>          // for each i in [0 ... m.length - 1]:
        m.map((_, j) =>        //   for each j in [0 ... m.length - 1]:
          g(                   //     do a recursive call with:
            F(m, i)            //       the i-th row of m removed
            .map(r => F(r, j)) //       the j-th column of m removed
          )                    //     end of recursive call
        )                      //   end of inner map()
      ),                       // end of outer map()
      D                        // invoke D ...
    )(m)                       // ... on m
    - d                        // provided that the result is equal to d
    || g[m]                    // and provided that this matrix was not already printed,
    || console.log(g[m] = m)   // print m and store it in the underlying object of g

```

# Answer
> 2 votes
# , 129 bytes

```
f=function(m,n,o={},z=nrow(m)){for(i in r<-1:z)for(j in r)o=c(o,if(round(det(m))==n)list(m),if(z)f(m[-i,-j,drop=F],n));unique(o)}

```

Try it online!

Recursive function returning a list of submatrices. Outputs `NULL` for no solution. It is a bit unfortunate that the determinant value has to be explicitly rounded (otherwise some tests fail due to numerical imprecision), but at least we have a built-in for calculating it.

---
Tags: code-golf
---


title: Is this a Major Scale (or equivalent)?

text:
# Question
Title: Is this a Major Scale (or equivalent)?
Sandbox

The major scale (or Ionian scale) is one of the most commonly used musical scales, especially in Western music. It is one of the diatonic scales. Like many musical scales, it is made up of seven notes: the eighth duplicates the first at double its frequency so that it is called a higher octave of the same note.

The seven musical notes are:

> **C, D, E, F, G, A, B**, C (repeated for example purposes)

A major scale is a diatonic scale. Take the previous succession of notes as a major scale *(Actually, It is the scale C Major)*. The sequence of intervals between the notes of a major scale is:

> whole, whole, half, whole, whole, whole, half

where "whole" stands for a whole tone (a red u-shaped curve in the figure), and "half" stands for a semitone (a red broken line in the figure).

In this case, from C to D exist a **whole** tone, from D to E exist a **whole** tone, from E to F exist **half** tone, etc...

We have 2 components that affects the tone distance between notes. These are the Sharp symbol (♯) and the flat symbol (♭).

The Sharp symbol (♯) adds half tone to the note. Example. From C to D we mentioned that exists a whole tone, if we use C♯ instead C then from C♯ to D exists half tone.

The Flat symbol (♭) do the opposite of the Sharp symbol, it subtract half tone from the note. Example: From D to E we mentioned that exists a whole tone, if we use Db instead D then from Db to E exists a tone and a half.

By default, from Note to Note exist a whole tone except for `E to F` and `B to C` in where just half tone exists.

**Note** in some cases using enharmonic pitches can create an equivalent to a Major Scale. An example of this is `C#, D#, E#, F#, G#, A#, B#, C#` where `E#` and `B#` are enharmonic but the scale follows the sequence of a Major Scale.

---

## Challenge

Given a scale, output a truthy value if it is a Major Scale or equivalent, otherwise output a falsey value.

**Rules**

* Standard I/O method allowed
* Standard rules apply
* You don't need to take in consideration the 8th note. Assume the input will only consist of 7 notes
* Assume double flat (♭♭), double sharp (♯♯) or natural sign (♮) don't exist

---

## Test cases

```
C, D, E, F, G, A, B                 => true
C#, D#, E#, F#, G#, A#, B#          => true
Db, Eb, F, Gb, Ab, Bb, C            => true
D, E, Gb, G, A, Cb, C#              => true
Eb, E#, G, G#, Bb, B#, D            => true
-----------------------------------------------
C, D#, E, F, G, A, B                => false
Db, Eb, F, Gb, Ab, B, C             => false
G#, E, F, A, B, D#, C               => false
C#, C#, E#, F#, G#, A#, B#          => false
Eb, E#, Gb, G#, Bb, B#, D           => false

```

# Answer
# Perl 6, ~~76~~ ~~65~~ ~~63~~ 59 bytes

*-4 bytes thanks to Phil H*

```
{221222==[~] (.skip Z-$_)X%12}o*>>.&{13*.ord+>3+?/\#/-?/b/}

```

Try it online!

### Explanation

```
*>>.&{ ... }  # Map notes to integers
  13*.ord     # 13 * ASCII code:  A=845 B=858 C=871 D=884 E=897 F=910 G=923
  +>3         # Right shift by 3: A=105 B=107 C=108 D=110 E=112 F=113 G=115
              # Subtracting 105 would yield A=0 B=2 C=3 D=5 E=7 F=8 G=10
              # but isn't necessary because we only need differences
  +?/\#/      # Add 1 for '#'
  -?/b/       # Subtract 1 for 'b'

{                           }o  # Compose with block
            (.skip Z-$_)        # Pairwise difference
                        X%12    # modulo 12
         [~]  # Join
 221222==     # Equals 221222

```
> 11 votes

# Answer
# Node.js v10.9.0, ~~78~~ ~~76~~ ~~71~~ 69 bytes

```
a=>!a.some(n=>(a-(a=~([x,y]=Buffer(n),x/.6)-~y%61)+48)%12-2+!i--,i=3)

```

Try it online!

### How?

Each note \\$n\\$ is converted to a negative number in \\$\[-118,-71\]\\$ with:

```
[x, y] = Buffer(n) // split n into two ASCII codes x and y
~(x / .6)          // base value, using the ASCII code of the 1st character
- ~y % 61          // +36 if the 2nd character is a '#' (ASCII code 35)
                   // +38 if the 2nd character is a 'b' (ASCII code 98)
                   // +1  if the 2nd character is undefined

```

Which gives:

```
  n   | x  | x / 0.6 | ~(x / 0.6) | -~y % 61 | sum
------+----+---------+------------+----------+------
 "Ab" | 65 | 108.333 |    -109    |    38    |  -71
 "A"  | 65 | 108.333 |    -109    |     1    | -108
 "A#" | 65 | 108.333 |    -109    |    36    |  -73
 "Bb" | 66 | 110.000 |    -111    |    38    |  -73
 "B"  | 66 | 110.000 |    -111    |     1    | -110
 "B#" | 66 | 110.000 |    -111    |    36    |  -75
 "Cb" | 67 | 111.667 |    -112    |    38    |  -74
 "C"  | 67 | 111.667 |    -112    |     1    | -111
 "C#" | 67 | 111.667 |    -112    |    36    |  -76
 "Db" | 68 | 113.333 |    -114    |    38    |  -76
 "D"  | 68 | 113.333 |    -114    |     1    | -113
 "D#" | 68 | 113.333 |    -114    |    36    |  -78
 "Eb" | 69 | 115.000 |    -116    |    38    |  -78
 "E"  | 69 | 115.000 |    -116    |     1    | -115
 "E#" | 69 | 115.000 |    -116    |    36    |  -80
 "Fb" | 70 | 116.667 |    -117    |    38    |  -79
 "F"  | 70 | 116.667 |    -117    |     1    | -116
 "F#" | 70 | 116.667 |    -117    |    36    |  -81
 "Gb" | 71 | 118.333 |    -119    |    38    |  -81
 "G"  | 71 | 118.333 |    -119    |     1    | -118
 "G#" | 71 | 118.333 |    -119    |    36    |  -83

```

We compute the pairwise differences modulo \\$12\\$ between these values.

The lowest possible difference between 2 notes is \\$-47\\$, so it's enough to add \\$4\times12=48\\$ before applying the modulo to make sure that we get a positive result.

Because we apply a modulo \\$12\\$, the offset produced by a `'#'` is actually \\$36 \bmod 12 = 0\\$ semitone, while the offset produced by a `'b'` is \\$38 \bmod 12 = 2\\$ semitones.

We are reusing the input variable \\$a\\$ to store the previous value, so the first iteration just generates \\$\text{NaN}\\$.

For a major scale, we should get \\$\[ \text{NaN}, 2, 2, 1, 2, 2, 2 \]\\$.

We use the counter \\$i\\$ to compare the 4th value with \\$1\\$ rather than \\$2\\$.
> 10 votes

# Answer
# JavaScript (Node.js), ~~150~~ ~~131~~ 125 bytes

```
l=>(l=l.map(x=>'C0D0EF0G0A0B'.search(x[0])+(x[1]=='#'|-(x[1]=='b')))).slice(1).map((n,i)=>(b=n-l[i])<0?2:b)+""=='2,2,1,2,2,2'

```

Try it online!

*-19 bytes thanks to Luis felipe*
*-6 bytes thanks to Shaggy*

## Ungolfed:

```
function isMajor(l) {
    // Get tone index of each entry
    let array = l.map(function (x) {
        // Use this to get indices of each note, using 0s as spacers for sharp keys
        let tones = 'C0D0EF0G0A0B';
        // Get the index of the letter component. EG D = 2, F = 5
        let tone = tones.search(x[0]);
        // Add 1 semitone if note is sharp
        // Use bool to number coercion to make this shorter
        tone += x[1] == '#' | -(x[1]=='b');
    });
    // Calculate deltas
    let deltas = array.slice(1).map(function (n,i) {
        // If delta is negative, replace it with 2
        // This accounts for octaves
        if (n - array[i] < 0) return 2;
        // Otherwise return the delta
        return n - array[i];
    });
    // Pseudo array-comparison
    return deltas+"" == '2,2,1,2,2,2';
}

```
> 4 votes

# Answer
# Dart, ~~198 197 196~~ 189 bytes

```
f(l){var i=0,j='',k,n=l.map((m){k=m.runes.first*2-130;k-=k>3?k>9?2:1:0;return m.length<2?k:m[1]=='#'?k+1:m[1]=='b'?k-1:k;}).toList();for(;++i<7;j+='${(n[i]-n[i-1])%12}');return'221222'==j;}

```

Try it online!

Loose port of the old Perl 6 answer https://codegolf.stackexchange.com/a/175522/64722

```
f(l){
  var i=0,j='',k,
  n=l.map((m){
    k=m.runes.first*2-130;
    k-=k>3?k>9?2:1:0;
    return m.length<2?k:m[1]=='#'?k+1:m[1]=='b'?k-1:k;
  }).toList();
  for(;++i<7;j+='${(n[i]-n[i-1])%12}');
  return'221222'==j;
}

```
* -1 byte by using ternary operators for #/b
* -1 byte by using ifs instead of ternaries for the scale shifts
* -7 bytes thanks to @Kevin Cruijssen

---

**Old version :**

# Dart, 210 bytes

```
f(l){var i=0,k=0,n={'C':0,'D':2,'E':4,'F':5,'G':7,'A':9,'B':11,'b':-1,'#':1},j='',y=[0,0];for(;++i<7;j+='${(y[0]-y[1])%12}')for(k=0;k<2;k++)y[k]=n[l[i-k][0]]+(l[i-k].length>1?n[l[i-k][1]]:0);return'221222'==j;}

```

Try it online!

Ungolfed:

```
f(l){
  var i=0,k=0,n={'C':0,'D':2,'E':4,'F':5,'G':7,'A':9,'B':11,'b':-1,'#':1},j='',y=[0,0];
  for(;++i<7;j+='${(y[0]-y[1])%12}')
    for(k=0;k<2;k++)
      y[k]=n[l[i-k][0]]+(l[i-k].length>1?n[l[i-k][1]]:0);

  return'221222'==j;
}

```

A whole step is 2, a quarter is 1. Mod 12 in case you jump to a higher octave. Iterates through all notes and computes the difference between the ith note and the i-1th note. Concatenates the result and should expect 221222 (2 whole, 1 half, 3 wholes).

* -2 bytes by not assigning 0 to k
* -4 bytes by using j as a String and not a List
* -6 bytes thanks to @Kevin Cruijssen by removing unnecessary clutter in loops
> 3 votes

# Answer
# C (gcc), `-DA=a[i]` \+ 183 = 191 bytes

```
f(int*a){char s[9],b[9],h=0,i=0,j=0,d;for(;A;A==35?b[i-h++-1]++:A^98?(b[i-h]=A*13>>3):b[i-h++-1]--,i++);for(;j<7;d=(b[j]-b[j-1])%12,d=d<0?d+12:d,s[j++-1]=d+48);a=!strcmp(s,"221222");}

```

Try it online!

Based on the Perl answer.

Takes input as a wide string.

Ungolfed:

```
int f(int *a){
	char s[9], b[9];
	int h, i, j;
	h = 0;
        for(i = 0; a[i] != NULL; i++){
		if(a[i] == '#'){
			b[i-h-1] += 1;
			h++;
		}
		else if(a[i] == 'b'){
			b[i-1-h] -= 1;
			h++;
		}
		else{
			b[i-h] = (a[i] * 13) >> 3;
		}
	}
	for(j = 1; j < 7; j++){
		int d = (b[j] - b[j-1]) % 12;
		d = d < 0? d + 12: d;
		s[j-1] = d + '0';
	}
	return strcmp(s, "221222") == 0;
}

```
> 2 votes

# Answer
# Python 3, ~~175~~ ~~136~~ ~~134~~ ~~114~~ 112 bytes

```
def f(t):r=[ord(x[0])//.6+ord(x[1:]or'"')%13-8for x in t];return[(y-x)%12for x,y in zip(r,r[1:])]==[2,2,1,2,2,2]

```

Try it online!

---

An one-liner Python 3 implementation.

Thanks to @Arnauld for idea of calculate tones using division and modulo.
Thanks to @Jo King for -39 bytes.
> 2 votes

# Answer
# \[Wolfram Language (Mathematica) + Music\` package\], 114 bytes

I love music and found this interesting, but I was out playing real golf when this code golf opportunity came down the pike so my submission is a little tardy.

I figured I'd try this a totally different way, utilizing some actual music knowledge. It turns out the music package of Mathematica knows the fundamental frequency of the named notes. First I convert the input string into sequence of named notes. Next, I take the ratios of each successive note and double any that are less than 2 (to account for octave shift). Then I compare these ratios to the ratios of the Ionian scale which has roughly a 6% frequency difference between half notes and 12% between full notes.

More than half of the bytes spent here are to convert the input into named symbols.

```
.06{2,2,1,2,2,2}+1==Round[Ratios[Symbol[#~~"0"]&/@StringReplace[# ,{"b"->"flat","#"->"sharp"}]]/.x_/;x<1->2x,.01]&

```

Try it online!
> 2 votes

# Answer
# \[Python\] ~~269~~ 202 bytes

Improvements from `Jo King`:

```
p=lambda z:"A BC D EF G".index(z[0])+"b #".index(z[1:]or' ')-1
def d(i,j):f=abs(p(i)-p(j));return min(f,12-f)
q=input().replace(' ','').split(',')
print([d(q[i],q[i+1])for i in range(6)]==[2,2,1,2,2,2])

```

Try it!

Ungolfed, with test driver:

```
tone = "A BC D EF G"   # tones in "piano" layout
adj = "b #"            # accidentals

def note_pos(note):
    if len(note) == 1:
        note += ' '
    n,a = note
    return tone.index(n) + adj[a]

def note_diff(i, j):
    x, y = note_pos(i), note_pos(j)
    diff = abs(x-y)
    return min(diff, 12-diff)

def is_scale(str):
    seq = str.replace(' ','').split(',')
    div = [note_diff(seq[i], seq[i+1]) for i in (0,1,2,3,4,5)]
    return div == [2,2,1,2,2,2]

case = [
("C, D, E, F, G, A, B", True),
("C#, D#, E#, F#, G#, A#, B#", True),
("Db, Eb, F, Gb, Ab, Bb, C", True),
("D, E, Gb, G, A, Cb, C#", True),
("Eb, E#, G, G#, Bb, B#, D", True),

("C, D#, E, F, G, A, B", False),
("Db, Eb, F, Gb, Ab, B, C", False),
("G#, E, F, A, B, D#, C", False),
("C#, C#, E#, F#, G#, A#, B#", False),
("Eb, E#, Gb, G#, Bb, B#, D", False),
]

for test, result in case:
    print(test + ' '*(30-len(test)), result, '\t',
          "valid" if is_scale(test) == result else "ERROR")

```
> 1 votes

# Answer
# Ruby, 109 bytes

```
->s{(0..11).any?{|t|s.map{|n|(w="Cef;DXg<E=Fhi>G j8A d9B:")[(w.index(""<<n.sum%107)/2-t)%12]}*''=='CfDX<=h'}}

```

Try it online!
> 1 votes

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


# Question
Title: Generate Hofstadter's Figure-Figure Sequence
In Gödel, Escher, Bach, Douglas Hofstadter introduces an integer sequence which is commonly referred to as the figure-figure sequence:

```
2, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, ...

```

You may enjoy working out the definition of the sequence yourself as part of the challenge, but if you can't or don't want to figure it out you can find it on OEIS as sequence A030124 and a slightly clearer definition on Wikipedia.

Write a program or function which, given `n` via STDIN, ARGV or function argument, prints a list of the first `n` numbers of the sequence to STDOUT in any reasonable list format.

This is code golf, the shortest solution in bytes wins.

# Answer
# CJam, ~~38~~ ~~30~~ ~~29~~ 21 bytes

```
li_3*,2>\{(_pX+:X-}*;

```

Try it online.

### How it works

```
li                     " Read an integer N from STDIN.              ";
  _3*,2>               " Push S := [ 2 3 ... (N * 3 - 1) ].         ";
        \{        }*   " Do the following N times:                  ";
          (            " Shift an integer I from S.                 ";
           _p          " Print a copy of I, followed by a linefeed. ";
             X+:X      " Execute X += I. (X is initialized to 1.)   ";
                 -     " Remove X from S.                           ";
                    ;  " Discard S from the stack.                  ";

```

### Example run

```
$ cjam <(echo 'li_3*,2>\{(_pX+:X-}*;') <<< 20
2
4
5
6
8
9
10
11
13
14
15
16
17
19
20
21
22
23
24
25

```
> 6 votes

# Answer
# Haskell, ~~67~~ ~~61~~ ~~60~~ ~~56~~ ~~55~~ 53 characters

```
g n=take n$2:4:h
a#(x:s)=[a..x-2]++x#s
h=5#scanl(+)8h

```

back to the first algorithm.

this solution computes the complement sequence by summing the starting elements of the sequence. it then computes the sequence as all the numbers between the complement's sequence numbers.

`(#)` is the function that calculates the numbers between the complement sequence.
`h` is the sequence itself.
`g` is the function that answers the question.

the g function is defined to just take the needed amount of elements from h.

subtleties:

`h` is actually the figure figure sequence except for the first 2 elements.
not the complement sequence is computed, but the complement sequence with added 1 for each element.
these two subtleties are the reason `scanl(+)8h` (which is the code for the complement sequence (except for the first 2 elements) with added 1's) has `8` in it. it is for the third element of the complement sequence with 1 added to it.
the reason the computation is not missing the first two elements is because they are added in `g` in `2:4:h`.

example:

```
>g 50
[2,4,5,6,8,9,10,11,13,14,15,16,17,19,20,21,22,23,24,25,27,28,29,30,31,32,33,34,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,57,58,59]

```
> 6 votes

# Answer
# Ruby, ~~54~~ 48

```
f=->n{x=1
b=*2..n*n
n.times{b-=[x+=p(b.shift)]}}

```

Demo

Edit: Golfed this a bit more once I realized I don't need to hold the full complement sequence in memory. Here's how it works now: We use `x` to keep track of the largest computed number in the complement sequence, and `b` is a pool of candidates for the sequence. `n` times, we output the smallest remaining element in `b` and add it to `x` to compute the next number in the complement sequence. Then we remove both numbers from the pool of candidates, so we're always outputting the smallest number that wasn't already added to either sequence.

Ruby golf tricks: Stabby lambda syntax is shorter than a method definition. The requirement that output is given to STDOUT instead of as return value inspired me to use the fact that the return value of `p(x)` is `x`, which I don't normally remember because it's not the case in the Ruby version used in Anarchy Golf.
> 5 votes

# Answer
## GolfScript (24 21 bytes)

```
~.3*,1>\{(\(.p@+\|}*;

```

Online demo

This started out quite differently, but ended up converging on a GolfScript port of histocrat's Ruby solution before Dennis made some suggestions which take it in a slightly different direction. In particular, printing the numbers as we identify them saves quite a bit over gathering them in an array for printing at the end; the reason is that it means that at no point do we have to worry about more than 3 items on the stack.

### Dissection

```
~.3*,           # Eval input n, dup, multiply by 3, make list [0 1 ... 3n-1]
1>              # Discard 0, which is part of neither sequence
\{              # Execute n times: stack contains pool of numbers not yet seen
                # in either sequence and the first element of it is the next element of the
                # complement sequence
  (\(           #   Pop two numbers from the start of the pool: stack is
                #     pool[0] pool[2..max] pool[1]
  .p            #   Print pool[1]
  @+            #   Rotate pool[0] to top and add to pool[1]
  \|            #   Place pool[0]+pool[1] at the start of the pool and
                #   (this is the clever bit) remove it from later in the pool
}*
;               # Discard the unused remainder of the pool

```
> 4 votes

# Answer
# Java - ~~183~~ 158

This was the most I have ever golfed anything, and I am proud of it! (Although it is nowhere near the top of the charts(because it's Java))

Thanks to Peter Taylor for suggestions

```
class f{public static void main(String[]a){int q=1,m=Byte.valueOf(a[0]),w=2,n[]=new int[m*m*2];for(n[q+=w]=1;m-->0;){System.out.println(w);for(;n[++w]>0;);}}}

```

bigger -

```
public class f {
    public static void main(String[] a) {
        int q = 1, m = Byte.valueOf(a[0]), w = 2, n[] = new int[m * m * 2];
        for (n[q += w] = 1; m-- > 0;) {
            System.out.println(w);
            for (; n[++w] > 0;)
                ;
        }
    }
}

```
> 3 votes

# Answer
# J - 28 char

Function taking `n` as argument.

```
($+/\(-.~2+i.)&:>:+/)^:_&2 4

```

We run a function, with `n` as left argument, onto its right argument repeatedly until it produces no change. The argument to start is the list `2 4`.

In the function itself, we take the partial sums `+/\` and the full sum `+/`, and then increment them both with `&:>:`. We then generate every integer from 2 to the one more than full sum (`2+i.`), and set subtract (`-.`) the partial sums, leaving a longer figure-figure sequence by definition. Finally, we shorten or cyclically extend the list to length `n`.

The result is that `2 4` becomes `3 7`, and this is removed from `2..8` leaving `2 4 5 6 8`. After another round, `2 4 5 6 8` becomes `3 7 12 18 26` becomes

```
2 4 5 6 8 9 10 11 13 14 15 16 17 19 20 21 22 23 24 25 27

```

In this way, we repeatedly extend the figure-figure sequence. The `$` length behaviour is just a non-trivial character saving way of waiting for the sequence to grow to length `n` or greater, and outputting the `n` first values when they stop changing. We don't have to wait very long, either: we can get as many as 46336 terms from four applications of the inner verb.

The same function in k:

* k2, 37 chars: `{{x#y@&~_lin[y:1+!1+/y;1+\y]}[x]/2 4}`
* k4, 36 chars: `{{x#y@&~(y:2+!1+/y)in\:1+\y}[x]/2 4}`
> 3 votes

# Answer
# Python 2 -- 77 bytes

---

Code:

```
n=input();x=1;b=range(2,n*n)
while n:v=b.pop(0);x+=v;print v;b.remove(x);n-=1

```

Works the same as @histocrat's solution, except input comes from stdin.
> 1 votes

# Answer
# Python 2 - 68

```
R=[1]
s=0
n=input()
while n:s+=1+(s+1in R);R+=[R[-1]+s];print s;n-=1

```
> 1 votes

# Answer
# Jelly, 15 bytes

```
SƤŻ‘µṀ‘Rḟ
2Ç³¡ḣ

```

Try it online!

Memory error at the input of 6.

### How it works

```
SƤŻ‘µṀ‘Rḟ  Aux. link (monad). Input: part of the desired sequence
SƤŻ‘       Sum of prefixes, then prepend a zero and increment
           This is a list of numbers to exclude from the next iteration
    µ      Re-focus on the above
     Ṁ‘Rḟ  Create range 1..Max + 1, then remove all elements of the above
           +1 is needed to progress from [2] to [2,4]

2Ç³¡ḣ  Main link (monad). Input: n, number of terms
2Ç³¡   Starting from 2, apply aux. link n times
    ḣ  Take n elements from the beginning

```

# More efficient version, 16 bytes

```
SƤŻ‘µṀ‘Rḟḣ³
2ÇÐL

```

Try it online!

Uses an idea from this J answer. Truncate to the desired length each iteration, and take the fixpoint. I thought using `S` (sum) instead of `Ṁ‘` (max+1), but I can't guarantee its correctness.
> 0 votes

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


title: Count arrays that are really unique

text:
# Question
Title: Count arrays that are really unique
This is a follow up to Count arrays that make unique sets . The significant difference is the definition of uniqueness.

Consider an array `A` of length `n`. The array contains only positive integers. For example `A = (1,1,2,2)`. Let us define `f(A)` as the set of sums of all the non-empty contiguous subarrays of `A`. In this case `f(A) = {1,2,3,4,5,6}`. The steps to produce `f(A)` are as follows:

The subarrays of `A` are `(1), (1), (2), (2), (1,1), (1,2), (2,2), (1,1,2), (1,2,2), (1,1,2,2)`. Their respective sums are `1,1,2,2,2,3,4,4,5,6`. The set you get from this list is therefore `{1,2,3,4,5,6}`.

We call an array `A` **unique** if there is no other array `B` of the same length such that `f(A) = f(B)`, except for the array `A` reversed. As an example, `f((1,2,3)) = f((3,2,1)) = {1,2,3,5,6}` but there is no other array of length `3` that produces the same set of sums.

**Task**

The task, for a given `n` and `s` is to count the number of unique arrays of that length. You can assume that `s` is between `1` and `9`. You only need to count arrays where the elements are either a given integer `s` or `s+1`. E.g. if `s=1` the arrays you are counting only contain `1` and `2`. However, the definition of uniqueness is with respect to any other array of the same length. As a concrete example `[1, 2, 2, 2]` is **not** unique as it gives the same set of sums as `[1, 1, 2, 3]`.

You should count the reverse of an array as well as the array itself (as long as the array is not a palindrome of course).

**Examples**

`s = 1`, the answers for n = 2,3,4,5,6,7,8,9 are:

```
4, 3, 3, 4, 4, 5, 5, 6

```

For `s = 1`, the unique arrays of length 4 are

```
(1, 1, 1, 1)
(2, 1, 1, 2)
(2, 2, 2, 2)

```

`s = 2`, the answers for n = 2,3,4,5,6,7,8,9 are:

```
4, 8, 16, 32, 46, 69, 121, 177

```

An example of an array that is not unique with `s = 2` is:

```
(3, 2, 2, 3, 3, 3).

```

This has the same set of sums as both of: `(3, 2, 2, 2, 4, 3)` and `(3, 2, 2, 4, 2, 3)`.

`s = 8`, the answers for n = 2,3,4,5,6,7,8,9 are:

```
4, 8, 16, 32, 64, 120, 244, 472

```

**Score**

For a given `n`, your code should output the answer for all values of `s` from `1` to `9`. Your score is the highest value of `n` for which this completes in one minute.

**Testing**

I will need to run your code on my ubuntu machine so please include as detailed instructions as possible for how to compile and run your code.

**Leaderboard**

* **n = 13** by Christian Sievers in **Haskell** (42 seconds)

# Answer
# Haskell

```
import Control.Monad (replicateM)
import Data.List (tails)
import qualified Data.IntSet as S
import qualified Data.Map.Strict as M
import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed.Mutable (write)
import System.Environment (getArgs)
import Control.Parallel.Strategies

orig:: Int -> Int -> M.Map S.IntSet (Maybe Int)
orig n s = M.fromListWith (\ _ _ -> Nothing)
               [(sums l, Just $! head l) |
                   l <- replicateM n [s, s+1],
                   l <= reverse l ]

sums :: [Int] -> S.IntSet
sums l = S.fromList [ hi-lo | (lo:r) <- tails $ scanl (+) 0 l, hi <- r ]

construct :: Int -> Int -> S.IntSet -> [Int]
construct n start set =
   setmax `seq` setmin `seq` setv `seq`
   [ weight r | r <- map (start:) $ constr (del start setlist)
                                           (V.singleton start)
                                           (n-1)
                                           (setmax - start),
                r <= reverse r ]
  where
    setlist = S.toList set
    setmin = S.findMin set
    setmax = S.findMax set
    setv = V.modify (\v -> mapM_ (\p -> write v p True) setlist)
                    (V.replicate (1+setmax) False)

    constr :: [Int] -> V.Vector Int -> Int -> Int -> [[Int]]
    constr m _ 0 _ | null m    = [[]]
                   | otherwise = []
    constr m a i x =
         [ v:r | v <- takeWhile (x-(i-1)*setmin >=) setlist,
                 V.all (V.unsafeIndex setv . (v+)) a,
                 let new = V.cons v $ V.map (v+) a,
                 r <- (constr (m \\\ new) $! new) (i-1) $! (x-v) ]

del x [] = []
del x yl@(y:ys) = if x==y then ys else if y<x then y : del x ys else yl

(\\\) = V.foldl (flip del)

weight l = if l==reverse l then 1 else 2

count n s = sum ( map value [ x | x@(_, Just _) <- M.toList $ orig n s]
                      `using` parBuffer 128 rseq )
  where
    value (sms, Just st) = uniqueval $ construct n st sms
    uniqueval [w] = w
    uniqueval _   = 0

main = do
  [ n ] <- getArgs
  mapM_ print ( map (count (read n)) [1..9]
                    `using` parBuffer 2 r0 )

```

The `orig` function creates all the lists of length `n` with entries `s` or `s+1`, keeps them if they come before their reverse, computes their sublist `sums` and puts those in a map which also remembers the first element of the list. When the same set of sums is found more than once, the first element is replaced with `Nothing`, so we know we don't have to look for other ways to get these sums.

The `construct` function searches for lists of given length and given starting value that have a given set of sublist sums. Its recursive part `constr` follows essentially the same logic as this, but has an additional argument giving the sum the remaining list entries need to have. This allows to stop early when even the smallest possible values are too big to get this sum, which gave a massive performance improvement. Further big improvements were obtained by moving this test to an earlier place (version 2) and by replacing the list of current sums by a `Vector` (version 3 (broken) and 4 (with additional strictness)). The latest version does the set membership test with a lookup table and adds some more strictness and parallelization.

When `construct` has found a list that gives the sublist sums and is smaller than its reverse, it could return it, but we are not really interested in it. It would almost be enough to just return `()` to indicate its existence, but we need to know if we have to count it twice (because it is not a palindrome and we'll never handle its reverse). So we put 1 or 2 as its `weight` into the list of results.

The function `count` puts these parts together. For each set of sublist sums (coming from `orig`) that was unique amongst the lists containing only `s` and `s+1`, it calls `value`, which calls `construct` and, via `uniqueval`, checks if there is only one result. If so, that is the weight we have to count, otherwise the set of sums was not unique and zero is returned. Note that due to lazyness, `construct` will stop when it has found two results.

The `main` function handles IO and the loop of `s` from 1 to 9.

### Compiling and Running

On debian this needs the packages `ghc`, `libghc-vector-dev` and `libghc-parallel-dev`. Save the program in a file `prog.hs` and compile it with `ghc -threaded -feager-blackholing -O2 -o prog prog.hs`. Run with `./prog <n> +RTS -N` where `<n>` is the array length for which we want to count the unique arrays.
> 5 votes

---
Tags: combinatorics, fastest-code
---


title: Largest and Smallest Possible Number

text:
# Question
Title: Largest and Smallest Possible Number
### Task

Given an array of non-negative numbers, output the largest and smallest possible number that can be formed by joining them.

### Rules

Input,Output can be in any convenient format.

The array may have at most 1 decimal number.

### Examples

```
input:[22,33,44,55.55,33]
output:4433332255.55,55.5522333344

input:[34,900,3,11,9]
output:990034311,113349009

input:[99.93,9,3,39]
output:939399.93,99.933399

input:[45.45,45,45,45]
output:45454545.45,45.45454545

input:[12,21,34,43,45.1]
output:4334211245.1,45.112213443

```

This is **code-golf** so shortest code wins.

# Answer
> 4 votes
# Python 2, ~~84~~ ~~80~~ ~~78~~ 76 bytes

```
lambda a:[''.join(sorted(a,key=lambda s:'.'in s or s+s)[::i])for i in[-1,1]]

```

Try it online!

<sub>-2 bytes, thanks to Arnauld</sub>

# Answer
> 3 votes
# Jelly, 6 bytes

```
Œ!VṢ.ị

```

Try it online!

Explanation:

```
Œ!VṢ.ị Arguments: x
Œ!     Permutations of x
  V    Concatenate the representations of each permutation's elements and evaluate the result as Jelly code
   Ṣ   Sort
    .ị Get element at index 0.5, i.e. elements at indices 0 (last) and 1 (first)

```

# Answer
> 3 votes
# Japt, ~~14 11~~ 10 bytes

```
á m¬ñn gJò

```

Try it online!

# Answer
> 3 votes
# Japt, ~~14~~ 11 bytes

```
á m¬ñn é v2

```

Try it

1 byte saved thanks to Luis, please `+1` his solution too.

```
á               :Permutations
  m             :Map
   ¬            :  Join
    ñ           :Sort by
     n          :  Converting each to a number
       é        :Rotate right
         v2     :Remove & return the first 2 elements

```

# Answer
> 3 votes
# 05AB1E, 11 bytes

```
œJΣ'.¡ï}Á2£

```

Try it online! or as a Test Suite

**Explanation**

```
 œ             # get permutations of input
  J            # join each
   Σ    }      # sort by
    '.¡        # splitting into [before decimal, after decimal]
       ï       # and converting each to int
         Á     # rotate the result right
          2£   # and take the first 2 values

```

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

```
a=>[1,-1].map(n=>a.sort((a,b)=>[a%1||a]+b<[b%1||b]+a?n:-n).join``)

```

Try it online!

### How?

We use the following test to compare two values in the input array:

```
[a % 1 || a] + b < [b % 1 || b] + a

```

The expression `x % 1 || x` returns the decimal part of \\$x\\$ if \\$x\\$ is a decimal number, or leaves \\$x\\$ unchanged otherwise.

The expression `[x % 1 || x] + y` coerces the above result to a string and concatenates it with the other value.

If there's a decimal number in the list, it must always be considered as the smallest value. By applying our conversion, a decimal number is turned into a string starting with `"0."`, which is lexicographically ordered before anything else.

*Examples:*

```
  a |   b | [a%1||a]+b | [b%1||b]+a
----+-----+------------+------------
  4 |   5 | "45"       | "54"
 10 |  11 | "1011"     | "1110"
  8 |  80 | "880"      | "808"
  7 | 9.5 | "79.5"     | "0.57"

```

# Answer
> 3 votes
# Ruby, ~~56~~ 45 bytes

```
->a{a.permutation.map{|p|p.join.to_f}.minmax}

```

Try it online!

-11 bytes, thanks Jordan

# Answer
> 2 votes
# Pyth, ~~13~~ 12 bytes

```
hM_BSvsM.p`M

```

Outputs in form `[smallest, largest]`. Try it online here, or verify all the test cases at once here.

```
hM_BSvsM.p`MQ   Implicit: Q=eval(input())
                Trailing Q inferred
          `MQ   Stringify all elements of Q
        .p      Generate all permutations of the above
      sM        Concatenate each permutation
     v          Evaluate each as a number
    S           Sort them
  _B            Pair the sorted list with its reverse
hM              Take the first element of each, implicit print

```

*Edit: Saved a byte by taking stringification out of the mapping function. Previous version:* `hM_BSmvs`Md.p`

# Answer
> 2 votes
# Perl 6, 41 bytes

```
{.max,.min}o+<<*.permutations.map(*.join)

```

Try it online!

Alternatives:

```
{.max,.min}o+<<*.permutations.map:{.join}
{.max,.min}o{[map +*.join,.permutations]}
{.max,.min}o{+<<map *.join,.permutations}

```

# Answer
> 1 votes
# Husk, 10 bytes

```
§,▼▲morṁsP

```

Try it online or verify all!

## Explanation

```
§,▼▲m(rṁs)P  -- example input: [2,3,1.1]
          P  -- permutations: [[2,3,1.1],[3,2,1.1],[1.1,3,2],[3,1.1,2],[1.1,2,3],[2,1.1,3]]
    m(   )   -- map the following
                (example with [1.1,2,3])
       ṁs    -- | show each and join: "1.123"
      r      -- | read: 1.123
             -- : [231.1,321.1,1.132,31.12,1.123,21.13]
§,           -- fork and join as tuple
  ▼          -- | min: 1.123
   ▲         -- | max: 321.1
             -- : (1.123,321.1)

```

---
Tags: code-golf
---


title: Golf some ones, and a program too

text:
# Question
Title: Golf some ones, and a program too
# Introduction

Busy Beavers are programs (specifically Turing Machine programs) that aim to output the **most ones as possible**, while having the least states as possible and halting.

---

# Challenge

Your challenge is to make a busy beaver, which outputs as many ones as possible, but also outputs **a second busy beaver**. That second busy beaver must be executable in the same language as the original program, and can be **no more bytes than the program that produced it**

So, for example, say my program was `a`. That program should aim to print as many `1`s as possible, and also output another program, say `b`, which also aims to print as many `1`s as possible and outputs another program etc etc etc. `b` must be no more bytes than `a`

The program should be printed after the `1`s, separated by any reasonable delimiter.

The outputted programs must also not be the same as any of the previous programs. When no more programs are generated, the scores are calculated from there. For example, program `a` can print `b` can print `c` can print `d`, but `d` doesn't print any other program. The scores would be calculated as `(a_ones + b_ones + c_ones + d_ones) / (a_bytes + b_bytes + c_bytes + d_bytes)` (see below)

The programs must also never error. The "programs" can also be functions, as long as they execute with no arguments

---

# Scoring

Your submission's score is the sum of the number of ones outputted by your programs, all divided by the sum of the bytes of the programs. The higher the score, the better.

# Answer
# C (gcc), 71 bytes

I've not done one of these before but here's a shot at it;

Each program should print 4,294,967,295 ones, divided by the sum of bytes 71+30 scores 85,048,857

```
main(c){puts("main(c){while(~c++)puts(\"1\");}");for(;~c++;)puts("1");}

```

Try it online!
> 1 votes

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

```
(f=_=>_?'1'.repeat(_)+`&&(f=${f})(${_-1})`:1)(1e3)

```

Try it online!
> 1 votes

# Answer
# brainfuck, 99 bytes, \\$f\_{255}(255^2)\\$

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

```

Assumes a wrapping implementation with an infinite tape in both directions.

This is modified from my Largest Number Printable to print `1`s instead of `3`s.
> 1 votes

---
Tags: code-challenge, busy-beaver
---


title: Number letter counts

text:
# Question
Title: Number letter counts
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

Output how many letters would be used if all the numbers from 1 to 1000 (one thousand) inclusive were written out in words.

*NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.*

You must actually calculate it - just printing the predetermined result is not allowed.

Output with any acceptable method.

# Answer
# Mathematica, 38 bytes

```
StringLength@StringJoin@IntegerName[Range[1000]]

```

@Doorknob has a leaner implementation:

```
Tr@StringLength@IntegerName@Range@1000

```

(\* 20961 \*)

---

*Explanation*

```
IntegerName[Range[10]]

```

(\* {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"} \*)

```
StringJoin@IntegerName[Range[10]]

```

(\* "onetwothreefourfivesixseveneightnineten" \*)

```
StringLength@StringJoin@IntegerName[Range[10]]

```

(\* 39 \*)
> 1 votes

# Answer
# Common Lisp, ~~104~~ ~~98~~ ~~85~~ ~~76~~ ~~75~~ 74 bytes

```
(princ(loop for i to 999 sum(count-if'both-case-p(format nil"~R"(1+ i)))))

```

Try it online!
> 1 votes

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


title: Reciprocal copycats

text:
# Question
Title: Reciprocal copycats
Let \\$A\\$ be a positive integer consisting of \\$n\\$ decimal digits \\$d\_1,d\_2,...,d\_n\\$. Let \\$B\\$ be another positive integer.

For the purpose of this challenge, we call \\$A\\$ a **copycat** of \\$B\\$ if there exists at least one list of positive integers \\$p\_1,p\_2,...,p\_n\\$ such that:

$$\sum\_{i=1}^{n}{{d\_i}^{p\_i}}=B$$

\\$A\\$ and \\$B\\$ are called **reciprocal copycats** if \\$A\\$ is a copycat of \\$B\\$ and \\$B\\$ is a copycat of \\$A\\$.

## Example

\\$526\\$ and \\$853\\$ are reciprocal copycats because:

$$5^3 + 2^9 + 6^3 = 853$$

and:

$$8^3 + 5^1 + 3^2 = 526$$

## The challenge

Given two positive integers \\$A\\$ and \\$B\\$, your task is to print or return a truthy value if \\$A\\$ and \\$B\\$ are reciprocal copycats or a falsy value otherwise.

## Clarifications and rules

* You may take \\$A\\$ and \\$B\\$ in any reasonable, unambiguous format (e.g. integers, strings, lists of digits, ...)
* \\$A\\$ and \\$B\\$ may be equal. If a number is a reciprocal copycat of itself, it belongs to A007532.
* Instead of truthy/falsy values, you may return two distinct **consistent** values.
* For \\$1\le A\<1000\\$ and \\$1\le B\<1000\\$, your code must complete in **less than one minute**. If it's taking too much time for higher values, it must however be able to solve them in theory.
* This is .

## Test cases

```
Truthy:
1 1
12 33
22 64
8 512
23 737
89 89
222 592
526 853
946 961
7 2401
24 4224
3263 9734
86 79424
68995 59227
32028 695345

Falsy:
1 2
3 27
9 24
24 42
33 715
33 732
222 542
935 994
17 2401
8245 4153

```

# Answer
# Brachylog, 19 bytes

```
ẹ{∧ℕ₁;?↔^}ᵐ².+ᵐ↔?∧≜

```

Try it online!

Outputs `true.` or `false.`

### Explanation

```
ẹ                     Split the numbers into lists of digits
 {       }ᵐ²          For each digit
  ∧ℕ₁                 Let I be a strictly positive integer
     ;?↔^                Compute the digit to the power I (which is unknown currently)
            .         Call . the list of those new numbers
            .+ᵐ       Their mapped sum results…
               ↔?     …in the reverse of the input
                 ∧≜   Find if there effectively are values for the numbers in . to satisfy
                        these relationships

```
> 8 votes

# Answer
# Husk, 17 bytes

```
Λλ€⁰mΣΠTṪ^ḣ√⁰d)De

```

Try it online! Finishes all test cases under 1000 in about 11 seconds.

## Explanation

```
Λλ€⁰mΣΠTṪ^ḣ√⁰d)De  Implicit inputs, say 12 and 33.
                e  Put into a list: [12,33]
               D   Duplicate: [12,33,12,33]
Λ                  Does this hold for all adjacent pairs:
                    (12,33 is checked twice but it doesn't matter)
                    For example, arguments are 33 and 12.
 λ            )     Anonymous function with arguments 33 (explicit) and 12 (implicit).
             d      Base-10 digits of implicit argument: [1,2]
          ḣ√⁰       Range to square root of explicit argument: [1,2,3,4]
        Ṫ^          Outer product with power: [[1,2],[1,4],[1,8],[1,16],[1,32]]
       T            Transpose: [[1,1,1,1,1],[2,4,8,16,32]]
      Π             Cartesian product: [[1,2],[1,4],...,[1,32]]
    mΣ              Map sum: [3,5,...,33]
  €⁰                Is the explicit argument in this list? Yes.

```

## Why it works

If we have \\$B = d\_1^{p\_1} + \cdots + d\_n^{p\_n}\\$ where the \\$d\_i\\$ are digits and \\$p\_i\\$ are positive integers, then \\$d\_i^{p\_i} \leq B\\$ for all \\$i\\$, or equivalently \\$p\_i \leq \log\_{d\_i} B\\$. We can ignore the case \\$d\_i \leq 1\\$, since exponentiating \\$0\\$ or \\$1\\$ does not change it. In my program the search space is \\$1 \leq p\_i \leq \sqrt{B}\\$ (to comply with the time restriction; I would use \\$1 \leq p\_i \leq B\\$ otherwise), so if we have \\$\lfloor \log\_{d\_i} B \rfloor \leq \lfloor \sqrt{B} \rfloor\\$, then everything is fine. If \\$d\_i \geq 3\\$, this holds for all natural numbers \\$B\\$, so the only dangerous case is \\$d\_i = 2\\$. We have \\$\lfloor \log\_2 B \rfloor \> \lfloor \sqrt{B} \rfloor\\$ only for \\$B = 8\\$. In this case \\$2^3 = 8\\$, but the search only considers exponents \\$1\\$ and \\$2\\$. If the other number number \\$A\\$ contains the digit \\$2\\$, either it has other nonzero digits as well (so the exponent of \\$2\\$ cannot be \\$3\\$ in the sum), or \\$A = 2 \cdot 10^k\\$ for some \\$k\\$. In the latter case, \\$A\\$ is not a power of \\$8\\$, so it cannot be a copycat of \\$B\\$ anyway, and the program correctly returns a falsy value regardless of the other computation.
> 6 votes

# Answer
# Perl 6, ~~87 84~~ 69 bytes

*-15 bytes thanks to nwellnhof!*

```
{!grep {!grep $^b,[X+] 0,|map (*X**1..$b.msb+1),$^a.comb},.[0,1,1,0]}

```

Try it online!

Anonymous code block that returns True or False.

### Explanation:

```
{!grep {!grep $^b,[X+] 0,|map (*X**1..$b.msb+1),$^a.comb},.[0,1,1,0]}

{                                                                   }  # Anonymous code block
 !grep    # None of:
                                                          .[0,1,1,0]   # The input and the input reverse
       {!grep       # None of
                  [X+]       # All possible sums of
                       0,|   # 0 (this is to prevent single digit numbers being crossed with themself)
                          map                  ,$^a.comb   # Each digit mapped to
                              (*X**           )  # The power of
                                   1..$b.msb+1   # All of 1 to the most significant bit of b plus 1
                                                 # This could just be b+1, but time constraints...
              $^b,  # Is equal to b

```
> 4 votes

# Answer
# JavaScript (Node.js), ~~116~~ ~~92~~ ~~89~~ ~~86~~ ~~83~~ 77 bytes

```
a=>b=>(G=(c,g,f=h=g%10)=>g?c>f&f>1&&G(c,g,h*f)||G(c-f,g/10|0):!c)(a,b)&G(b,a)

```

Try it online!

Expect input as `(A)(B)`.
> 4 votes

# Answer
# 05AB1E, ~~26~~ 22 bytes

```
εVтLIàgãεYSym}OIyKå}˜P

```

Takes the input as a list (i.e. `[526,853]`).

Try it online or verify most test cases in the range `[1,999]`.

Similar as my old answer below, except that the `[1,n]` list is hardcoded to `[1,100]`, and it creates the cartesian list twice, once for each input-mapping, which is the main bottleneck in terms of performance.

---

**Old 26 bytes answer that's better for performance:**

```
Z©bgL®gãUεVXεYSym}OsN>èå}P

```

In this version I traded in some bytes to make the performance a lot better so it can run `[1,1000]` with ease. Test cases containing numbers in the range `[1,9999]` are done in about a second on TIO. Test cases in the range `[10000,99999]` in about 10-15 seconds on TIO. Above that it will timeout.

Try it online or verify all test cases with numbers in the range `[1,9999]`.

**Explanation:**

```
Z                 # Push the max of the (implicit) input-list (without popping)
                  #  i.e. [526,853] → 853
 ©                # Store it in the register (without popping)
  b               # Convert to binary
                  #  i.e. 853 → 1101010101
   g              # Take its length
                  #  i.e. 1101010101 → 10
    L             # Pop and push a list [1, n]
                  #  i.e. 10 → [1,2,3,4,5,6,7,8,9,10]
     ®            # Push the max from the register
      g           # Take its length
                  #  i.e. 853 → 3
       ã          # Cartesian product the list that many times
                  #  i.e. [1,2,3,4,5,6,7,8,9,10] and 3
                  #   → [[1,1,1],[1,1,2],[1,1,3],...,[10,10,8],[10,10,9],[10,10,10]]
        U         # Pop and store it in variable `X`
ε              }  # Map both values of the input list:
 V                # Store the current value in variable `Y`
  Xε    }         # Map `y` over the numbers of variable `X`
    Y             # Push variable `Y`
     S            # Convert it to a list of digits
                  #  i.e. 526 → [5,2,6]
      ym          # Take each digit to the power of the current cartesian product sublist
                  #  i.e. [5,2,6] and [3,9,3] → [125,512,216]
         O        # Take the sum of each inner list
                  #  i.e. [[5,2,6],[5,2,36],[5,2,216],...,[125,512,216],...]
                  #   → [13,43,223,...,853,...]
          s       # Swap to push the (implicit) input
           N>     # Push the index + 1
                  #  i.e. 0 → 1
             è    # Index into the input-list (with automatic wraparound)
                  #  i.e. [526,853] and 1 → 853
              å   # Check if it's in the list of sums
                  #  i.e. [13,43,223,...,853,...] and 853 → 1
                P # Check if it's truthy for both both (and output implicitly)
                  #  i.e. [1,1] → 1

```
> 4 votes

# Answer
# Python 2, 102 bytes

```
lambda a,b:g(a,b)*g(b,a)
g=lambda a,b,e=1:b==a<1or(b>0<=b-e>=0<a)and(g(a/10,b-(a%10)**e)or g(a,b,e+1))

```

Try it online!
> 4 votes

# Answer
# Haskell, 77 bytes

```
a#b=a!b&&b!a
a!b|a<1=b==0|b<1=b>1|1<2=or[div a 10!(b-mod a 10^e)|e<-[1..b+1]]

```

Try it online!
> 4 votes

# Answer
# , 56 bytes

```
h~*h=.4 :'x e.+/|:>,{x 4 :''<y&*^:(x&>)^:a:y''"+"."+":y'

```

Try it online!

Yay, nested explicit definition!

### How it works

```
powers =. 4 :'<y&*^:(x&>)^:a:y'  Explicit aux verb. x = target, y = digit
                             y   Starting from y,
               y&*^:     ^:a:    collect all results of multiplying y
                    (x&>)        until the result is at least x
              <                  Box it.

h=.4 :'x e.+/|:>,{x powers"+"."+":y'  Explicit aux verb. x, y = two input numbers
                            "."+":y   Digits of y
                  x powers"+          Collect powers of digits of y under x
                 {            Cartesian product of each item
           +/|:>,             Format correctly and compute the sums
       x e.                   Does x appear in the list of sums?

h~*h  Tacit main verb. x, y = two input numbers
      Since h tests the condition in only one direction,
      test again the other way around (~) and take the AND.

```
> 2 votes

# Answer
# Python 2, ~~149~~ ~~147~~ ~~143~~ ~~139~~ ~~132~~ ~~118~~ ~~108~~ ~~107~~ ~~106~~ 105 bytes

```
lambda a,b:g(a,b)*g(b,a)
g=lambda a,b:any(g(a/10,b-(a%10)**-~i)for i in(a*b>0)*range(len(bin(b))))or b==0

```

Try it online!

<sub>-4 bytes, thanks to Vedant Kandoi</sub>
> 1 votes

# Answer
# J, 68 bytes

I thought J would perform quite well here, but it ended up being tougher than I expected and would love any suggestions for further golfing...

```
g=.#@#:@[
1 1-:[:(([:+./[=1#.]^"#.1+g#.inv[:i.g^#@])"."0@":)/"1],:|.

```

Try it online!

*NOTE: we subtract 3 chars from the TIO count there since `f=.` on the main function doesn't count*

## ungolfed

```
1 1 -: [: (([: +./ [ = 1 #. ] ^"#. 1 + g #.inv [: i. g ^ #@]) "."0@":)/"1 ] ,: |.

```
> 1 votes

---
Tags: code-golf, decision-problem, integer, restricted-time
---


title: Quaternion square root

text:
# Question
Title: Quaternion square root
## Background

Quaternion is a number system that extends complex numbers. A quaternion has the following form

$$ a + bi + cj + dk $$

where \\$ a,b,c,d \\$ are real numbers and \\$ i,j,k \\$ are three *fundamental quaternion units*. The units have the following properties:

$$ i^2 = j^2 = k^2 = -1 $$ $$ ij = k, jk = i, ki = j $$ $$ ji = -k, kj = -i, ik = -j $$

Note that **quaternion multiplication is not commutative**.

## Task

Given a *non-real* quaternion, compute at least one of its square roots.

### How?

According to this Math.SE answer, we can express any non-real quaternion in the following form:

$$ q = a + b\vec{u} $$

where \\$ a,b\\$ are real numbers and \\$ \vec{u} \\$ is the imaginary unit vector in the form \\$ xi + yj + zk \\$ with \\$ x^2 + y^2 + z^2 = 1 \\$. Any such \\$ \vec{u} \\$ has the property \\$ \vec{u}^2 = -1 \\$, so it can be viewed as the imaginary unit.

Then the square of \\$ q \\$ looks like this:

$$ q^2 = (a^2 - b^2) + 2ab\vec{u} $$

Inversely, given a quaternion \\$ q' = x + y\vec{u} \\$, we can find the square root of \\$ q' \\$ by solving the following equations

$$ x = a^2 - b^2, y = 2ab $$

which is identical to the process of finding the square root of a complex number.

Note that a negative real number has infinitely many quaternion square roots, but **a non-real quaternion has only two square roots**.

## Input and output

Input is a non-real quaternion. You can take it as four real (floating-point) numbers, in any order and structure of your choice. Non-real means that at least one of \\$ b,c,d \\$ is non-zero.

Output is one or two quaternions which, when squared, are equal to the input.

## Test cases

```
   Input (a, b, c, d)  =>  Output (a, b, c, d) rounded to 6 digits

 0.0,  1.0,  0.0,  0.0 =>  0.707107,  0.707107,  0.000000,  0.000000
 1.0,  1.0,  0.0,  0.0 =>  1.098684,  0.455090,  0.000000,  0.000000
 1.0, -1.0,  1.0,  0.0 =>  1.168771, -0.427800,  0.427800,  0.000000
 2.0,  0.0, -2.0, -1.0 =>  1.581139,  0.000000, -0.632456, -0.316228
 1.0,  1.0,  1.0,  1.0 =>  1.224745,  0.408248,  0.408248,  0.408248
 0.1,  0.2,  0.3,  0.4 =>  0.569088,  0.175720,  0.263580,  0.351439
99.0,  0.0,  0.0,  0.1 =>  9.949876,  0.000000,  0.000000,  0.005025

```

Generated using this Python script. Only one of the two correct answers is specified for each test case; the other is all four values negated.

## Scoring & winning criterion

Standard rules apply. The shortest program or function in bytes in each language wins.

# Answer
## APL (NARS), 2 bytes

NARS has built-in support for quaternions. ¯\\\_(⍨)\_/¯
> 30 votes

# Answer
# Python 2, 72 bytes

```
def f(a,b,c,d):s=((a+(a*a+b*b+c*c+d*d)**.5)*2)**.5;print s/2,b/s,c/s,d/s

```

Try it online!

More or less a raw formula. I thought I could use list comprehensions to loop over `b,c,d`, but this seems to be longer. Python is really hurt here by a lack of vector operations, in particular scaling and norm.

**Python 3, 77 bytes**

```
def f(a,*l):r=a+sum(x*x for x in[a,*l])**.5;return[x/(r*2)**.5for x in[r,*l]]

```

Try it online!

Solving the quadratic directly was also shorter than using Python's complex-number square root to solve it like in the problem statement.
> 8 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
Sqrt
<<Quaternions`

```

Try it online!

Mathematica has Quaternion built-in too, but is more verbose.

---

Although built-ins look cool, do upvote solutions that don't use built-ins too! I don't want votes on questions reaching HNQ be skewed.
> 6 votes

# Answer
# JavaScript (ES7), ~~55~~ 53 bytes

Based on the direct formula used by xnor.

Takes input as an array.

```
q=>q.map(v=>1/q?v/2/q:q=((v+Math.hypot(...q))/2)**.5)

```

Try it online!

### How?

Given an array \\$q=\[a,b,c,d\]\\$, this computes:

$$x=\sqrt{\frac{a+\sqrt{a^2+b^2+c^2+d^2}}{2}}$$

And returns:

$$\left\[x,\frac{b}{2x},\frac{c}{2x},\frac{d}{2x}\right\]$$

```
q =>                            // q[] = input array
  q.map(v =>                    // for each value v in q[]:
    1 / q ?                     //   if q is numeric (2nd to 4th iteration):
      v / 2 / q                 //     yield v / 2q
    :                           //   else (1st iteration, with v = a):
      q = (                     //     compute x (as defined above) and store it in q
        (v + Math.hypot(...q))  //     we use Math.hypot(...q) to compute:
        / 2                     //       (q[0]**2 + q[1]**2 + q[2]**2 + q[3]**2) ** 0.5
      ) ** .5                   //     yield x
  )                             // end of map()

```
> 4 votes

# Answer
# Haskell, 51 bytes

```
f(a:l)|r<-a+sqrt(sum$(^2)<$>a:l)=(/sqrt(r*2))<$>r:l

```

Try it online!

A direct formula. The main trick to express the real part of the output as `r/sqrt(r*2)` to parallel the imaginary part expression, which saves a few bytes over:

**54 bytes**

```
f(a:l)|s<-sqrt$2*(a+sqrt(sum$(^2)<$>a:l))=s/2:map(/s)l

```

Try it online!
> 3 votes

# Answer
# Charcoal, 32 bytes

```
≔Ｘ⊗⁺§θ⁰ＸΣＥθ×ιι·⁵¦·⁵η≧∕ηθ§≔θ⁰⊘ηＩθ

```

Try it online! Link is to verbose version of code. Port of @xnor's Python answer. Explanation:

```
≔Ｘ⊗⁺§θ⁰ＸΣＥθ×ιι·⁵¦·⁵η

```

Square all of the elements of the input and take the sum, then take the square root. This calculates \\$ | x + y\vec{u} | = \sqrt{ x^2 + y^2 } = \sqrt{ (a^2 - b^2)^2 + (2ab)^2 } = a^2 + b^2 \\$. Adding \\$ x \\$ gives \\$ 2a^2 \\$ which is then doubled and square rooted to give \\$ 2a \\$.

```
≧∕ηθ

```

Because \\$ y = 2ab \\$, calculate \\$ b \\$ by dividing by \\$ 2a \\$.

```
§≔θ⁰⊘η

```

Set the first element of the array (i.e. the real part) to half of \\$ 2a \\$.

```
Ｉθ

```

Cast the values to string and implicitly print.
> 3 votes

# Answer
# Java 8, 84 bytes

```
(a,b,c,d)->(a=Math.sqrt(2*(a+Math.sqrt(a*a+b*b+c*c+d*d))))/2+" "+b/a+" "+c/a+" "+d/a

```

Port of *@xnor*'s Python 2 answer.

Try it online.

**Explanation:**

```
(a,b,c,d)->           // Method with four double parameters and String return-type
  (a=                 //  Change `a` to:
     Math.sqrt(       //   The square root of:
       2*             //    Two times:
         (a+          //     `a` plus,
          Math.sqrt(  //     the square-root of:
            a*a       //      `a`  squared,
            +b*b      //      `b` squared,
            +c*c      //      `c` squared,
            +d*d))))  //      And `d` squared summed together
  /2                  //  Then return this modified `a` divided by 2
  +" "+b/a            //  `b` divided by the modified `a`
  +" "+c/a            //  `c` divided by the modified `a`
  +" "+d/a            //  And `d` divided by the modified `a`, with space delimiters

```
> 3 votes

# Answer
# 05AB1E, 14 bytes

```
nOtsн+·t©/¦®;š

```

Port of *@xnor*'s Python 2 answer.

Try it online or verify all test cases.

**Explanation:**

```
n                 # Square each number in the (implicit) input-list
 O                # Sum them
  t               # Take the square-root of that
   sн+            # Add the first item of the input-list
      ·           # Double it
       t          # Take the square-root of it
        ©         # Store it in the register (without popping)
         /        # Divide each value in the (implicit) input with it
          ¦       # Remove the first item
           ®;     # Push the value from the register again, and halve it
             š    # Prepend it to the list (and output implicitly)

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 28 bytes

```
{s=#+Norm@{##},##2}/(2s)^.5&

```

Port of @xnor's Python 2 answer.

Try it online!
> 2 votes

# Answer
# C# .NET, 88 bytes

```
(a,b,c,d)=>((a=System.Math.Sqrt(2*(a+System.Math.Sqrt(a*a+b*b+c*c+d*d))))/2,b/a,c/a,d/a)

```

Port of my Java 8 answer, but returns a Tuple instead of a String. I thought that would have been shorter, but unfortunately the `Math.Sqrt` require a `System`-import in C# .NET, ending up at 4 bytes longer instead of 10 bytes shorter.. \>.\>

The lambda declaration looks pretty funny, though:

```
System.Func<double, double, double, double, (double, double, double, double)> f =

```

Try it online.
> 2 votes

# Answer
# Perl 6, 49 bytes

```
{;(*+@^b>>².sum**.5*i).sqrt.&{.re,(@b X/2*.re)}}

```

Try it online!

Curried function taking input as `f(b,c,d)(a)`. Returns quaternion as `a,(b,c,d)`.

### Explanation

```
{;                                             }  # Block returning WhateverCode
     @^b>>².sum**.5     # Compute B of quaternion written as q = a + B*u
                        # (length of vector (b,c,d))
  (*+              *i)  # Complex number a + B*i
                      .sqrt  # Square root of complex number
                           .&{                }  # Return
                              .re,  # Real part of square root
                                  (@b X/2*.re)  # b,c,d divided by 2* real part

```
> 1 votes

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