title: Ways to add 1 to lists of lists

text:
# Question
Title: Ways to add 1 to lists of lists
*Adapted from this StackOverflow question*

In this challenge you will take a list of lists of integers, e.g.

```
A = [[1,2],[3,4],[5],[]]

```

And an additional single integer (e.g. `n = 7`). If you were to add `n` to the front of one of the lists in `A` there would be as many ways to do that as there are lists in `A`. In this example `4`:

```
A' = [[7,1,2],[3,4],[5],[]]
A' = [[1,2],[7,3,4],[5],[]]
A' = [[1,2],[3,4],[7,5],[]]
A' = [[1,2],[3,4],[5],[7]]

```

In this challenge you will output all possible ways to do this, in the order of how early `n` is inserted. So for the example the output is just:

```
[ [[7,1,2],[3,4],[5],[]]
, [[1,2],[7,3,4],[5],[]]
, [[1,2],[3,4],[7,5],[]]
, [[1,2],[3,4],[5],[7]]
]

```

This is so answer answers will be scored in bytes with fewer bytes being better.

## Test cases

```
9, [] -> []
9, [[]] -> [[[9]]]
10, [[1,2,3]] -> [[[10,1,2,3]]]
7, [[1,2],[3,4],[5],[]] -> [[[7,1,2],[3,4],[5],[]],[[1,2],[7,3,4],[5],[]],[[1,2],[3,4],[7,5],[]],[[1,2],[3,4],[5],[7]]]
2, [[1,2],[2,2],[2]] -> [[[2,1,2],[2,2],[2]],[[1,2],[2,2,2],[2]],[[1,2],[2,2],[2,2]]]

```

# Answer
> 10 votes
# Rust, 185 184 bytes

My first ever code golf submission

```
fn r(a:Vec<Vec<u8>>,n:u8){let mut x:Vec<Vec<Vec<u8>>>=Vec::new();for i in 0..a.len(){let mut b=a.clone();let c=&vec![n];b[i].splice(0..0,c.iter().cloned());x.push(b);}print!("{:?}",x)}

```

**Explanation**

This code copies the list for every sublist, then appends the number to the front of it, adds it to a final list which it then prints. We can also get away with returning the print statement to save a ;!

Try it online!

Edit: Kevin Cruijssen pointed out a space in my print.

Edit: @Bubbler showed me what it's like to truly golf in Rust and got it down to 90 bytes! I won't be updating the byte count in the header since I don't believe that his edits counts as "edits" rather an entire new submission and it doesn't reflect my work.

```
|a:&mut[Vec<_>],n|{for i in 0..a.len(){a[i].insert(0,n);print!("{:?}",a);a[i].remove(0);}}

```

# Answer
> 7 votes
# 05AB1E, 6 bytes

```
UεXšNǝ

```

Try it online or verify all test cases.

**Explanation:**

```
U       # Pop the store the first (implicit) input-integer in variable `X`
 ε      # Map over the second (implicit) input-list of lists:
  Xš    #  Prepend `X` in front of the current part
    Nǝ  #  And replace the item at the current map-index in the second (implicit)
        #  input-list with this modified part
        # (after which the result is output implicitly)

```

# Answer
> 6 votes
# Haskell, 37 bytes

This is Willem Van Onsem's SO answer with a couple of trivial golfs.

```
n!(a:b)=((n:a):b):map(a:)(n!b)
_!_=[]

```

Try it online!

# Answer
> 3 votes
# Vyxal, 54 bitsv2, 6.75 bytes

```
vJ¨2¹^Ȧ

```

Try it Online!

Bitstring:

```
100010101100011111000100110100010110110111100010110010

```

# Answer
> 3 votes
# APL+WIN, 36 bytes

Prompts for the list of lists as a nested vector then the integer to be added. Index origin = 0

```
m←((⍴n)*2)⍴n←,⎕⋄m[(1+⍴n)×⍳⍴n]←⎕,¨n⋄m

```

Try it online! Thanks to Dyalog Classic

# Answer
> 3 votes
# , 22 17 21 20 bytes

```
(<@#"0~[:=#\),&.>"1]

```

Try it online!

Could save 4 bytes if we can assume each element of the input is unique.

Consider `7 f 1 2 3; 1 2; 4`:

* `[:=#\` Create an identity matrix whose sides equal our list length:

```
1 0 0
0 1 0
0 0 1

```
* `<@#"0~` Use that as a mask to copy our new element, and box each result. Zeros become empty boxes:

```
┌─┬─┬─┐
│7│ │ │
├─┼─┼─┤
│ │7│ │
├─┼─┼─┤
│ │ │7│
└─┴─┴─┘

```
* `,&.>"1]` For each row, join elementwise to the original input:

```
┌───────┬─────┬───┐
│7 1 2 3│1 2  │4  │
├───────┼─────┼───┤
│1 2 3  │7 1 2│4  │
├───────┼─────┼───┤
│1 2 3  │1 2  │7 4│
└───────┴─────┴───┘

```

# Answer
> 3 votes
# JavaScript (Node.js), 41 bytes

```
t=>a=>a.map(u=>a.map(v=>u==v?[t,...u]:v))

```

Try it online!

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

```
(i=1;x##~Insert~{i++,1})/@#&

```

Try it online!

# Answer
> 3 votes
# Uiua, ~~13~~ 12 bytes

```
≡⍜(⇌⊔⊡)⊂⇡⊃⧻¤

```

Try it!

-1 thanks to Bubbler

```
≡⍜(⇌⊔⊡)⊂⇡⊃⧻¤
         ⊃⧻¤  # fix the array and get its length
        ⇡     # range (of length)
≡⍜(⇌⊔⊡)       # change each unboxed reversed row by...
       ⊂      # join (the integer input)
              # then unreverse, re-box, and put each item back

```

# Answer
> 2 votes
# Retina, 33 bytes

```
L$`\[+(?=(.+),(.+))
$>`$2,$1
,]
]

```

Try it online! Takes `n` as the second argument. Explanation:

```
L$`\[+(?=(.+),(.+))

```

Find the beginning of each list.

```
$>`$2,$1

```

For each occurrence, output the list with `n` moved to that position.

```
,]
]

```

Fix up the list if it was originally empty.

# Answer
> 2 votes
# Python 3, 50 bytes

```
lambda a,L:[[[a][:l is k]+l for l in L]for k in L]

```

Try it online!

Will not work on lists with multiple references to the same object. I..e.: `L = [[10],[10]]` fine (same value but different objects) but `L = 2*[[10]]` fail (twice the same object)

# Answer
> 2 votes
# , 58 bytes

Or **\>=4.1, 44 bytes** by replacing two `function` occurrences with `\`s.

```
function(x,A)Map(function(i){A[[i]]=c(x,A[[i]]);A},seq(A))

```

Try it online!

# Answer
> 2 votes
# Julia 1.0, 47 bytes

```
n\l=(k=keys(l)).|>i->k.|>j->[fill(n,i==j);l[j]]

```

Try it online!

# Answer
> 2 votes
# Ruby, 60 bytes

```
->n,l{(0...t=l.size).map{|i|[*l[0,i],[n]+l[i],*l[i+1...t]]}}

```

Try it online!

# Answer
> 2 votes
# ayr, 15 bytes

Beats J by 5 bytes, so I'm happy :)

```
],`"\:]:#":i:&#

```

# Explanation

```
           i:&#    Construct an NxN identity matrix (N = # lists)
        #":        Foreach num I in that, replace with left arg I times
      ]:           Convert that to a hook
    \:             For each item on the right and entirety of left
 ,`"               Concatenate left to back of right on an element x element basis
]                  Where the left is the list

```

Takes the number on the left and the list of lists on the right.

# Answer
> 2 votes
# jq, 51 bytes

```
. as$a|[range(length)]|map(. as$i|$a|.[$i]|=[$n]+.)

```

Where `$n` is `n`.

# Answer
> 2 votes
# Curry (PAKCS), 21 bytes

```
n!(a++b:c)=a++(n:b):c

```

Attempt This Online!

# Answer
> 1 votes
# Charcoal, 16 bytes

```
ＩＥηＥη⎇⁼κμ⮌⊞Ｏ⮌λθλ

```

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

```
  η                 Input list of lists
 Ｅ                  Map over each list
    η               Input list of lists
   Ｅ                Map over each list
       κ            Outer index
      ⁼             Equal to
        μ           Inner index
     ⎇              If true then
             λ      Current list
            ⮌       Reversed
              θ     Input `n`
          ⊞Ｏ        Appended
         ⮌          Reversed
               λ    Otherwise current list
Ｉ                   Cast to string
                    Implicitly print

```

Charcoal's default output format might be a little tricky to read, so here's a 17-byte version with prettier output:

```
Ｅη⭆¹Ｅη⎇⁼κξ⮌⊞Ｏ⮌νθν

```

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

# Answer
> 1 votes
# Pari/GP, 48 bytes

```
(n,a)->matrix(#a,,i,j,concat([n][1..i==j],a[j]))

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 44 bytes

Expects `(n)(list_of_lists)`.

### Version 1

```
n=>a=>a.map((v,i,[...b])=>(b[i]=[n,...v],b))

```

Try it online!

### Version 2

```
n=>a=>a.map((_,i)=>a.map(v=>i--?v:[n,...v]))

```

Try it online!

# Answer
> 1 votes
# Pip `-xP`, 13 bytes

```
aRA_(BPEb)MEa

```

Attempt This Online!

### Explanation

The `-x` flag evaluates the inputs, meaning we can treat `[[1];[2;3]]` as a list rather than a string.

```
aRA_(BPEb)MEa
            a  First command-line input (the nested list)
          ME   Map the following function to that list, enumerated (first function arg
               is index, second function arg is sublist):
a               The whole list
 RA             Replace the element at index given by
   _            first function arg
    (    )      with
     B          second function arg
      PE        with the following value prepended:
        b       Second command-line input

```

The `-P` flag prints each sublist of the result, formatted as a list, on a separate line. Other formats that could work include `-p` and `-S`.

# Answer
> 0 votes
# Ruby, 42 bytes

```
->n,l{i=-1;l.map{|w|z=*l;z[i+=1]=[n]+w;z}}

```

Try it online!

# Answer
> 0 votes
# Burlesque, 24 bytes

```
1svsa.*zi{{1gv+]}x/ap}^m

```

Try it online!

I'm sure there's a better way...

```
1sv    # Save input as 1
sa.*   # Repeat arr len(arr) times
zi     # Zip with indices
{
 {
  1gv  # Get input (value1)
  +]   # Prepend
 }
 x/    # Reorder local stack
 ap    # Apply function to index (from zip)
}^m    # Push and map each

```

# Answer
> 0 votes
# Stax, 10 bytes

```
ü↨○◘╞Q┐p☺Ç

```

Run and debug it

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


title: Answer a Loaded Question (with Lojban!)

text:
# Question
Title: Answer a Loaded Question (with Lojban!)
A loaded question is something like 'Have you stopped swearing?' in which both yes and no answers mean that I have swore, meaning it is impossible to answer the question if I haven't swore.

However, the constructed language Lojban has a word na'i, which means there is something wrong with what you just said.

Your input should be a list of newline-seperated strings containing the following tokens:

1. `start`  followed by any integer (e.g. `-1`, `0`, `1`)
2. `stop`  \+ integer
3. `haveYouStopped`  \+ integer

You can assume that each `stop`  *n* is followed by the corresponding `start`  *n*.

Then for each `haveYouStopped`  *n* in the code:

* Print `Yes, I have.` \+ a newline if the last `stop`  *n* occurs before the last `start`  *n*
* Print `No, I have not.` \+ a newline if the last `stop`  *n* occures after the last `start`  *n*, or at least one `start`  *n* but no `stop`  *n* is found in the previous line
* Print `.i na'i` \+ a newline if no `start`  *n* occurs in the previous lines.

The last newline is optional.

Examples:

```
start 1
stop 1
haveYouStopped 1

```

Output: Yes, I have.

```
start 1
haveYouStopped 1

```

Output: No, I haven't.

```
haveYouStopped 1

```

Output: .i na'i

All code is counted in UTF-8 bytes. Codepoints outside the UTF-8 range are not allowed. Use any language, shortest code wins. Also, no external sources are allowed.

# Answer
> 2 votes
# Retina, ~~92~~ ~~75~~ 74 bytes

```
L$ms`d( \S+)$(?<=([pt])\1$.+?)?
$2.i na'i
p.+
YesI.
t.+
NoIn't.
I
, I have

```

Try it online! Link includes test cases. Explanation:

```
L$ms`d( \S+)$(?<=([pt])\1$.+?)?
$2.i na'i

```

For each `haveYouStopped` line, look for a previous `start` or `stop` line with that signed integer, and if so prefix the output with the final `t` or `p`, otherwise just output `.i na'i`.

```
p.*
YesI.
t.*
NoIn't.
I
, I have

```

If a start or stop was found then decode it to the desired output string.

Edit: Saved 17 bytes and corrected the Yes/No order thanks to @tsh.

Since this question counts in UTF-8, I didn't post a Charcoal answer, but had it been allowed it would have been 59 SBCS bytes:

```
≔⦃⦄θＷＳ¿№ιs§≔θΣι⪫⪪⎇№ιp¦Yes,.¦No,n't.¦,¦, I have⟦∨§θΣι.i na'i

```

Attempt This Online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:

```
≔⦃⦄θ

```

Start with all questions being impossible.

```
ＷＳ

```

Loop through the input strings.

```
¿№ιs

```

Does this string resolve a question?

```
§≔θΣι⪫⪪⎇№ιp¦Yes,.¦No,n't.¦,¦, I have

```

If so then save the appropriate answer.

```
⟦∨§θΣι.i na'i

```

Otherwise, output the saved answer, or the impossible answer if one wasn't saved.

# Answer
> 2 votes
# 05AB1E, (68 bytes) 107 bytesUTF-8

† Since the challenge states the answers should be counted in UTF-8 bytes for some reason.. -\_-

```
|ηʒθ'hÅ?}ε€#R.¡θ}н€н€θDgi".i na'i"ëJ…dptQi“Yes, I€¡.“ë“No, I€¡€–.“]»

```

Try it online.

**Explanation:**

```
|                           # Get all inputs as a list of strings
 η                          # Pop and push its prefixes
  ʒ     }                   # Filter this list of prefixes, keeping those where:
   θ                        #  The last string of the prefix
      Å?                    #  ends with
    'h                     '#  an "h"
ε                           # Map over each prefix ending with "haveYouStopped"
 €#                         #  Split each inner string by spaces
   R                        #  Reverse this list of pairs
    .¡ }                    #  Then group it by:
      θ                     #   The last item of the pair (the numbers)
        н                   #  Keep the first group (of the reversed list)
 €н                         #  Keep the strings of each inner pair
   €θ                       #  Keep the last letter of each string
     Dg                     #  Duplicate, pop and push the amount of characters in this list
       i                    #  If this length is 1 (thus only "haveYouStopped"):
        ".i na'i"           #   Push string ".i na'i"
       ë                    #  Else:
        J                   #   Join the list of 2 or 3 characters to a string
         …dptQi             #   If it's equal to "dpt" (thus "haveYouStopped,stop,start"):
               “Yes, I€¡.“  #    Push dictionary string "Yes, I have."
              ë             #   Else:
               “No, I€¡€–.“ #    Push dictionary string "No, I have not."
]                           # Close both if-else statements and map
 »                          # Join the list of strings by newlines
                            # (after which it is output implicitly with additional trailing newline)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“Yes, I€¡.“` is `"Yes, I have."` and `“No, I€¡€–.“` is `"No, I have not."`.

# Answer
> 2 votes
# Scala 3, 255 bytes

255 bytes. It can be golfed much more.

---

Golfed version. Attempt This Online!

```
def p(t:String,d:Map[String,String]=Map[String,String]()):Unit={t.split("\n").filterNot(_.isEmpty).foreach{l=>val Array(c,v)=l.split(" ");if(c.contains("s"))d(v)=if(c.contains("p"))"Yes, I have."else"No, I haven't."else println(d.getOrElse(v,".i na'i"))}}

```

Ungolfed version. Attempt This Online!

```
object Main {
  import scala.io.Source
  import scala.collection.mutable

  def processText(text: String, dict: mutable.Map[String, String] = mutable.Map[String, String]()): Unit = {
    val lines = text.split("\n").filterNot(_.isEmpty)
    for (line <- lines) {
      val Array(command, value) = line.split(" ")
      if (command.contains("s")) {
        dict(value) = if (command.contains("p")) "Yes, I have." else "No, I haven't."
      }
      else {
        println(dict.getOrElse(value, ".i na'i"))
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val text =
      """
        |start 1
        |haveYouStopped 1
      """.stripMargin
    processText(text)
  }
}

```

# Answer
> 0 votes
## Python, ~~160~~ 158 bytes

```
def d(t,i={}):
 for l in t.strip().split("\n"):
  c,v=l.split()
  if"s"in c:i[v]="Yes, I have."if"p"in c else"No, I haven't."
  else:print(i.get(v,".i na'i"))

```

-2 thanks to UndoneStudios

(Assumes that you are referring to taking input as a newline-delimited string)

### Ungolfed version

```
def decode(text):
    data = {}
    for line in text.strip().split("\n"):
        command, value = line.split()
        if "s" in command:
            data[value] = "Yes, I have." if "p" in command else "No, I haven't."
        else:
            print(data.get(v, ".i na'i"))

```

---
Tags: code-golf
---


title: Get the Systematic Chemical Symbol

text:
# Question
Title: Get the Systematic Chemical Symbol
### Background

The systematic chemical symbol is defined as such for \\$ 118 \< n \< 1000 \\$:

* The first letter corresponds to the first digit, capitalized.
* The second letter corresponds to the second digit.
* The third letter corresponds to the third digit.

This can be generalized for all \\$ n \> 0\\$:

* For each digit, get the corresponding letter.
* Capitalize the first character.

### Task

Write a function or full program that takes an integer or a list of digits \\$n \> 0\\$ and returns or prints the corresponding systematic chemical symbol.

```
Digit | Letter
--------------
0     | n
1     | u
2     | b
3     | t
4     | q
5     | p
6     | h
7     | s
8     | o
9     | e

```

This is , so ***shortest code wins.***

### Test Cases

```
In - Out
----------
119 - Uue
120 - Ubn
123 - Ubt
999 - Eee
6859 - Hope
1 - U
92 - Eb
987654321 - Eoshpqtbu
1010101 - Unununu

```

# Answer
> 8 votes
# 05AB1E, 13 bytes

Input is a list of digits.

```
.•*Š"—Êo•sèJ™

```

Try it online! or Try all cases!

**Commented:**

```
.•*Š"—Êo•      # compressed alphabet string "nubtqphsoe"
         s     # swap to implicit input
          è    # index each digit into the string
           J   # join into a single string
            ™  # apply title case

```

See the step-by-step output here.

---

Lyxal has suggested another 13-byter with a nicer input format:

```
.•*Š"—Êo•ÅвJ™

```

Try it online!

This uses `Åв`, which converts the input integer into the custom base defined by the string.

# Answer
> 7 votes
# Haskell, 43 bytes

```
f(h:t)="NUBTQPHSOE"!!h:map("nubtqphsoe"!!)t

```

Try it online!

Input is a list of digits. Yes, the code really just writes out the string once in uppercase and a second time in lowercase. This kludge seems shorter than other things I tried. Haskell without imports doesn't have built-ins to capitalize and is really clumsy in working with characters.

**43 bytes**

```
zipWith(!!)$"NUBTQPHSOE":repeat"nubtqphsoe"

```

Try it online!

Taking Lynn's solution and making it more boring. We can also write:

**43 bytes**

```
zipWith(!!)$"NUBTQPHSOE":l
l="nubtqphsoe":l

```

Try it online!

**47 bytes**

```
(%0)
(h:t)%i=["NUBTQPHSOE"!!h..]!!i:t%32
_%_=""

```

Try it online!

Based off Lynn's solution. Handles the capitalization by passing in an offset `i` of 0 initially, then updating it to 32 in each recursive function call.

It doesn't seem like Haskell has a nice function to title-case a string even with imports, which are probably too lengthy anyway to be competitive. The below with `Data.Text` doesn't work because it operates on `Text` not `[Char]`. `Data.Char` only has `toUpper` to capitalize a single character.

*44 bytes (non-working)*

```
import Data.Text
toTitle.map("NUBTQPHSOE"!!)

```

Try it online!

# Answer
> 6 votes
# Jelly, 15 bytes

```
ị“ubtqphsoen”Œt

```

Try it online!

Inputs as a list of digits, which the Footer does for you.

As it appears the string can't be compressed, this is likely to be the shortest approach in Jelly

## How it works

```
ị“ubtqphsoen”Œt - Main link. Takes a list l on the left
 “ubtqphsoen”   - Yield the string “ubtqphsoen”
ị               - For each digit in l, index into the string (1-indexing)
             Œt - Title case (capitalise the first character)

```

# Answer
> 6 votes
# , ~~80~~ ~~72~~ 56 bytes

-8 bytes thanks to Kirill L.

-16 bytes thanks to Giuseppe.

```
sub("(.)","\\U\\1",chartr("0-9","nubtqphsoe",scan()),,T)

```

Try it online!

First we translate the digits to the relevant letters thanks to `chartr`, then `sub` switches the first letter to upper case. This last part is possible thanks to the option `perl = T`, a nice trick found by Giuseppe.

Also, note that all the functions are vectorized the way we need them to be, so we can handle several inputs at a time, which is rather unusual in R golf with `scan()`.

# Answer
> 5 votes
# Japt, ~~17~~ 16 bytes

Input as a digit array, output as a character array.

```
mg`eo¢pqt¿n`w)vu

```

Try it

```
mg`...`w)vu     :Implicit input of digit array
m               :Map
 g              :  Index (0-based) into
  `...`         :    Compressed string "eoshpqtbun"
       w        :    Reversed
        )       :End map
         v      :Modify first element
          u     :  Uppercase

```

# Answer
> 5 votes
# Charcoal, ~~20~~ 18 bytes

```
⭆⍘Ｎnubtqphsoe⎇κι↥ι

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @Lyxal's comment on @ovs's answer. Explanation:

```
  Ｎ                 Input number
 ⍘                  Custom base conversion using
   nubtqphsoe       Literal string
⭆                   Map over characters
              κ     Current index
             ⎇      If not first character then
               ι    Current character
                ↥ι  Else uppercased character
                    Implicitly print

```

# Answer
> 5 votes
# Haskell, 48 bytes

```
zipWith(\i d->["NUBTQPHSOE"!!d..]!!i)$0:k
k=32:k

```

Try it online!

# Answer
> 5 votes
# Husk, <sup>~~20~~</sup> 17 bytes

```
§:oa←tm!¨Ḃ+q²"ṗen

```

Try it online!

input as a list of digits.

There's probably a better way to do the titlecasing part.

-3 bytes from Dominic van Essen.

## Explanation (old)

```
§:oa←tmo!¨nḂ+q²"ṗe¨→
                   → increment input to accomodate 0-indexing
      mo             map each digit to
        !¨nḂ+q²"ṗe¨  it's index value in the compressed string
§:                   join the
  oa←                first letter uppercased
     t               with it's tail

```

# Answer
> 4 votes
# Python 3, 51 bytes

```
lambda a:"".join("nubtqphsoe"[x]for x in a).title()

```

Try it online!

---

# Proton, 42 bytes

```
a=>"".join("nubtqphsoe"[x]for x:a).title()

```

Try it online!

# Answer
> 4 votes
# C (gcc), ~~51~~ 49 bytes

Apparently I can get rid of the customary "assign to first parameter" because I only care about a false/non-false answer from this function. Interesting to know!

```
f(n){n&&putchar("nubtqphsoe"[n%10]^32*!f(n/10));}

```

Try it online!

# Answer
> 4 votes
# Ruby `-nl`, 37 bytes

```
p$_.tr("0-9","nubtqphsoe").capitalize

```

Try it online!

# Answer
> 4 votes
# Perl 5, 27 bytes

```
y/0-9/nubtqphsoe/;$_="\u$_"

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 54 bytes

Expects an array of digits.

```
a=>a.map((c,i)=>"nNuUbBtTqQpPhHsSoOeE"[c*2+!i]).join``

```

Try it online!

# Answer
> 4 votes
# Vyxal, ~~11~~ 10 bytes

```
«/
∨+Ċ≤«βǐ

```

Try it Online!

I finally turned my suggested 13 byte 05AB1E answer into a Vyxal answer.

## Explained

```
«...«βǐ
«...«    # the string "nubtqphsoe"
     β   # convert the input to bijective-base 10 using the above string as the alphabet
      ǐ  # titlecase that result

```

# Answer
> 3 votes
# Retina 0.8.2, 26 bytes

```
T`d`nubtq\p\hs\oe
T`l`L`^.

```

Try it online! Link includes test cases. Explanation:

```
T`d`nubtq\p\hs\oe

```

Translate each digit to the appropriate letter. The letters `h`, `o` and `p` have special meaning, so they need to be quoted.

```
T`l`L`^.

```

Translate the first letter to upper case.

# Answer
> 3 votes
# GolfScript, ~~31~~ ~~29~~ 28 bytes

```
~{"nubtqphsoe"1/=}%()[32-]|\

```

Try it online!

Input as a digit array.

```
~                             # Parse the input to an array         [6 8 5 9]
 {               }%           # For each digit
  "nubtqphsoe"1/              # Split each letter of this string    6 ["n" "u" ... "e"]
                =             # Get the corresponding letter        "h"
                   (          # Get the first letter                ["o" "p" "e"] "h"
                    )         # Get the ascii value                 ["o" "p" "e"] "" 104
                      32-     # Subtract 32                         ["o" "p" "e"] "" 72
                     [   ]    # Put it in an array                  ["o" "p" "e"] "" [72]
                          |   # Convert to ascii                    ["o" "p" "e"] "H"
                           \  # Swap the two elements in the stack  "H" ["o" "p" "e"]
                              # Only the strings are outputted      "Hope"

```

# Answer
> 3 votes
# APL+WIN, 39 bytes

Prompts for a character vector of digits with index origin = 0

```
⎕av[(↑n),32+1↓n←⎕av⍳'NUBTQPHSOE'[⍎¨⍕⎕]]

```

Explanation:

```
[⍎¨⍕⎕]] Convert input to individual digits

⎕av⍳'NUBTQPHSOE' Find index positions of all upper case characters in atomic vector
and use result above to select those according to input

(↑n),32+1↓n Concatenate first index to remaining indices + 32 to apply appropriate case

⎕av[...] Use the above indices to select required characters from atomic vector

```

# Answer
> 3 votes
# x86 machine code (MS-DOS .COM format), ~~35~~ 33 bytes

The program will terminate at the end of input from the command line.

For fun, I decided to use `XLAT` to index each digit's representation as the translation array easily fits into an 8-bit index and everything is 1:1.

Byte representation:

```
0000    B4 20 BB 19 01 BE 82 00 AC 2C 0D 74 09 D7 32 C4
0010    CD 29 32 E4 EB F0 C3 6E 75 62 74 71 70 68 73 6F
0020    65

```

Assembly code (TASM):

```
IDEAL

MODEL TINY
CODESEG
ORG 100H

SYMS_M EQU OFFSET SYMS-23H

MAIN:
    MOV AH,20H
    MOV BX,SYMS_M
    MOV SI,82H
VAL:
    LODSB
    SUB AL,0DH
    JZ  QUIT
    XLATB
    XOR AL,AH
    INT 29H
    XOR AH,AH
    JMP VAL
QUIT:
    RET

SYMS DB "nubtqphsoe"

END MAIN
ENDS

```

# Answer
> 3 votes
# Scala, ~~47~~ 40 bytes

```
_+""map(d=>"nubtqphsoe"(d-48))capitalize

```

Try it online!

* -7 Thanks to user!

# Answer
> 3 votes
# Befunge-93, 105 bytes

Terrible implementation, it works at least, input is each digit of the number then any other character to terminate. Feel free to suggest any optimisations.

```
~::68*`vnubtqphsoe
 v+4*96_@
 `
@_68*8--0 v
   v        <
v:~<,-*84g<
>:68*` v
 v+4*96_@
 `
@_68*8--0 g,^

```

Try it online!

# Answer
> 3 votes
# Zsh, 29 bytes

```
<<<${(C)$(tr 0-9 nubtqphsoe)}

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~63~~ 60 bytes

Saved 3 bytes thanks to AZTECCO!!!

```
f(a,l)int*a;{l--&&f(a,l)+putchar("nubtqphsoe"[a[l]]-!l*32);}

```

Try it online!

Inputs a pointer to an array of digits and its length (since there's no way to know how long an array passed into a function as a pointer is in C) and prints the corresponding systematic chemical symbol.

# Answer
> 2 votes
# JavaScript, ~~264~~ ~~157~~ ~~150~~ 100 bytes

-107 bytes by replacing `if` statements with a JavaScript object to match each number with a corresponding string.

-7 bytes by using ES6 `for` loop through a string, and shorter arrow functions.

-50 bytes by replacing JavaScript Object with ES6 string indexing.

```
a='';o='nubtqphsoe';x=c=>a+=o[c];for(let e of prompt())x(e);alert(a[0].toUpperCase()+a.substring(1))
```

# Answer
> 2 votes
# Pyth, 41 bytes

```
V.T,.T]."buÞ“;UØ".T]."09I–Ò"=:zeNhN;rz3

```

Try it online!

## Explanation

The main part of the program is `.T,.T]."buÞ“;UØ".T]."09I–Ò"`, which returns the list `[['u', '1'], ['b', '2'], ['t', '3'], ..., ['n', '0']]`. `."buÞ“;UØ"` is the packed string `ubtqphsoen`, and `."09I–Ò"` is the packed string `1234567890`. `.T]` splits them into characters, and `.T,` zips them together.

# Pyth, 24 bytes

```
Vz=+k@."bu\nL‘"vN;rk3

```

Try it online!

This one is a port of HyperNeutrino's Python 3 answer.

# Answer
> 2 votes
# CJam, 24 bytes

```
q~{"nubtqphsoe"1/=}%(eu\

```

Try it online!

Input in the form of a digit array string.

# Answer
> 2 votes
# Raku, 29 bytes

```
*.trans(^10=>'nubtqphsoe').tc

```

Try it online!

# Answer
> 2 votes
# PowerShell, ~~142~~ ~~100~~ 94 bytes

```
$k=[string]$args;0..9|%{$k=$k.replace([string]$_,'nubtqphsoe'[$_])};get-culture|% t*o|% *se $k

```

Try it online!

# Answer
> 1 votes
# Lexurgy, 101 bytes

Map a digit to its respective letter.

```
Class D {\0,\1,\2,\3,\4,\5,\6,\7,\8,\9}
a:
@D=>{N,U,B,T,Q,P,H,S,O,E}/$ _
@D=>{n,u,b,t,q,p,h,s,o,e}

```

# Answer
> 1 votes
## bash + coreutils, ~~40~~ 37 bytes

```
c=`tr 0-9 nubtqphsoe<<<$1`
echo ${c^}

```

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


title: Get the Bible verse

text:
# Question
Title: Get the Bible verse
Write a program that accesses Project Gutenberg's KJV Bible, either from a file called `pg10.txt` in the working directory or in any other way that is typical for the language, takes a Bible verse reference as input, and prints the corresponding verse, with no newlines except optionally one at the end, as output.

The standard format for a reference is `[book] [chapter]:[verse]`, e.g. `John 3:13`. However, some books have only one chapter. For these books, the format is `[book] [verse]`, e.g. `Jude 2`. Your program must accept this format for single-chapter books. Behavior when using the standard format with single-chapter books, or when using the single-chapter format with multi-chapter books, is undefined.

Note that the "title" for the book of Psalms, for the purposes of this question, is `Psalm`, not `Psalms`, because references are usually written like `Psalm 119:11`, not `Psalms 119:11`.

Use the following titles for books of the Bible. Single-chapter books are in *italics*.

* Genesis
* Exodus
* Leviticus
* Numbers
* Deuteronomy
* Joshua
* Judges
* Ruth
* 1 Samuel
* 2 Samuel
* 1 Kings
* 2 Kings
* 1 Chronicles
* 2 Chronicles
* Ezra
* Nehemiah
* Esther
* Job
* Psalm
* Proverbs
* Ecclesiastes
* Song of Solomon
* Isaiah
* Jeremiah
* Lamentations
* Ezekiel
* Daniel
* Hosea
* Joel
* Amos
* *Obadiah*
* Jonah
* Micah
* Nahum
* Habakkuk
* Zephaniah
* Haggai
* Zechariah
* Malachi
* Matthew
* Mark
* Luke
* John
* Acts
* Romans
* 1 Corinthians
* 2 Corinthians
* Galatians
* Ephesians
* Philippians
* Colossians
* 1 Thessalonians
* 2 Thessalonians
* 1 Timothy
* 2 Timothy
* Titus
* *Philemon*
* Hebrews
* James
* 1 Peter
* 2 Peter
* 1 John
* *2 John*
* *3 John*
* *Jude*
* Revelation

| Reference | Text |
| --- | --- |
| Genesis 1:1 | In the beginning God created the heaven and the earth. |
| 1 Samuel 1:1 | Now there was a certain man of Ramathaimzophim, of mount Ephraim, and his name was Elkanah, the son of Jeroham, the son of Elihu, the son of Tohu, the son of Zuph, an Ephrathite: |
| 1 Kings 1:1 | Now king David was old and stricken in years; and they covered him with clothes, but he gat no heat. |
| Psalm 119:11 | Thy word have I hid in mine heart, that I might not sin against thee. |
| John 3:16 | For God so loved the world, that he gave his only begotten Son, that whosoever believeth in him should not perish, but have everlasting life. |
| 1 John 1:9 | If we confess our sins, he is faithful and just to forgive us our sins, and to cleanse us from all unrighteousness. |
| 3 John 1 | The elder unto the wellbeloved Gaius, whom I love in the truth. |
| Jude 21 | Keep yourselves in the love of God, looking for the mercy of our Lord Jesus Christ unto eternal life. |
| Revelation 21:11 | Having the glory of God: and her light was like unto a stone most precious, even like a jasper stone, clear as crystal; |
| Revelation 21:16 | And the city lieth foursquare, and the length is as large as the breadth: and he measured the city with the reed, twelve thousand furlongs. The length and the breadth and the height of it are equal. |
| Revelation 22:20 | He which testifieth these things saith, Surely I come quickly. Amen. Even so, come, Lord Jesus. |
| Revelation 22:21 | The grace of our Lord Jesus Christ be with you all. Amen. |

# Answer
# GNU sed `-En`:  ~~330 321 303 298~~  283 bytes

The reference is given in the first line. In real life you can do this like `sed 'the script' <<(echo Luke 19:10;cat pg10.txt)`

```
1{s/^([123]) /\1/;s/.* S/S/;/:/!s/ / 1:/;h}
/\n/!N;N;/^.{5}$/!D;n;n;s/\r//;/Bi/D
/Ac|La|Re/s/ of.*//
s/The Fi/1/;s/The Se/2/;s/The Th/3/;s/^[123].*M//
s/[^0-9]* //;s/ms$/m/;G;/^(..*)\n\1/!d
:1
n;G;/(.*:.*) .*\n.* \1$/!b1
s/\n.*//;s/.*[0-9]:\S* //
:2
N;/ *[0-9]*[:*]\S.*/!b2
s///;s/\r\n/ /gp

```

**Explanation:** The first line forms the given verse to remove the whitespace after a number, rename the Song of Salomon and add `1:` for one-chapter books; this gets saved in the hold space. The second line finds book titles, the following three convert them to a canonical form and check for a match with the given verse. The rest of the script search for the exact verse inside the book and strip it to only that verse.

This was the original POSIX `sed -n` version with 298 bytes:

```
1{s/^\([123]\) /\1/;s/.* S/S/;/:/!s/ / 1:/;h;}
/\n/!N;N;/^.....$/!D;n;n;s/^M//;/Bi/D
/[ALR][cae]/s/ of.*//
s/The F/1/;s/The Se/2/;s/The T/3/;s/^[123].*M//
s/[^0-9]* //;s/ms$/m/;G;/^\(..*\)\n\1/!d
:1
n;G;/\(.*:.*\) .*\n.* \1$/!b1
s/\n.*//;s/.*[0-9]:[^ ]* //
:2
N;/ *[0-9]*[:*][^ ].*/!b2
s///;s/^M\n/ /g;p

```
> 5 votes

# Answer
# JavaScript (ES6), 216 bytes

Expects `(text)(reference)`.

```
t=>s=>([,s,v]=s[M='match'](/(.+) (.+)/),t.split(/\*+|[\r\n]{10}/)[(n=t.split`
`.findIndex(r=>r[M](s.replace(/\d/,n=>` ${"_FST"[n]}.* .*`))))?n-21:64]+0)[M]((v[1]?v:"1:"+v)+"([^]*?)\\d")[1].trim().replace(/\r\n/g," ")

```

Try it online!

(The TIO code works on a small extract of the original file.)

### Method

1. We compute the book number by looking for the line containing the book name in the summary. There's a special case for *James* which appears on the very first line of the file. We also have to be careful about the misalignment between *Malachi* and *Matthew*.
2. We split the text and extract the relevant book.
3. We look for the requested verse in this book and format it.

### Commented

```
t =>                    // t = input text
s =>                    // s = reference
(                       //
  [, s, v] = s.match(   // split s into:
    /(.+) (.+)/         //   s = book name
  ),                    //   v = "chapter:verse" or just "verse"
  t.split(              // turn t into an array of books
    /\*+|[\r\n]{10}/    // by splitting on "***" or "\r\n" * 5
  )[(                   //
    n = t.split`\n`     // split t on new lines
      .findIndex(r =>   // and find the first string r
        r.match(        //   which contains:
          s.replace(    //     the book name
            /\d/, n =>  //       with the leading digit (if any)
            " " +       //       replaced with a space
            "_FST"[n] + //       followed by "F", "S" or "T"
                        //       (for "First", "Second", "Third")
            ".* .*"     //       followed by ".* .*"
          )             //     end of replace()
        )               //   end of match()
      )                 // end of findIndex()
  ) ?                   // if n is not 0:
    n - 21              //   use n - 21
  :                     // else:
    64                  //   use 64 for "James"
  ] + 0                 // get the n-th book and append a "0"
).match(                // then find:
  (v[1] ? v : "1:" + v) //   the verse header,
  + "([^]*?)"           //   followed by the verse content,
  + "\\d"               //   followed by a trailing digit
)[1]                    // end of match(); keep the content
.trim()                 // trim it
.replace(/\r\n/g, " ")  // and turn line breaks into spaces

```
> 4 votes

# Answer
# Jelly, ~~80~~ \# Jelly, 66 bytes

```
ḢfØDV+2ị=”JƲo1
Ḳ-ị⁹œṣ⁷x5¤¤ỴḢwɗƇị@Ç{ỴKḲ<”AȦ$€œṗ$Ḣ⁼¥ƇḲṪ¹⁾1:;$f?”:ʋḢK

```

Try it online!

A pair of links that is called as a dyad and that takes the pg10.txt file as its right argument and the required biblical reference as its left argument. TIO fails with the full document (presumably because the POST exceeds the maximum size), and the links to TIO on CGCC are even more limited because of length. However, it should work with the full text if run locally.

Pleasingly now code length in bytes == number of books in bible.

## Explanation (outdated)

```
ḢfØDV+2ị=”JƲo1                                          # Helper link: Takes a bible reference and returns which number book should be used that matches the textual part of the reference; half the code is to handle the John letters
Ḣ                                                       # Head
 fØD                                                    # Keep only digits
    V                                                   # Evaluate (will be 0 if no digits)
     +     Ʋ                                            # Add the result of the following, applied to the helper link's original argument
      2ị=”J                                             # - 1 if the second remaining character is a J, otherwise 0
            o1                                          # Or 1 (replaces 0s with ones)

Ḳ-ị⁹œṣ”¶x5¤¤Ỵ€¤Ḣw¥Ƈị@Ç{KœṣḲṪ¹⁾1:;$f?”:ʋ2ịwⱮØD;€”:¤œPƊḢḊ # Main link: takes a bible reference as its argument and returns the verse
Ḳ                                                       # Split at spaces
 -ị                                                     # Penultimate part (will be the last word of the book title)
   ⁹          ¤                                         # Using the following applied to the right argument:
    œṣ”¶x5¤¤                                            # - Split at five consecutive newlines
            Ỵ€                                          # - Split each at newlines
               Ḣw¥Ƈ                                     # Keep those where the first line includes the book title word from earlier
                   ị@Ç{                                 # Index into this using the result of calling the helper link on the original reference (so returning a single book)
                       K                                # Join with spaces
                        œṣ            Ʋ                 # Split at the substring determined by calling following on the original reference:
                          Ḳ                             # - Split at spaces
                           Ṫ                            # - Tail (i.e. the verse or chapter:verse)
                                  f?”:                  # - If contains a colon:
                            ¹                           #   - Leave as is
                             ⁾1:;$                      #   - Else: prepend "1:"
                                       2ị               # Take the second part (i.e. the bit immediately after the chapter:verse reference)
                                                    Ɗ   # Following as a monad:
                                         wⱮØD;€”:¤      # - Find the position of every sublist that comprises of a digit followed by a colon
                                                  œP    # - And split at these
                                                     ḢḊ # Take the first remaining part, and then remove the first character (which will be the space left just after the original chapter:verse marker)

```

Created with the help of Luminespire.
> 4 votes

---
Tags: code-golf
---


# Question
Title: Reverse the polyglot, change the language
# Task

Write a polyglot in two languages that when run, outputs the name of the language it is run in. Additionally, this program must *also* output the **other** language's name if the source code is reversed

# Example:

Program `ABC` in language `foo` outputs `foo`. `ABC` in language `bar` outputs `bar`. `CBA` in language `foo` outputs `bar`, and `CBA` in language `bar` outputs `foo`.

This is code-golf, so the shortest code wins

# Answer
# JavaScript, HTML, 68 bytes

|  | HTML | JavaScript |
| --- | --- | --- |
| Normal | ``` <!---->HTML<!--!<tpircSavaJ>-- alert`JavaScript`//`LMTH`trela <!--!< ``` | ``` <!---->HTML<!--!<tpircSavaJ>-- alert`JavaScript`//`LMTH`trela <!--!< ``` |
| Reversed | ``` <!--!< alert`HTML`//`tpircSavaJ`trela -->JavaScript<!--!<LMTH>----!< ``` | ``` <!--!< alert`HTML`//`tpircSavaJ`trela -->JavaScript<!--!<LMTH>----!< ``` |

JavaScript is a strange language that support 5 kinds of comment and 5 kinds of link breaks.

Comment:

* Multi line comment `/* ... */` Ref
* Single line comment `// ...` Ref
* Hashbang comment `#! ...` Ref
    + Must at the beginning of source code
    + Some script host support an extra BOM in front of hashbang
* Single line HTML open comment `<!-- ...` Ref
* Single line HTML close comment `--> ...` Ref

Line breaks: Ref

* `<LF>`
* `<CR>`
* `<LS>`
* `<PS>`
* `<CR>` `<LF>`
> 16 votes

# Answer
# Python + \>\<\>, 49 bytes

```
#o<"><>"
print("python")#)"><>"(tnirp
"nohtyp"<o#

```

**Try it**:
> 14 votes

# Answer
# Java and Whitespace, 175 bytes

```
v->"Java"//"ecapsetihW">-vSSTTN
SSTTTN
SSTTSTN
SSSTSTSN
SSSTTSTN
SSTTN
SSSTTTSN
SSSTTN
SSSTSN
SSTTTTTN
N
SSN
SSSTTSSTTSN
TSSSTN
SSN
SN
N
N
N
SN
SSN
TSSSTN
SSSSSTTSSSN
SSN
N
STTSTTSSN
TSSSN
STTSTSSSN
TSSS

```

Above, the spaces, tabs, and newlines are indicated with `S`; `T`; and `N` respectively for readability only. The TIO-links below contain the actual spaces/tabs/newlines.

**Explanation:**

*In Java:*

```
v->                        // Method with empty unused parameter & String return-type
   "Java"                  //  Return "Java"
         //"ecapsetihW">-v //  No-op comment
                           //  No-op spaces/tabs/newlines

```

*In Java reversed:*

```
                           // No-op spaces/tabs/newlines
v->                        // Method with empty unused parameter & String return-type
   "Whitespace"            //  Return "Whitespace"
               //"avaJ">-v //  No-op comment

```

*In Whitespace:*

```
v->"Java"//"ecapsetihW">-v // No-ops
SSTTN                      // Push -1 (e)
SSTTTN                     // Push -3 (c)
SSTTSTN                    // Push -5 (a)
SSSTSTSN                   // Push 10 (p)
SSSTTSTN                   // Push 13 (s)
SSTTN                      // Push -1 (e)
SSSTTTSN                   // Push 14 (t)
SSSTTN                     // Push 3 (i)
SSSTSN                     // Push 2 (h)
SSTTTTTN                   // Push -15 (W)
NSSN                       // Create Label LOOP
 SSSTTSSTTSN               //  Push 102
 TSSS                      //  Add the top two integers together
                           //  (which will implicitly stop the program with an error if
                           //  there is just a single value on the stack)
 TNSS                      //  Print the top as character to STDOUT
 NSNN                      //  Jump to Label LOOP
NNSNSSNTSSSTNSSSSSTTSSSNSSNNSTTSTTSSNTSSSNSTTSTSSSNTSSS
                           // No-op whitespaces

```

*In Whitespace reversed:*

```
SSSTN                      // Push 1 (a)
SSSTSTTSN                  // Push 22 (v)
SSSTN                      // Push 1 (a)
SSTTSTTSN                  // Push -22 (J)
NSSN                       // Create Label LOOP
 SSSTTSSSSSN               //  Push 96
 TSSS                      //  Add the top two integers together
                           //  (which will implicitly stop the program with an error if
                           //  there is just a single value on the stack)
 TNSS                      //  Print the top as character to STDOUT
 NSNN                      //  Jump to Label LOOP
NNSNSSNTSSSTNSTTSSTTSSSNSSNNTTTTTSSNSTSSSNTTSSSNSTTTSSSNTTSSNTSTTSSSNSTSTSSSNTSTTSSNTTTSSNTTSS
                           // No-op whitespaces
v->"Whitespace"//"avaJ">-v // No-ops

```

The constants `102` and `96` are generated by this Java program based on this Whitespace tip of mine.
> 12 votes

# Answer
# 05AB1E and , 15 bytes

```
"Y"gxg"E1BA50"R

```

**Explanation:**

*In 05AB1E:*

```
"Y"              # Push string "Y"
                 #  STACK: "Y"
   g             # Pop and push its length
                 #  STACK: 1
    x            # Double it (without popping)
                 #  STACK: 1,2
     g           # Pop and push its length
                 #  STACK: 1,1
      "E1BA50"   # Push string "E1BA50"
                 #  STACK: 1,1,"E1BA50"
              R  # Reverse it
                 #  STACK: 1,1,"05AB1E"
                 # (after which the top of the stack is output implicitly)

```

*In 05AB1E reversed:*

```
R                # Reverse (without input, it'll push an empty string)
                 #  STACK: ""
 "05AB1E"        # Push string "05AB1E"
                 #  STACK: "","05AB1E"
         g       # Pop and push its length
                 #  STACK: "",6
          x      # Double it (without popping)
                 #  STACK: "",6,12
           g     # Pop and push its length
                 #  STACK: "",6,2
            "Y"  # Push string "Y"
                 #  STACK: "",6,2,"Y"
                 # (after which the top of the stack is output implicitly)

```

*In Y:*

```
"Y"              # Push string "Y"
   g             # Pop and print it
    x            # Stop the program
     g"E1BA50"R  # No-ops

```

*In Y reversed:*

```
R                # No-op character
 "05AB1E"        # Push string "05AB1E"
         g       # Pop and print it
          x      # Stop the program
           g"Y"  # No-ops

```
> 11 votes

# Answer
# Python + Javascript(Node.js) 150 bytes

Uses the differences between javascript objects and python dicts to change code passed to `eval` in both languages. Uses both quoting styles with escaping to evaluate different code when reversed

```
"'\",)]'0'[}')'\nohtyP'\(gol.elosnoc':0,')'\tpircsavaJ'\(tnirp':'0'{(lave,'",eval({"0":"print(\"Python\")",0:"console.log(\"Javascript\")"}["0"]),'\"'

```

Python normal

Javascript normal

Python reversed

Javascript reversed
> 9 votes

# Answer
# C/C++, 119 bytes

```
#include<stdio.h>//
int main(){puts(sizeof!0-1?"C":"C++");}//};)"++C+0\C0"+0!foezis(stup{)(niam tni
//>h.oidts<edulcni#

```

Try it online!

Reference

Old: C/C++, 167 bytes

```
#include<stdio.h>//
int main(){puts("C"//
#ifdef __cplusplus//
"++"//
#endif//
);}//};)
//fidne#
//"++"
//sulpsulpc__ fednfi#
//"C"(stup{)(niam tni
//>h.oidts<edulcni#

```

Try it online!

~~Not that elegant due to `#ifdef` but resolving it also save bytes~~ done
> 8 votes

# Answer
# PHP Perl 4 or 5, ~~45~~ ~~43~~ 41 bytes

```
print-true?php:perl;#;php:lrep?eurt-tnirp

```

Try it online PHP

Try it online Perl

A simple take at it, I assumed it was not mandatory to specify the Perl version as it is not a polyglot between different versions of perl (though I could do one). Works in Perl 4 or 5

Takes advantage of the fact that PHP converts `true` to `1` for numerical operations while Perl 4/5 ignores it

EDIT: saved 2 bytes by removing `1`, `-true` is enough (with swaped languages names)

EDIT 2: thanks to Neil for saving another 2 bytes removing the spaces
> 7 votes

# Answer
# C and Python, ~~163~~ 119 bytes

```
p=0//1;print("Python")#//#
#define p;main(){puts("C");}//#
p
#//};)"nohtyP"(stup{)(niam;p enifed#
#//#)"C"(tnirp;1//0=p

```

Try it online!

---

###### `warning`-less & C`99` compliant version, 235 bytes

```

#include<stdio.h>//#
#define p int main(void){puts("C");}//#
#if 0//fidne#
print("Python");p=0//1#//#
#endif//0 fi#
p
#if 0//fidne#
#//#1//0=p;)"C"(tnirp
#endif//0 fi#
#//};)"nohtyP"(stup{)diov(niam tni p enifed#
#//>h.oidts<edulcni#

```

Try it online!

Turns out, since C99, `main()` does implicitly `return 0` which indicates successful termination. A single `#` (with optional whitespaces and/or comments after it) followed by a new line is also allowed; The standard calls it "Null directive".
> 6 votes

# Answer
# Python 3.8 (pre-release) \+ JavaScript (Node.js), 95 bytes

```
1//print("Python")#1//)"nohtyP"(gol.elosnoc
console.log("JavaScript")//1#)"tpircSavaJ"(tnirp//1

```

Try it online! (Python)

```
1//print("Python")#1//)"nohtyP"(gol.elosnoc
console.log("JavaScript")//1#)"tpircSavaJ"(tnirp//1

```

Try it online! (JavaScript)

The python programs error after printing
> 2 votes

# Answer
# dc and Fission, 35 bytes

```
[dc]P[;"cd"R"Fission";][[P]noissiF[

```

Try it online! `dc` in dc.

Try it online! `Fission` in Fission.

Try it online! `Fission` in dc reversed.

Try it online! `dc` in Fission reversed.

## Explanations

### dc → `dc`

```
[dc]P[;"cd"R"Fission";][[P]noissiF[
[dc]                                   push the string "dc"
    P                                  print without newline
     [;"cd"R"Fission";]                push the string (psuedo comment)
                       [               push the rest of the program as string (ditto)

```

### Fission → `Fission`

```
[dc]P[;"cd"R"Fission";][[P]noissiF[
           R                           start an atom going right
            "Fission"                  print "Fission" and set the atom's mass to 7
                     ;                 destroy the atom

```

### dc reversed → `Fission`

```
[Fission]P[[];"noissiF"R"dc";[P]cd[
[       ]                              push the string "Fission"
         P                             print without newline
          [                            push the rest of the program as string (psuedo comment)
                                       note that dc's [strings] nest
                                       and also doesn't complain with an unterminated string

```

### Fission reversed → `dc`

```
[Fission]P[[];"noissiF"R"dc";[P]cd[
                       R               start an atom going right
                        "dc"           print "dc" and set the atom's mass to 2
                            ;          destroy the atom

```
> 2 votes

# Answer
# Minecraft Function and C, 243 bytes

```
#include <stdio.h>//a fednu#
#define w int main(){printf("C");}//a fednu#
w
#undef a//>h.oidts< edulcni#
#undef a//};)"noitcnuF tfarceniM"(ftnirp{)(niam tni w enifed#
#if 0//fidne#
tellraw @a "Minecraft Function"#
#"C" a@ warllet
#endif//0 fi#

```

The C code is hidden behind preprocessor directives, which are interpreted as comments in the Minecraft function. The Minecraft code is hidden with `#if 0` and `#endif` which is completely skipped by the compiler.

The code is written symmetrically with appropriate comments to comment out the reversed version. `#undef a//` (a comment in Minecraft and a no-op in C) is used to hide the reversed code.

The `w`, which is interpreted in C as `int main(){printf("C");}`, is also a valid Minecraft command. It has the wrong number of arguments, which causes a silent error, but the rest of the function still runs.

Try It Online:

(Minecraft Function not available on TIO)
> 2 votes

# Answer
# Python, JavaScript (Node.js), 107 bytes

```
00000000: 2321 2f2f e280 a863 6f6e 736f 6c65 2e6c  #!//...console.l
00000010: 6f67 2822 4a61 7661 5363 7269 7074 2229  og("JavaScript")
00000020: 2f2f 2922 6e6f 6874 7950 2228 676f 6c2e  //)"nohtyP"(gol.
00000030: 656c 6f73 6e6f 63e2 80a8 3b60 230a 7072  elosnoc...;`#.pr
00000040: 696e 7428 2250 7974 686f 6e22 2923 2922  int("Python")#)"
00000050: 7470 6972 6353 6176 614a 2228 746e 6972  tpircSavaJ"(tnir
00000060: 700a 2360 e280 a82f 2f21 23              p.#`...//!#

```

No TIO link available...

All you need is comment out whatever you don't want...
> 1 votes

# Answer
# Vyxal \+ 05AB1E, 39 bytes

```
"‛₴ŀ,Q,`E1BA50``"i0"laxyV"}"05AB1E"0i0`

```

Vyxal code

Vyxal code reversed

05AB1E code

05AB1E code reversed
> 1 votes

# Answer
# Clip and Fission, 18 bytes

```
"Clip";"noissiF"L+

```

Try it online in Fission!

Try it online in Fission reversed!

No online link for Clip.

In Clip, most things after the first entity and its parameters recursively don't matter. (Some operators also wait for input, but not in this case.) Strings takes no parameters. `L` is an empty list. `+` is for concatenation.

In Fission, `L` emits an atom to the left and `;` destroys the atom. Strings in double quotes on the path of the atom are printed. It wraps around on the edges like most 2D languages.

# GolfScript and Fission, 25 bytes

```
"GolfScript"K}K"noissiF"L

```

Try it online in GolfScript!

Try it online in Fission!

Try it online in GolfScript reversed!

Try it online in Fission reversed!

In GolfScript, `K` is a no-op and `}` is a super comment.

In Fission, `K` works like `;` but also does something else that doesn't matter. Using `;` here would break GolfScript.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, source-layout, polyglot
---


# Question
Title: Shortest Algorithm* That Generates a Harlequin Pattern
What is the **shortest sequence** of moves that, from the solved state of the cube, creates a pattern that meets the following criteria:

* 6 colors on each face
* at most 2 facelets of the same color
* no adjacent facelets of the same color

EDIT: I made up the name of the pattern. I asked this question in 2018 on Mathematics Stack Exchange and forgot about it. Thanks to uhoh for suggesting Code Golf. Who knows when I would have discovered this awesome community!

---

* In the Rubik's world, an algorithm is a sequence of moves, like: L, R, U, D, F, B etc.

# Answer
# Seven Face Turns

```
U D2 F2 B2 R L U'

```

With yellow (Y) at the top, red (R) at the front and green (G) at the right (with their opposites white (W), orange (O), and blue (B) respectively) that produces the net:

```
      O R G
      W Y W
      B O R
W R Y O G B W O Y R B G
G B R Y R W B G O Y O W
O G B W G Y R B G W B Y
      O Y B
      R W O
      G Y R

```

Here is Python code that finds this solution.

**Try it online!**

```
from dataclasses import dataclass

# Move functions (not the nicest to read but they do the job)
def U(state):
    return [
        state[0][6:] + state[0][:6],
        state[2][:3] + state[1][3:],
        state[4][:3] + state[2][3:],
        state[3],
        state[5][:3] + state[4][3:],
        state[1][:3] + state[5][3:],
    ]

def F(state):
    return [
        state[0][:4] + state[5][2:5] + state[0][7:],
        state[1][6:] + state[1][:6],
        state[0][6:7] + state[2][1:6] + state[0][4:6],
        state[2][6:8] + state[2][:1] + state[3][3:],
        state[4],
        state[5][:2] + state[3][:3] + state[5][5:],
    ]

def R(state):
    return [
        state[0][:2] + state[1][2:5] + state[0][5:],
        state[1][:2] + state[3][2:5] + state[1][5:],
        state[2][6:] + state[2][:6],
        state[3][:2] + state[4][6:] + state[4][:1] + state[3][5:],
        state[0][4:5] + state[4][1:6] + state[0][2:4],
        state[5],
    ]

def D(state):
    return [
        state[0],
        state[1][:4] + state[5][4:7] + state[1][7:],
        state[2][:4] + state[1][4:7] + state[2][7:],
        state[3][6:] + state[3][:6],
        state[4][:4] + state[2][4:7] + state[4][7:],
        state[5][:4] + state[4][4:7] + state[5][7:],
    ]

def B(state):
    return [
        state[2][2:5] + state[0][3:],
        state[1],
        state[2][:2] + state[3][4:7] + state[2][5:],
        state[3][:4] + state[5][6:] + state[5][:1] + state[3][7:],
        state[4][6:] + state[4][:6],
        state[0][2:3] + state[5][1:6] + state[0][:2],
    ]

def L(state):
    return [
        state[4][4:5] + state[0][1:6] + state[4][2:4],
        state[0][:1] + state[1][1:6] + state[0][6:],
        state[2],
        state[1][:1] + state[3][1:6] + state[1][6:],
        state[4][:2] + state[3][6:] + state[3][:1] + state[4][5:],
        state[5][6:] + state[5][:6],
    ]

# Names of the move functions above, first anticlockwise around one corner - UFR
# then their opposing faces (clockwise around the opposite corner) - DBL
FACES = "UFRDBL"
N_FACE_PAIRS = len(FACES) // 2

MOVE_FUNCTIONS = [eval(f) for f in FACES]

ROTATION_INDICATORS = ("", "2", "'")
ROTATIONS = tuple(clockwise_quarters for clockwise_quarters, indicator in enumerate(ROTATION_INDICATORS, start=1))

FIRST_FACES_TO_TURN = (FACES.index("U"),)  # one choice up to symmetry (arbitrary)
SECOND_FACES_TO_TURN = (FACES.index("D"), FACES.index("F"))  # two choices up to symmetry (one opposite, one adjacent)

SOLVED_STATE = [[i] * 8 for i in range(len(FACES))]

def adjacent(face_1, face_2):
    return face_1 % N_FACE_PAIRS != face_2 % N_FACE_PAIRS

@dataclass()
class Move:
    face: int
    rotation: int

def gen_move_sequences(depth):
    if depth > 0:
        for move_sequence in gen_move_sequences(depth - 1):
            if len(move_sequence) > 1:
                faces = (f for f in range(len(FACES))
                         if f != move_sequence[-1].face
                         and (f != move_sequence[-2].face
                              or adjacent(move_sequence[-1].face, move_sequence[-2].face)
                              )
                         )
                turn_stop = 3
            elif len(move_sequence) == 1:
                faces = SECOND_FACES_TO_TURN
                turn_stop = 3
            else:
                faces = FIRST_FACES_TO_TURN
                turn_stop = 2
            for face in faces:
                for turn in ROTATIONS[:turn_stop]:
                    yield move_sequence + [Move(face, turn)]
    else:
        yield []

def get_state(move_sequence):
    v = SOLVED_STATE
    for m in move_sequence:
        for i in range(m.rotation):
            v = MOVE_FUNCTIONS[m.face](v)
    return v

def print_move_sequence(move_sequence):
    print(' '.join(FACES[move.face] + ROTATION_INDICATORS[move.rotation - 1] for move in move_sequence))

def is_harlequin(state):
    for face in range(len(FACES)):
        # centre colour must not be an edge facelet colour
        if face in state[face][1::2]:
            return False
        # adjacent non-centre facelets must not have the same colour
        if any(a == b for a, b in zip(state[face], state[face][1:] + state[face][:1])):
            return False
        # face must have all colours
        if len(set(state[face] + [face])) < len(FACES):
            return False
        # No need to check the maximum repetitions to find the first "Harlequin" it seems, but if it were:
        # from collections import Counter  # move to top of module
        # if max(Counter(state + [face]).values()) > 2:
        #     return False
    return True

def main():
    depth = 1
    while depth:
        print(f"searching at {depth=}")
        for move_sequence in gen_move_sequences(depth):
            if is_harlequin(get_state(move_sequence)):
                print_move_sequence(move_sequence)
                break
        else:
            depth += 1
            continue
        break

if __name__ == "__main__":
    main()

```
> 22 votes

# Answer
While I was was sieving through hundreds of patterns, using Herbert Kociemba's Cube Explorer, I stumbled upon a pattern, shown in the animation\* below, that can be generated by a 15-move algorithm. But I don't know if this is the shortest algorithm which generates a harlequin pattern.

D' F L2 D F U2 B U' R' L F B L2 D L'

---

**UPDATE – I found another one!**
F R B D B F2 R2 U2 L' F' L D2 B R2 U

Today I decided to systematically search for the shortest harlequin algorithm using Kociemba's program. I started by manually counting the number of harlequin search patterns to be used in the Pattern Editor. There are 7 ways to arrange the first 2 facelets of the 1st color (excluding rotation symmetry):

For patterns 1 and 5 there are only 13 ways to arrange the next 2 facelets of the 2nd color:

For patterns 2, 6 and 7 there are 15 ways to arrange the 2nd color facelet pair. For patterns 3 and 4 there are 14 ways.

So, there are 99 ways in which the first 4 facelets can be arranged. For pattern 1 I counted 80 ways in which the 3rd color facelet pair can be placed. Because the colors of the search pattern only tell the program the structure of the pattern and not the actual colors to be searched, it doesn't matter how we color the last 3 facelets as long as each has a unique color. So there are 80 search patterns that begin with pattern 1. Pattern 2 is the starting point for 110 search patterns. Pattern 3 generates 94 search patterns. But I ran into a roadblock. Some search patterns produce 7 results, some 164 and some... OVER 9000!!

I had to stop the program after letting it run for more than 24 hours. It was still searching for patterns.

Obviously, it is unfeasible to manually search for the shortest harlequin generator. I hope someone will find a better way to answer this question. I understand that the number of harlequin patterns may be so large that it renders such patterns as... not so special to worth the effort of investigating. I don't know enough math to go any further.

I am still interested in a mathematical solution to this puzzle.

---

* GIF created using Rubik's Cube Explorer and VirtualDub.
> 4 votes

---
Tags: rubiks-cube, fewest-operations
---


title: Sum the array times n, except the last

text:
# Question
Title: Sum the array times n, except the last
I've been posting relatively hard challenges recently, so here goes an easy one.

## Task

Given an array \\$A\\$ and a number \\$n\\$, calculate the sum of all numbers of \\$A\\$ multiplied by \\$n\\$, except the last one. All numbers (the elements of \\$A\\$ and the value of \\$n\\$) are positive integers, and \\$A\\$ is non-empty. Shortest code in bytes wins.

I have a 3-byte J solution. Can you find it (or beat it in a different language)?

## Test cases

```
A           N   Ans   Explanation
3 1 4 1 5   10  95    (3+1+4+1)*10+5
3 1 4 1 5   1   14    (3+1+4+1)*1+5
1           999 1     1

```

# Answer
# , 3 bytes

That was fun to find.

```
&+/

```

Try it online!

### How it works

`10 (&+/) 3 1 4 1 5` will bind `10` as an argument of `+` as `10&+`, one verb that gets inserted between the elements of the list by `/`. So we have: `3 (10&+) 1 (10&+) 4 (10&+) 1 (10&+) 5`. Now `x n&v y` means that `y` gets applied to `n&v` for `x` times. With J's right to left evaluation we get: to 5 add 1 times 10, add 4 times 10, add 1 times 10, add 3 times 10. A challenge made for J's stranger parts. :-) And because `+` is commutative, `+&/` would also be a valid solution.
> 33 votes

# Answer
# JavaScript (ES6),  ~~28~~  23 bytes

*Saved 3 bytes thanks to @Mukundan314*

Expects `(A)(n)`.

```
A=>n=>eval(A.join`*n+`)

```

Try it online!

### How?

We simply join the input array with `"*n+"`, so that `[1,2,3]` is turned into `"1*n+2*n+3"` and evaluate the resulting string.
> 28 votes

# Answer
# Haskell, 17 bytes

```
foldr1.((+).).(*)

```

Try it online!

It turns out this this was close to a port of the intended J solution. The pointfree function `((+).).(*)` takes the argument `n` to the map `\a b->a*n+b`, that is, to add `n` times the left value to the right value. This creates the same "verb" as J used, and the `foldr1` does the same a J's automatic right to left evaluation. It starts with the rightmost value in the list, which never gets multiplied by `n`, and applies it right-to-left, effectively increasing the sum so far with `n` times to the new element.
> 10 votes

# Answer
# Python 3, 27 bytes

```
lambda a,n:a.pop()+sum(a)*n

```

Port of my Japt solution to python

Try it online!
> 7 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
#2Tr@Most@#+Last@#&

```

Try it online!
> 6 votes

# Answer
# Python 3, 27 bytes

```
lambda a,n:a.pop()+sum(a)*n

```

Try it online!
> 5 votes

# Answer
## Clojure 41 bytes

`#(+(last %1)(* %2(apply +(butlast %1))))`

Unfortunately, `+` does have to be `apply`ed.

Try It Online
> 5 votes

# Answer
# 05AB1E, 5 bytes

-2 bytes thanks to @KevinCruijssen.

```
*`²÷O

```

Try it online!

## Explanation

```
*     Multiply list by second operand
 `    Dump
   ÷  Divide the last item by
  ²   the second operand
    O Sum the stack

```

# 05AB1E, 7 bytes

```
„²*ý.VO

```

Try it online!

## Explanation

```
„       2-char string
 ²*     (Which does when evaluated) Multiply by the second input
   ý    Join the input list by this
    .V  Evaluate
      O Sum the resulting stack

```
> 4 votes

# Answer
# APL (Dyalog Extended), 9 bytes (SBCS)

Anonymous tacit infix function. Takes \\$A\\$ as left argument and \\$n\\$ as right argument.

```
⊢/+.×+×∘~

```

Try it online!

`×∘~`\\$A×(1-n)\\$

`+.×+`\\$\big(\sum\_{i=1}^N A\_i×n\big)+\\$

`⊢/` rightmost element (lit. right-argument reduction)

So this effectively implements: $$ \Bigg(\bigg(\sum\_{i=1}^N A\_i×n\bigg)+A×(1-n)\Bigg)\_N\\ \bigg(\sum\_{i=1}^N A\_i×n\bigg)+A\_N×(1-n)\\ \bigg(\sum\_{i=1}^N A\_i×n\bigg)+A\_N-n×A\_N\\ \bigg(\sum\_{i=1}^{N-1} A\_i×n\bigg)+A\_N $$
> 4 votes

# Answer
# APL (Dyalog Unicode), 5 bytes

```
+⍣⎕/⎕

```

Try it online!

A full program, which pretty much works like the 3-byte J solution. Takes two lines of input, \\$A\\$ first and \\$n\\$ second.

### How it works

```
+⍣⎕/⎕
    ⎕  ⍝ Take the input A
   /   ⍝ Reduce by...
+      ⍝   Add the left argument
 ⍣⎕    ⍝   n times

For n=10 and A = 3 1 4 1 5, this becomes:
+⍣10/3 1 4 1 5
3 (+⍣10) 1 (+⍣10) 4 (+⍣10) 1 (+⍣10) 5
3 added 10 times to
         1 added 10 times to
                  4 added 10 times to
                           1 added 10 times to
                                    5

```

---

# APL (Dyalog Extended), 8 bytes

```
1¨⍛,⊥0,⊣

```

Try it online!

A longer but more interesting one. A tacit dyadic function that takes \\$A\\$ on its left and \\$n\\$ on the right.

Uses mixed base conversion , which does the following:

```
Base:        1  1  1  ... 1    n
Digit value: n  n  n  ... n    1
Array value: 0  a1 a2 ... ax-1 ax
Total: a1n + a2n + ... + ax-1n + ax

```

### How the code works

```
1¨⍛,⊥0,⊣  ⍝ Input: left=A, right=n
1¨        ⍝ An array of ones as long as A
  ⍛,      ⍝ Append n, which becomes the base
     0,⊣  ⍝ A prepended with single zero, which becomes the values
    ⊥     ⍝ Mixed base conversion as described above

```
> 4 votes

# Answer
# , ~~37~~ ~~36~~ 35 bytes

-2 bytes with help from Giuseppe

```
function(l,n)rev(l)%*%n^(seq(!l)>1)

```

Try it online!

Reverse the vector, and perform dot product with the vector \\$(n^0, n^1, n^1, \ldots,n^1) = (1, n, n,\ldots, n)\\$.

I just discovered this behaviour of `seq`, which gains 1 byte on item 4 of this tip: `seq(!l)` is equivalent to `seq(along.with = l)` (giving the vector `1 2 3 ... length(l)`) in all situations, even if `l` is of length 1. That is because `!l` is a logical, not an integer, and so we avoid the call to `seq.int` when `l` is a (length 1) integer.
> 4 votes

# Answer
# K (oK), ~~14~~ 13 bytes

**Solution:**

```
{*|x+/y*-1_x}

```

Try it online!

**Explanation:**

Couldn't figure out a smart way of solving this.

```
{*|x+/y*-1_x} / the solution
{           } / lambda taking implicity x, y
        -1_x  / drop (_) 1 element from end of x
      y*      / multiply by y
   x+/        / sum up with x as accumulator
 *|           / take last (reverse, first)

```

**Notes:**

* **-1 byte** thanks to coltim - thanks!
> 4 votes

# Answer
# Pyramid Scheme, 407 bytes

```
     ^      ^
    /l\    /+\
   /oop\  ^---^
  ^-----^ -  /x\
 / \   / \   ---
/arg\ /set\
-----^-----^
    /2\   /+\
    ---  ^---^
        ^-  /1\
       ^-   ---
      ^-
     /]\
    ^---^
   / \ /2\
  /set\---
 ^-----^
/x\   ^-
---  /]\
    ^---^
   ^-  /#\
  / \  ---^
 /set\   / \
^-----^ /arg\
-    /+\-----^
    ^---^   /2\
   /*\  -   ---
  ^---^
 ^-  /#\
/x\ ^---
---/ \
  /arg\
 ^-----
/1\
---

```

Try it online!

Takes input through command arguments, with `n` as the first argument. This basically implements the algorithm:

```
i = 2
x = 0
o = 0
while args[i]:
  o += x*args[1]
  x = args[i]
  i += 1

print(o + x)

```

But with more nesting and some shortcuts, like using the variable `2`.
> 4 votes

# Answer
# Perl 5 \+ `-pa -MList::Util+sum`, 19 bytes

```
$_=pop(@F)+<>*sum@F

```

Try it online!
> 3 votes

# Answer
# Japt, 7 bytes

```
o +V*Ux

```

Try it online!

## Explanation

```
o +V*Ux
o         // Pop and return last element of first input
  +       // plus
   V*     // second input times
     Ux   // Sum of first input

```
> 3 votes

# Answer
# Retina 0.8.2, 31 bytes

```
\d+
$*
1(?=.*,1*;(1*)|1*$)
$1
1

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
1(?=.*,1*;(1*)|1*$)
$1

```

Multiply all but the last element of `A` by `n` and delete `A`.

```
1

```

Take the sum and convert to decimal.
> 3 votes

# Answer
# Pyth, 7 bytes

```
+*sPQEe

```

Try it online!

## Explanation

```
+*sPQEe
    Q    # First input
   P     # Remove the last element
  s      # Sum elements
 *   E   # Multiply by the second input
+     e  # Add the last element of the first input

```
> 3 votes

# Answer
# Emacs Lisp with dash library: ~~38~~ 51 bytes

```
(lambda(n A)(+(car(last A))(* n(-sum(butlast A)))))

```

(38 bytes was the function body' size only.)
> 3 votes

# Answer
# x86-16 machine code, 18 bytes

```
33 DB       XOR  BX, BX         ; clear running sum
49          DEC  CX             ; decrement array length
74 09       JZ   ADD_LAST       ; handle array length of 1 case
        LOOP_SUM:
AD          LODSW               ; load next value into AX
03 D8       ADD  BX, AX         ; BX = BX + AX
E2 FB       LOOP LOOP_SUM       ; keep looping
93          XCHG AX, BX         ; move sum into AX
F7 E2       MUL  DX             ; DX:AX = AX * DX
93          XCHG AX, BX         ; move result back to BX
        ADD_LAST:
AD          LODSW               ; load last value into AX
03 C3       ADD  AX, BX         ; AX = AX + BX
C3          RET                 ; return to caller

```

As a callable function: `[SI]` to input array, `CX` array length, `DX` = `N`. Output to `AX`.

Rather than make an elaborate test program, here's it being run using DOS DEBUG, entering the input array into memory and setting registers as they would be called:

Explanation of above:

Enter input array into memory address `DS:200` as 16-bit, little-endian words:

```
-e 200 3 0 1 0 4 0 1 0 5 0

```

Point `SI` to this input array:

```
-r SI
:200

```

Set `CX` to array's length:

```
-r CX
:5

```

Set `N` to `10` (`0xA` in hex):

```
-r DX
:A

```

Execute and stop before last instruction (`RET` will "return to DOS" and clobber registers):

```
-g 111

```

Result is `AX=005F` or `95` in decimal.
> 3 votes

# Answer
# Golfscript, 13 bytes

```
~:i;-1%{i*+}*

```

Try it online!

**Explanation:** `~` to convert string input to array and integer on stack. `:i;` assigns \\$n\\$ to `i` and pops value. `-1%` reverses the array and `{i*+}*` folds the array with `(a, b) -> a*n + b`
> 3 votes

# Answer
# Pyramid Scheme, ~~7747~~ ~~3668~~ ~~1985~~ ~~1732~~ 1619 bytes

## Edits

* -4079 bytes by giving the variables shorter names...
* -1638 bytes by doing some more manual optimisation
* -253 bytes by using more 0-height trees
* -113 bytes because out can output the final result directly

```
    ^  ^        ^       ^        ^  ^        ^        ^        ^
   / \ -^      / \     / \      / \ -^      / \      / \      / \
  /set\ -^    / do\   /set\    /   \ -^    /set\    /   \    /out\
 ^-----^ -^  ^-----^ ^-----^  / set \ -^  ^-----^  /     \   -----^
/l\   / \ -^/c\   ^-/n\   ^- ^-------^ -^/i\   ^- / loop  \      /+\
---  /arg\^----  ^- ---  ^- /N\     /#\^----  ^- ^---------^    ^---^
    ^------^    / \     /-\ ---    ^----^    ^- / \       / \  /s\ /#\
   / \    ^-   ^---^   ^---^      / \  ^-   ^- /<=>\     ^---^ --- ---^
  /99 \  ^-   / \ / \ /n\ /1\    /arg\^-   ^- ^-----^   / \ / \      / \
  ----- ^-   ^---/   \--- ---   ^------^  ^- /i\   /0\ ^---/set\    /arg\
       ^-   / \  -----^        /n\    ^- /-\ ---   ---/ \ ^-----^   -----^
      ^-   ^---      / \       ---   ^- ^---^        ^---/s\   / \      /-\
     ^-   / \       /set\           ^- /n\ /1\      / \  ---  / + \    ^---^
    ^-   /set\     ^-----^         / \ --- ---     ^---      ^-----^  /n\ /1\
   ^-   ^-----^   /c\   /!\       /set\           / \       /s\   /*\ --- ---
   -^  /n\   /+\  ---  ^---      ^-----^         /set\      ---  ^---^
   / \ ---  ^---^     /=\       /s\   /0\       ^-----^         /#\ /N\
  /set\    /n\ /1\   ^---^      ---   ---      /i\   /-\       ^--- ---
 ^-----^   --- ---  / \ /l\                    ---  ^---^     / \
/n\   /0\          /arg\---                        /i\ /1\   /arg\
---   ---         ^-----                           --- ---  ^-----
                 /n\                                       /i\
                 ---                                       ---

```

Try it online!

## Explanation

```
(set nil (arg 99)) // Make nil

// Count the number of input arguments - n
(set nargin 0)
(do
    cond
    (
        (set nargin (+ nargin 1))
        (set cond (! (= (arg nargin) nil)))
    )
)
(set nargin (- nargin 1))

(set N (# (arg nargin))) // N - the number all but last of the array elements is getting multiplied by

// Add all but last elements of A
(set sum 0)
(set i (- nargin 1))
(loop
    (<=> i 0)
    (
        (set i (- i 1))
        (set sum (+ sum (* (# (arg i)) N))) // A[i] multiplied by N
    )
)
(set sum (+ sum (# (arg (- nargin 1))))) // Add the last element of A
(out sum) // Print

```
> 3 votes

# Answer
# Ruby, 46 19 bytes

```
->a,n{eval a*"*n+"}

```

Courtesy of petStorm.

**Old answer:**

```
n,*A,l=gets.split(' ').map(&:to_i)
p A.sum*n+l

```
> 3 votes

# Answer
## MAWP, 26 bytes

```
%@_2A<\:.>2M3A[1A~M~]%\WM:

```

Now it works properly on the testcases. Works on MAWP 1.1's integer input.

Try it!
> 3 votes

# Answer
# Jelly, 4 bytes

```
Ṫṭ×S

```

Try it online!

```
Ṫ       Pop the last element of the left argument,
 ṭ      append it to
  ×     the right argument times what's left of the left argument,
   S    and sum.

```

A more fun solution, which borrows Jonathan Allan's base conversion trick:

# Jelly, 5 bytes

```
S,¥/ḅ

```

Try it online!

```
   /     Reduce the left argument by
 ,       pair right with
S ¥      the sum of left,
    ḅ    and convert from base right.

```

Bonus: `Ä-.ịḅ’}` is a whole 7 bytes, and doesn't even work if the left argument only has one element, but it's just kind of funny.
> 3 votes

# Answer
# Befunge-98 (PyFunge), ~~29~~ 27 bytes

```
j&10p#v&\10g*\4
_\.@  >+\:#

```

Try it online! Input is first `N`, then `A`. Note that there has to be a trailing space.

Animation of the code:

The pilcrow (¶) represents a newline (value 10) in the grid.
> 2 votes

# Answer
# PHP, 41 bytes

```
fn($a,$n)=>array_pop($a)+array_sum($a)*$n

```

Try it online!

Just trying to use all the built-ins!
> 2 votes

# Answer
# Raku, 20 bytes

```
{@^a.pop+$^b*@a.sum}

```

By using twigils, `@^a` matches the first arg (the array), and `$^b` the second (the multiplier).

Try it online!
> 2 votes

# Answer
# Jelly, 5 bytes

```
ṪṭSƊḅ

```

A dyadic Link accepting a list of numbers on the left and a number on the right which yields a number.

**Try it online!**

```
ṪṭSƊḅ - Link: list of numbers, A; number n
   Ɗ  - last three links as a monad - f(A):
Ṫ     -   remove the tail (of A) and yield its value
  S   -   sum (the remaining elements in A)
 ṭ    -   tack -> [sum_of_remaining, tail]
    ḅ  - convert from base (n) -> n×sum_of_remaining+1×tail

```
> 2 votes

# Answer
# Q'Nial, 33 bytes (20 bytes without operator definition)

```
s is op n a{+link[n*front,last]a}   %full operator definition

+link[n*front,last]a                %simple function

```

Explanation:

```
+                                   sum, reduce by +
 link                               list of the items of the argument
     [                              atlas (argument of link operation), point-free notation
      n*                            n *
        front                       all elements but the last of the argument
             ,
              last                  last element of the argument
                  ]                 end atlas
                   a                array a (argument of atlas)

```

Intermediate results, for `n=10` and `a=3 1 4 1 5`

```
         10 s 3 1 4 1 5
or
         s 10 (3 1 4 1 5)

or
         +link[10*front,last]3 1 4 1 5

         [n*front,last] a
+-------------+-+
|+--+--+--+--+|5|
||30|10|40|10|| |
|+--+--+--+--+| |
+-------------+-+

         link[n*front,last] a
+--+--+--+--+-+
|30|10|40|10|5|
+--+--+--+--+-+

         +link[n*front,last]a
95

```
> 2 votes

# Answer
# Pip, 10 bytes

```
a@v+b*$+Ha
```

Attempt This Online!

-2 from DLosc.
> 2 votes

# Answer
# Julia 1.0, ~~21~~ 19 bytes

```
A$n=pop!(A)+sum(A)n

```

Try it online!
> 2 votes

# Answer
# Risky, 9 bytes

```
-_{1+0+00_?+0+?*?

```

Try it online!
> 2 votes

# Answer
# tinylisp, 58 bytes

```
(load library
(d S(q((A N)(i(t A)(a(*(h A)N)(S(t A)N))(h A

```

Try it online!

# tinylisp, ~~78~~ 65 bytes

```
(d S(q((A N)(i(t A)(i(h A)(a(S(c(s(h A)1)(t A))N)N)(S(t A)N))(h A

```

Try it online!

Solution without using `library`, which is only for `*`.

-13 bytes thanks to DLosc
> 2 votes

# Answer
# C (gcc), 56 bytes

```
s,i;f(v,l,f)int*v;{for(i=0;i<l-1;s+=v[i++]);return s*f;}

```

Try It Online!

`f` takes a vector (`v`), the length of the vector (`l`) and the factor to multiply the vector with (`f`) as arguments. It sums up the values in the vector, except for the last one (in `s`) and returns the sum multiplied by the factor.
> 2 votes

# Answer
# Thunno 2 `s`, 4 bytes

```
×Ẹ¹÷

```

Attempt This Online!

# Thunno 2, 5 bytes

```
µʋ¹×+

```

Attempt This Online!

Suggested by @noodleman.

#### Explanation

```
×Ẹ¹÷  # Implicit input
×     # Multiply each item in the list by the number
 Ẹ    # Dump onto stack, last item on top
  ¹÷  # Divide this number by the second input
      # Implicit output of summed stack

```

```
µʋ¹×+ # Implicit input
µʋ    # Right-reduce the input list by:
  ¹×  #  Multiply by the second input
    + #  And add this to the cumulative total
      # Implicit output

```
> 2 votes

# Answer
# TI-BASIC, 17 bytes

```
Input N
Nsum(Ans)-(N-1)Ans(dim(Ans

```

Takes input of \\$A\\$ in `Ans`.

Alternatives that are also 17 bytes:

```
Input N
sum(Ansmax(1,N(N>cumSum(1 or Ans

```

```
Input N
sum(AnsNaugment(1 or ΔList(Ans),{N⁻¹

```
> 2 votes

# Answer
# Charcoal, ~~10~~ 9 bytes

```
Ｉ⁺⊟θ×η↨θ¹

```

Try it online! Link is to verbose version of code. Presumably Charcoal has the same problem as IO when it comes to summing empty lists. Edit: saved 1 byte by converting from base 1 instead. Explanation:

```
   θ        `A`
  ⊟         Remove last element
 ⁺          Added to
       θ    Remaining elements of `A`
      ↨ ¹   Take the sum by converting from base 1
    ×       Multiplied by
     η      `n`
Ｉ           Cast to string
            Implicitly print

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
a___~f~b_=+a#+b&

```

Try it online!

This one doesn't need a strange-looking input.

Takes input as `f[A][n]`.

---

**older, 17 bytes**

```
#//.a_@b_:>a#2+b&

```

Try it online!

Takes a singly linked list as input: if `X` is a value and `L` is a list, `X` is the single-element list with element `X`, and `X[L]` is the list with element `X`, followed by the elements of `L`. For example, `3@1@4@1@5=3[1[4[1[5]]]]` is the list with `3, 1, 4, 1, 5`.

Per this discussion, we can take the first element with `Head`, and the tail with `Last`.
> 1 votes

# Answer
# Zsh, 25 bytes

```
n=`<&0`
<<<$[0${@/#/*n+}]

```

Try it online!

Takes the list as arguments and N on stdin. Inspired by the JS answer. Prefix each element with `*n+` and `$[evaluate arithmetically]`. We have to add a `0` to the start as well. This is one byte shorter than using the join flag `<<<$[${(j:*n+:)@}]`

# Zsh `-P`, 24 bytes

```
a=(0 \*`<&0`+$@)
<<<$[a]

```

Try it online!

Alternate solution using the -P flag, which enables RC\_EXPAND\_PARAM to do the same thing.
> 1 votes

# Answer
# Vimscript 36 Bytes

Disgusted to report that Arnauld's solution also works for vimscript.

```
let F={a,n->eval(join(a,"*".n."+"))}

```
> 1 votes

# Answer
# T-SQL, 40 bytes

I am using a table instead of an array, sql doesn't have arrays

The test uses a temporary table instead of a real table, because of lack of permissions to create a table.

```
SELECT sum(a*@-i/@@rowcount*a*~-@)FROM t

```

**Try it online**
> 1 votes

# Answer
# SimpleTemplate, 81 bytes

It's fairly chunky :/
Mostly due to limitations in my language...

```
{@eachargv.0}{@ifloop.last is equal0}{@set*_ _,argv.1}{@/}{@incby_ R}{@/}{@echoR}

```

Takes a string of numbers or an array as the first argument, and the `n` as the 2nd argument.

You can try this on http://sandbox.onlinephpfunctions.com/code/4c7290781560c876ff1e72e5d1680ed7b98861a3

---

**Ungolfed:**

The code above is a little weird to read...

Here's a more readable version:

```
{@set result 0}
{@each argv.0 as number}
    {@if loop.last is equal to false}
        {@set* number number, argv.1}
    {@/}
    {@inc by number result}
{@/}
{@echo result}

```

Notes:

* `{@set result 0}` is optional, as `{@inc}` will create the variable, if it doesn't exist
* `{@each argv.0 as number}` doesn't need need the `as number`, defaulting to the variable `_` to store values
* `{@if loop.last is equal to false}` uses the special variable `loop` to know if it is the last item in the `{@each}` Also, `false` is the same as `0`.
* `{@set* number number, argv.1}` multiplies `number` with `argv.1` and stores it inside `number`. If `number` was an array, it would multiply with all the values.
* `{@inc by number result}` will increment the variable `result` by `number` (effectivelly, `result = result + number`)
* `{@/}` is usually optional, but, with this code, they are all required.
> 1 votes

# Answer
# Perl 5 \+ `-pi`, 19 bytes

```
s/,/*$^I+/g;$_=eval

```

For example, for multiplicand 10, `perl -pi10 -e's/,/*$^I+/g;$_=eval`

Try it online. Idea stolen from this J answer. Accuracy improved by Dom Hastings in comments on this answer (many thanks!).
> 1 votes

# Answer
## dc, 21 bytes

`ss0[+z2<o]dso0rx*ls+p`

Examples:

```
dc -e '10 3 1 4 1 5 ss0[+z2<o]dso0rx*ls+p'
95
dc -e '1 3 1 4 1 5 ss0[+z2<o]dso0rx*ls+p'
14
dc -e '999 1 ss0[+z2<o]dso0rx*ls+p'
1

```
> 1 votes

# Answer
# Raku, 21 bytes

```
{*.join("*$_+").EVAL}

```

Try it online!

This works the same as the Perl 5 answer and also works with non-mutable lists, unlike the existing Raku answer, which is only one byte smaller than this.

Note: My previous answer of the same size does not work for singleton lists, which I've lodged an issue about.
> 1 votes

# Answer
## excel, 25 bytes

Enter A followed by n in one column, followed by this formula

`=SUM(R1:R[-3])*R[-1]+R[-2]`
> 1 votes

# Answer
# Lua, 58 bytes

```
r,t=0,{...}for i=2,#t-1 do
r=r+t[i]end print(r*t[1]+t[#t])

```

Try it online!

Having almost no array functions, Lua doesn't do too well in this challenge.
> 1 votes

# Answer
# Scala, 22 bytes

```
a=>a.last+_*a.init.sum

```

This returns a `List[Int] => Int => Int`

Try it online
> 1 votes

# Answer
# MATL, 9 bytes

```
*1G0)0Z(s

```

Try it online!

## Explanation

```
*1G0)0Z(s
*          % Multiply the inputs and push it onto the stack
 1G        % Push first input onto the stack
   0)      % Replace top stack element with its last element
     0Z(   % Set last element of multiplied inputs to top element in stack
        s  % Replace top stack element with its sum

```
> 1 votes

# Answer
# Rust, 45 bytes

```
|a,n|a.pop().unwrap()+a.iter().sum::<i64>()*n

```

Try it online

The expected argument types are `a: &mut Vec<i64>` and `n: i64`.
> 1 votes

# Answer
# Japt `-h`, 6 bytes

```
Ç+Ux*V

```

Try it
> 1 votes

# Answer
# PowerShell Core, 29 bytes

```
param($a,$b)$a-join"*$b+"|iex

```

Try it online!

^ inspired by Arnauld's solution

My original one

# PowerShell Core, 75 bytes

```
param($a,$b)(($a[($l=$a.Length-1)]+$b*($a[0..($l-1)]-join'+'|iex)),$a)[!$l]

```

Try it online!
> 1 votes

# Answer
# Stax, ~~6~~ 4 bytes

```
╡÷E@

```

Run and debug it
> 1 votes

# Answer
# Factor \+ `math.unicode`, 23 bytes

```
[ dup pop -rot Σ * + ]

```

Try it online!
> 1 votes

# Answer
# Vyxal `s`, 5 bytes

```
*ṫ⁰/J

```

Try it Online!
> 1 votes

# Answer
# TI-BASIC, 30 bytes (on-calc) / 37 bytes (as text)

Assumes list variable `L₁` contains the array and variable `N` contains n.

```
dim(L₁
Nsum(L₁,1,Ans-1)+L₁(Ans

```

## Explanation

* `dim(L₁`: Get the size of L₁, to be used in the next line as `Ans`.
* `Nsum(L₁,1,Ans-1)+L₁(Ans`: The `sum(` function has optional arguments to specify the beginning and end of a region of the list to be summed. The sum is implicitly multiplied by N, then added to the last element of the list, and implicitly printed.

Closing parentheses can be left out at the end of lines in TI-BASIC.
> 1 votes

# Answer
# Ly, 18 bytes

```
&n&spp&+>l<s>l*+u;

```

Try it online!

```
&n                 - read all the numbers into the stack
  &s               - save the entire stack to the backup cell
    pp             - delete top two entries on the stack
      &+           - sum the stack
        >l         - switch to clean stack, load original input
          <s       - switch back, save summary to backup cell
            >l     - switch stacks, load save sum of 2nd to N entries
              *    - multiple top two entries on stack
               +   - add top two stack entries
                u  - print top of stack as a number
                 ; - exit the code to avoid printing the rest of the stack

```
> 1 votes

# Answer
# Arturo, 28 bytes

```
$[a,n][+last a n*sum chop a]

```

Try it

```
$[a,n][           ; a function taking args a and n
  +last a         ; add the last elt in a to
  n*sum chop a    ; n times the sum of a without its last elt
]                 ; end function

```
> 1 votes

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

```
n=>a=>a.reduceRight((x,c)=>x+c*n)

```

Attempt This Online!

Not as short as the `eval` solution but uses a very similar method.
> 1 votes

# Answer
# Swift, 46 bytes

```
{a,n in a.dropLast().reduce(a.last!){$0+n*$1}}

```

Try it online!

Type signature: `<C: BidirectionalCollection where C.Element: Numeric>(C, C.Element) -> C.Element`. (That syntax isn't quite legal Swift for lack of generic lambdas, but you know what I mean.)

For each element (`$1`) in `a` except the last one, add `n*$1` to the running total. The total starts at `a.last` instead of zero.
> 1 votes

# Answer
# sed 4.2.2, 65 bytes

```
s/<(!*)><(!*)>$/%\2%\1/
s/><//g
:a
s/!>%(!*)%/>%\1%\1/
ta
s/.*%//

```

Try it online!

Input is a list exclamation marks surrounded by `<>`. `n` is given as the last element of the list. Output is just exclamation marks.

Example where `A = [3,1,4,1,5]` and `n = 1`:

`<!!!><!><!!!!><!><!!!!!><!>` =\> `!!!!!!!!!!!!!!`
> 1 votes

# Answer
# C (clang), 40 bytes

```
f(*a,l,n){return--l?*a*n+f(a+1,l,n):*a;}

```

Try it online!
> 1 votes

# Answer
# jq, 18 bytes

```
(add-last)*$n+last

```

Try it online!
> 1 votes

# Answer
# Befunge-98 (PyFunge), 24 bytes

```
j&0#v&:61p+2
g+.@>'.-*61

```

Try it online!

Ended up converging on a similar layout to ovs' answer, though with a different strategy:

### Explanation:

```
 &0          Read numeric input (n) and push a zero on top as sum
   #         Skip into the main loop
     &:61p+  Read a number in, save a copy in (6,1) and add it to the sum
j          2 Jump over the initialisation and continue the loop
    v&       When we're out of input, go to the next line

At this point, our stack looks like `n sum`

    >'.-     Retrieve our saved last value and subtract it from the sum
        *    Multiply by n
g+       61  Retrieve our saved value and add it back to the sum
  .@         Print and exit

```
> 1 votes

# Answer
# Nibbles, 2.5 bytes (5 nibbles)

```
/@+*_

```

```
/@+*_       # full program
/@+*_$@     # with implicit args added;
/           # fold from right over
 @          # arg2
            # with function:
  +         #   add
   *        #   the product of
    _       #     arg1
     $      #     and the left-hand element
      @     #   to the right-hand element

```
> 1 votes

# Answer
# Uiua, 7 bytes

```
/+⍜↘×¯1

```

Try it!

```
/+⍜↘×¯1
     ¯1  # push negative one
  ⍜↘×    # multiply all but last element by input
/+       # sum

```
> 1 votes

# Answer
# Desmos, ~~32~~ 31 bytes

```
f(a,n)=na.total-(n-1)a[a.count]

```

Try it on Desmos

-1 byte thanks to Aiden Chow.
> 1 votes

# Answer
# Io, 31 bytes

Saves a byte over the 32 byte solution. But it's boring.

```
method(a,N,a sum*N-a pop*(N-1))

```

Try it online!

## Explanation

```
method(a, N,
    a sum * N         // Sum the input, multiply by N
  - a pop * (N - 1)   // Minus the last item, multiplied by N - 1
)

```

# Io, 32 bytes

Just as comparison

```
method(a,N,a push(a pop/N)sum*N)

```

Try it online!

## Explanation

```
method(a, N,
           a pop           // Extract the last item from the input list
                /N         // Divide it by N
    a push(       )        // And then put it back into the original list
                   sum     // Sum the list
                      *N   // Multiply the value by N
)

```
> 0 votes

# Answer
# C (gcc), 53 bytes

Saved 2 bytes thanks to ceilingcat

```
s;f(a,n)int*a,n;{for(s=0;a[1];s+=*a++);return*a+s*n;}

```

Try it online!
> 0 votes

# Answer
# Perl 6, 29 bytes

```
->$a,$b {$a.pop+([+] $a)*$b};

```

Try it online!
> 0 votes

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