title: Generate the Crystal Maze™ time matrix

text:
# Question
Title: Generate the Crystal Maze™ time matrix
Behold! The Crystal Maze™ Time Matrix!

```
      0   1   2   3   4   5   6   7   8   9  10
  1   0   5  10  15  20  25  30  35  40  45  50
  2   0  10  20  30  40  50  60  70  80  90 100
  3   0  15  30  45  60  75  90 105 120 135 150
  4   0  20  40  60  80 100 120 140 160 180 200
  5   0  25  50  75 100 125 150 175 200 225 250

```

Obviously, this is self explanatory to anyone who knows The Crystal Maze™, but here's a quick run-down for anyone else:

* In The Crystal Maze™, team members attempt a series of games where they can win Crystals.
* Crystals represent time in the final game, 5 seconds for every crystal.
* They can also fail these games in a way which gets a team member locked in, so they are not able to participate in the final game.
* Before the final game, they have the option to buy the team members back with crystals, giving them less time but more people.

The Matrix shows you the number of crystals along the top, and the number of team members on the left. The body of the matrix is filled with "people seconds". Its purpose is to decide if selling a crystal will increase your "people seconds" or not.

# The game

* Generate the precise textual output of The Crystal Maze™ Matrix.
    + The crystals, along the top, will range from 0 to 10.
    + Team members will range from 1 to 5.
    + All columns will be exactly 3 characters wide and right-justified.
    + Columns are separated with a space.
    + A single value will show (crystals × team members × 5).
* Use any language capable of producing this textual output.
* It's code golf, so attempt to do so in the fewest bytes.
* Please include a link to an online interpreter such as TIO.

# Answer
> 8 votes
# , 60 bytes

```
write(format(rbind(c("",1:5),0:10%o%c(1,1:5*5)),j="r"),1,12)

```

Try it online!

# Answer
> 7 votes
# Excel (ms365), ~~145~~, 122 bytes

Formula in `A1`:

```
=LET(x,ROW(1:6)-1,y,COLUMN(A:K)-1,TEXTJOIN(HSTACK(IF(y+1," "),CHAR(10)),,RIGHT("  "&HSTACK(IF(x,x," "),IF(x,y*5*x,y)),3)))

```

This can be 117 bytes if we would swap `CHAR(10)` out for a literal `Alt`+`Enter`:

```
=LET(x,ROW(1:6)-1,y,COLUMN(A:K)-1,TEXTJOIN(HSTACK(IF(y+1," "),"
"),,RIGHT("  "&HSTACK(IF(x,x," "),IF(x,y*5*x,y)),3)))

```

# Answer
> 5 votes
# Charcoal, ~~26~~ 25 bytes

```
Ｅ⁶⪫Ｅ¹²◧⎇λＩ×⊖λ∨×⁵ι¹⎇ιＩιω³

```

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

```
 ⁶                          Literal integer `6`
Ｅ                           Map over implicit range
    ¹²                      Literal integer `12`
   Ｅ                        Map over implicit range
       ⎇λ                   If not the first column
            λ               Current column
           ⊖                Decremented
          ×                 Multiplied by
                ι           Current row
              ×             Multiplied by
               ⁵            Literal integer `5`
             ∨              Logical Or
                 ¹          Literal integer `1`
         Ｉ                  Cast to string
                  ⎇ι        If not the first row
                    Ｉι      Current row as a string
                      ω     Else empty string
      ◧                ³    Left-pad to length 3
  ⪫                         Join with spaces
                            Implicitly print

```

~~23~~ 22 bytes using the newer version of Charcoal on ATO:

```
Ｅ⁶⪫Ｅ¹²◧⎇λ×⊖λ∨×⁵ι¹∨ιω³

```

Attempt This Online! Link is to verbose version of code. Explanation: `PadLeft` stringifies its argument, allowing the removal of two instances of `Cast` and the subsequent simplification of `Ternary` to `Or`.

# Answer
> 5 votes
# Pure Bash \- no external utilities, 66

Thanks to @Nahuel Fouilleul for saving 10 bytes!

```
printf "`echo %3s{,,}{,,,}`\n" '' {0..10} $[{1..5}*{1,{0..50..5}}]

```

Try it online!

# Answer
> 4 votes
# Thunno 2 `N`, 21 bytes

```
5ıTĖ×5×nƤð4ṙ;TĖðƤð4ṙƤ

```

Try it online!

#### Explanation

```
5ı           # Map over [1..5]:
  TĖ×        #  Multiply by [0..10]
     5×      #  And multiply by 5
       nƤ    #  Prepend the current number
         ð4ṙ #  Right-justify to length 4
;            # End map
 TĖ          # Push [0..10]
   ðƤ        # Prepend a space
     ð4ṙ     # Right-justify to length 4
        Ƥ    # Prepend this list
             # Implicit output, joined on newlines

```

# Answer
> 4 votes
# Vyxal, 115 bitsv1, 14.375 bytes

```
5ƛ₀ʀ*5*J;₀ʀðppÞĠ

```

Try it Online!

## Explained

```
5ƛ₀ʀ*5*J;₀ʀðppÞĠ
5ƛ      ;         # To each number in the range [1, 5]:
  ₀ʀ*             #   Multiply it by the range [0, 10]
     5*           #   Multiply that by 5
       J          #   And prepend the number to the start of the list
         ₀ʀðp     # The list [0, 10] with " " prepended
             p    # Put that list at the start of the list of lists from before
              ÞĠ  # Gridify, right-aligning and joining columns on spaces.

```

Created with the help of Luminespire.

# Answer
> 4 votes
# Perl 5, 76 bytes

```
printf$"x3 .($b="%4d"x11),0..10;//,printf"
  $_$b",map$_*=5*$',0..10for 1..5

```

Try it online!

# Answer
> 4 votes
# Python 3, 69 bytes

```
for k in b"\n":print(('%4s'*12%(k//5or'',*range(0,11*k,k)))[1:])

```

Try it online!

Thanks to dingledooper for -3 bytes from the bytestring hardcode. If trailing spaces are allowed:

**64 bytes**

```
for k in b"\n":print('%3s '*12%(k//5or'',*range(0,11*k,k)))

```

Try it online!

# Answer
> 4 votes
# Python 3, 76 bytes

```
print(*(' '.join(f'{i*j*5:3}'for i in range(11))for j in range(6)),sep='\n')

```

Try it online!

# Answer
> 4 votes
**SQL, Will never win 267**

```
with C AS(SELECT 10 C UNION ALL SELECT C-1FROM C WHERE C-1>=0),M AS(SELECT 5 M UNION ALL SELECT M-1FROM M WHERE M-1>0),PS as(select C,M,C*M*5 PS from C cross join M)SELECT*FROM(SELECT*FROM PS)tbl PIVOT(max(PS)FOR C IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]))P

```

Try it here db\<\>fiddle

**Explained...**

```
--List Crystals 0-10
with Crystal AS (
    SELECT 10 Crystal
UNION ALL
    SELECT Crystal-1
    FROM Crystal
    WHERE Crystal-1>=0
    )
--List Members 1-5
,Member AS (
    SELECT 5 Member
UNION ALL
    SELECT Member-1
    FROM Member
    WHERE Member-1>0
    )
--Join Crystal and Member, Calc People Seconds
,PS as
(
    select Crystal,Member,Crystal*Member*5 PS
    from Crystal
    cross join Member
)
--Pivot Maze
SELECT * FROM
    (
    SELECT *
    FROM PS
    ) tbl
PIVOT(
    max(PS)
    FOR Crystal IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
    ) pvt

```

# Answer
> 3 votes
# JavaScript (ES6), 74 bytes

*+4 bytes for a quick and dirty fix to comply with the updated output*

```
f=(y=5,x=11)=>x--?f(y,x)+`   ${x*y*5||x}`.slice(-4):y?f(y-1)+`
  `+y:'   '

```

Try it online!

### Commented

```
f = (                    // f is a recursive function taking:
  y = 5,                 //   y = team members
  x = 11                 //   x = crystals
) =>                     //
x-- ?                    // if x is not 0 (decrement it afterwards):
  f(y, x) +              //   do a recursive call with (x, y)
  `   ${x * y * 5 || x}` //   and append x * y * 5 or x if this is 0
  .slice(-4)             //   right-justified to 4 characters
                         //   with leading spaces
:                        // else:
  y ?                    //   if y is not 0:
    f(y - 1) +           //     do a recursive call with just y-1 (which
                         //     means that x is implicitly reset to 11)
    `\n  ` +             //     followed by a line feed a 2 spaces
    y                    //     followed by y
  :                      //   else:
    '   '                //     insert the 3 top-left spaces and stop

```

# Answer
> 3 votes
# Bash, 138 bytes

```
(echo;seq 0 10;paste -d' ' <(seq 5) <(printf %s\\n {1..5}\*{0..10}\*5|bc|xargs -n11)|tr \  \\n)|sed 's/^/printf %3s\\\\n /e'|pr -ats\  -12

```

Try it online!

### With comments

This solution works by generating all the desired numbers, one per line, and then formatting the table with `printf(1)` and `pr(1)`:

```
(
  # Generate the top line
  echo
  seq 0 10

  # Intersperse 1 through 5 in-between the calculated rows using paste(1).
  # The calculation is done with a cross-product of {1..5}*{0..10}*5 piped
  # to bc(1).
  paste -d' ' \
    <(seq 5)  \
    <(\
        printf '%s\n' {1..5}\*{0..10}\*5 |
        bc                               |
        xargs -n11                       \
     ) |
  tr ' ' '\n' \
) |

# All columns should be 3 characters wide.
sed 's/^/printf "%3s\\n" /e' |

# Use pr(1) to output data across (-a), no header (-t) and with a space
# separator (-s ' ') between the 12 columns (-12).
pr -ats' ' -12

```

# Answer
> 3 votes
# Retina, 67 bytes

```

   11*#5*$(¶_11*@
_
$>:&
#
 $:&
%`@(?<=(.).*)
 $.($1*$:&*5*
P^`\d+

```

Try it online! Explanation:

```

   11*#5*$(¶_11*@

```

Insert a template for the output: 11 column headers, and 5 rows, each with a header.

```
_
$>:&

```

Populate the row headers. `$>:&` translates as `1`-indexed match index.

```
#
 $:&

```

Populate the column headers. `$:&` is the `0`-indexed match index.

```
%`@(?<=(.).*)
 $.($1*$:&*5*

```

Populate the table body. Each row is processed independently, and each `@`'s match index is multiplied by the row number and by `5`.

```
P^`\d+

```

Left-pad all of the numbers to the same width.

# Answer
> 3 votes
# Jelly, 19 bytes

```
-r⁵×þ`ḣ7ẸƇ»×¥5AG⁶3¦

```

**Try it online!**

### How?

```
-r⁵×þ`ḣ7ẸƇ»×¥5AG⁶3¦ - Main Link: no arguments
-r⁵                 - -1 inclusive range 10 -> [-1,0,1,2,3,4,5,6,7,8,9,10]
     `              - use as both arguments of:
    þ               -   table with:
   ×                -     multiplication
      ḣ7            - head to index seven
         Ƈ          - keep those for which:
        Ẹ           -   any?
            ¥5      - last two links as a dyad - f(M=that, 5):
           ×        -   {M} multiply {5}
          »         -   {M} maximum {that}
                      (multiplies M's positive values by 5)
              A     - absolute values
               G    - format as a grid
                  ¦ - sparse application...
                 3  - ...to indices: [3]
                ⁶   - ...action: a space character
                      (replaces the top left 5 (from -1×-1×5) with a space)

```

# Answer
> 3 votes
# Ruby, 77 bytes

Improvements thanks to Dingus

```
q=*r=1..10;s=" "
1.upto(6){|i|puts"  #{s} "+("%4d"*10)%q
q=r.map{|j|j*5*s=i}}

```

Try it online!

# Ruby, 82 bytes

```
q=r=[*1..10];s=" "
1.upto(6){|i|puts ("  #{s} "+"%4d"*10)%q
s=i;q=r.map{|j|j*i*5}}

```

Try it online!

# Answer
> 3 votes
# C (clang), 99 bytes

```
p(r,i){r?printf("\n%d",r):0;for(i=-1;i++<10;printf("\t%d",r>0?i*5*r:i));}f(i){for(i=0;i<6;p(i++));}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 22 bytes

```
5LTÝδ*5*TÝšεNš}§3j»ð2ǝ

```

Should have been 21 bytes without the `§`, but unfortunately there is a bug in 05AB1E.

Try it online.

**Explanation:**

```
5LTÝδ*           # Push a 0..10 by 1..5 multiplication table:
5L               #  Push a list in the range [1,5]
  TÝ             #  Push a list in the range [0,10]
    δ            #  Pop both lists, and apply double-vectorized:
     *           #   Multiply the values together
      5*         # Multiply each value by 5
        TÝš      # Prepend list [0,10] to this matrix
           ε  }  # Map over each row:
            Nš   #  Prepend the 0-based map-index to the list
§                # (workaround: cast every integer to a string)
 3j              # Prepend leading spaces where necessary so each string is of length 3
   »             # Join each inner list of strings with space delimiter,
                 # and then each string with newline delimiter
      ǝ          # Replace the character
     2           # at (0-based) index 2 (which is the first '0')
    ð            # with a space
                 # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Python, 97 bytes

```
[print(("%4s"*12%x)[1:])for x in[(" ",*range(11))]+[(c,*range(0,c*50+1,5*c))for c in range(1,6)]]

```

Attempt This Online!

# Answer
> 2 votes
# Kotlin, ~~118 bytes~~ 97 bytes

```
fun main() = println((0..5).joinToString("\n") { j -> (0..10).joinToString(" ") { i -> "${i * j * 5}".padStart(3) } })

```

Try it online!

I've removed about 21 bytes thanks to The Thonnu because I forgot to remove spaces, also I've used `"%3d".format()` to pad the numbers to a width of 3 characters.

```
fun main()=println((0..5).joinToString("\n"){j->(0..10).joinToString(" "){"%3d".format(it*j*5)}})

```

Try it online!

# Answer
> 1 votes
# BQN (CBQN), 128 bytes

This is definitely sub-optimal. I don't really know what I'm doing with this language.

```
•Out ¯1↓⥊(1↓˘∾˘⍉(/⟜" "∘(4-≠)∾⊢)¨•Fmt¨[↕6]∾⍉[↕11]∾5××´¨1↓↕6‿11)∾˘6‿1⥊@+10

```

Attempt This Online!

# Answer
> 1 votes
# Jelly, 16 bytes

```
⁵Żð⁶;W;Gµ5×1;×þ5

```

Try it online!

```
   ð⁶;W;Gµ          [[" "] + a] + f(a), as a grid
                    where
 ⁵Ż                 a    = [0…10]
          5×1;×þ5   f(r) = table of [1]+(5×r) times [1…5]

```

# Answer
> 1 votes
# Java, 112 bytes

```
v->{var r="";for(int i=-1,j;i++<5;r+="\n")for(j=-2;j++<10;)r+=r.format("%4s",i<1?j<0?r:j:j<0?i:i*j*5);return r;}

```

Try it online.

**Explanation:**

```
v->{                      // Method with empty unused parameter and String return-type
  var r="";               //  Result-String, starting empty
  for(int i=-1,j;i++<5    //  Loop `i` in the range (-1,5]:
      ;                   //    After every iteration:
       r+="\n")           //     Append a newline to the result-String
    for(j=-2;j++<10;)     //   Inner loop `j` in the range (-2,10]:
      r+=r.format("%4s",  //    Append the following with up to 4 leading spaces to the
                          //    result-String:
          i<1?i<j?        //     If it's the first row and column:
            r             //      Append the result-String itself, which is still "" at
                          //      this point
          :               //     Else-if it's the first row, but NOT the first column:
            j             //      Append `j`
          :j<0?           //     Else-if it's the first column, but NOT the first row:
            i             //      Append `i`
          :               //     Else (it's neither the first row nor column):
            i*j*5);       //      Append `i` multiplied by `j` multiplied by 5
  return r;}              //  After the nested loops, return the result-String

```

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


title: Calculate average characters of string

text:
# Question
Title: Calculate average characters of string
# Task

Your task is to produce string that contains average characters of string. First character of result would be average character of first character (which is first character) and second character average of two first characters and so on.

# What is average character?

Strings are arrays of bytes. *Average character* of string can be found by calculating the average of the ASCII values of characters in string and taking corresponding ASCII character.

For example string `"Hello!"` can be written as byte sequence `72 101 108 108 111 33`. Average of ascii values is 533/6 = 88.833... and when it's rounded to nearest integer we get 89 which is ascii code for captial letter `Y`.

# Rules

* You can assume that input contains only printable ASCII characters
* Input can be read from stdin or as command line arguments or as function arguments
* Output must be stdout. If your program is function, you can also return the string you would otherwise print.
* It must be whole program or function, not snippet
* Standard loopholes apply
* Integers are rounded by function `floor(x+0.5)` or similar function.

# How do I win?

This is , so shortest answer (in bytes) in wins.

# Examples

* `Hello!``HW^adY`
* `test``tmop`
* `42``43`
* `StackExchange``Sdccd_ccccddd`

# Answer
> 14 votes
## Brainfuck 106 bytes

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

```

This is my first participation in a code-golf, please be gentle! It does work but brainfuck can't handle floats (not that i know of) so the rounded value is always the bottom one (might fix my algorithm later).

Also, the algorithm averages the values 2 by 2, meaning it could be innacurate in some spots. And I need to fix a bug that is printing a number at the end of the output too.

# Answer
> 10 votes
# Pyth, 16 bytes

```
smCs+.5csaYCdlYz

```

Pretty straightforward. Using `s+.5` instead of rounding, because for some reason `round(0.5, 0)` is 0 in Python.

# Answer
> 7 votes
# Q, ~~15~~ 12 bytes

12 bytes as an expression

```
"c"$avgs"i"$

q)"c"$avgs"i"$"Hello!"
"HW^adY"
q)"c"$avgs"i"$"test"
"tmop"
q)"c"$avgs"i"$"42"
"43"
q)"c"$avgs"i"$"StackExchange"
"Sdccd_ccccddd"

```

or 15 bytes as a function

```
{"c"$avgs"i"$x}

q){"c"$avgs"i"$x} "Hello!"
"HW^adY"
q){"c"$avgs"i"$x} "test"
"tmop"
q){"c"$avgs"i"$x} "42"
"43"
q){"c"$avgs"i"$x} "StackExchange"
"Sdccd_ccccddd"

```

takes advantage of

1. the "i"$ cast to convert a string (list of characters) to a list of integers
2. the avgs function, which computes the running average of a list as a list of floats
3. the "c"$ cast to convert a list of floats to a list of characters, and which automatically rounds each float to the nearest integer before doing so \[i.e. ("c"$99.5) = ("c"$100) and ("c"$99.4) = ("c"$99) \]

# Answer
> 4 votes
# CJam, 19 bytes

```
Uq{i+_U):Ud/moco}/;

```

Try it online in the CJam interpreter.

# Answer
> 4 votes
# Perl: ~~31~~ 30 characters

(29 characters code + 1 character command line option.)

```
s!.!chr.5+($s+=ord$&)/++$c!ge

```

Sample run:

```
bash-4.3$ perl -pe 's!.!chr.5+($s+=ord$&)/++$c!ge' <<< 'StackExchange'
Sdccd_ccccddd

```

# Answer
> 4 votes
# Python 3, 65 bytes

```
n=t=0
for c in input():n+=1;t+=ord(c);print(end=chr(int(.5+t/n)))

```

Try it online!

If I use `round()` instead of `int(.5+` etc., it saves one character but is *technically* not in compliance with the challenge: Python's `round()` rounds halves to the nearest even integer, not upwards. However, it works correctly on all sample inputs.

# Answer
> 3 votes
# C# ~~189 135 134~~ 106 Bytes

```
var x=s.Select((t,i)=>Math.Round(s.Select(a=>(int)a).Take(i+1).Average())).Aggregate("",(m,c)=>m+(char)c);

```

Can be seen here

First time golfer

# Answer
> 3 votes
# Ruby, 46

```
s=0.0
$<.bytes{|b|s+=b;$><<'%c'%(0.5+s/$.+=1)}

```

ideone.

With apologies to w0lf, my answer ended up different enough that it seemed worth posting.

`$<.bytes` iterates over each byte in stdin, so we print the rolling average in each loop. '%c' converts a float to a character by rounding down and taking the ASCII, so all we have to do is add 0.5 to make it round properly. `$.` is a magic variable that starts off initialized to 0--it's supposed to store the line count, but since here we want byte count we just increment it manually.

# Answer
> 3 votes
# JavaScript (ES6), 75 bytes

```
let f =
s=>s.replace(/./g,x=>String.fromCharCode((t+=x.charCodeAt())/++i+.5),i=t=0)
```

```
<input oninput="O.value=f(this.value)" value="Hello!"><br>
<input id=O value="HW^adY" disabled>
```

I can't believe there's no JS answer with this technique yet...

# Answer
> 3 votes
# Python 2, 65 bytes

```
f=lambda s:s and f(s[:-1])+chr(int(sum(map(ord,s))*1./len(s)+.5))

```

Try it online!

# Answer
> 3 votes
# Ruby, 27 bytes

```
putc gets.sum.quo(~/$/)+0.5

```

Solution produced through some collaborative golfing at work.

## How this works

* `Kernel#putc` prints a single character (e.g. `putc "Hello"` outputs `H`). Passing an object to it prints the character whose code is the least-significant byte of the object. So `putc 72` outputs `H`.
* `Kernel#gets` reads stdin and returns a string.
* `String#sum` returns a checksum. The result is the sum of the binary value of each byte in the string modulo `2**16 - 1`. Since ASCII bytes comfortably fit in this space, this just returns the byte total.
* Because the byte total is an integer, we can’t do floating point calculations (in Ruby `10 / 3` is `3` whereas `10.to_f / 3` is `3.33…`). Here’s where `Numeric#quo` comes in – `10.quo(3)` returns the Rational `(10/3)`.
* `Regexp#~` matches a regular expression against the contents of `$_` (the last string read by `gets`). It returns index of the match.
* The Regexp `/$/` matches the end of the string, so `~/$/` means “print the index of the end of the string” – in other words, the string length. This gives us the final is a short-hand for the length of the string read by `gets`.
* This gives us the Rational (byte total/string length). Now we need to round it into an integer. `+0.5` casts the Rational to a float. `putc` floors the float into an integer.

# Answer
> 2 votes
# Julia, ~~85~~ 81 bytes

```
s->(i=[int(c)for c=s];print(join([char(iround(mean(i[1:j])))for j=1:length(i)])))

```

This creates an unnamed function that accepts a string and creates a vector of its ASCII code points. Means are taken for each sequential group, rounded to integers, converted to characters, joined into a string, and printed to STDOUT.

# Answer
> 2 votes
# K, 36 bytes

```
`0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic

```

Usage:

```
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"Hello!"
HW^adY
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"test"
tmop
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"42"
43
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"StackExchange"
Sdccd_ccccddd

```

`_ci` and `_ic` convert ascii to chars and vice versa, respectively. `{(+/x)%#x}` is a classic K idiom for calculating a mean. Pretty straightforward overall.

Edit: oh, misread the spec. \`0: is needed to print the result to stdout. Waiting for clarification on input re. Dennis' question.

# Answer
> 2 votes
## Python 2, 71

```
i=s=0
r=''
for c in input():s+=ord(c);i+=1.;r+=chr(int(s/i+.5))
print r

```

With each new character, updates the character sum `s` and the number of characters `i` to compute and append the average character.

# Answer
> 2 votes
# Matlab, ~~43~~ 31 bytes

*Thanks to @beaker for 9 bytes off!*

Using an anonymous function:

```
@(s)[cumsum(+s)./find(s)+.5 '']

```

Examples:

```
>> @(s)[cumsum(+s)./find(s)+.5 '']
ans =
  function_handle with value:
    @(s)[cumsum(+s)./(find(s))+.5 '']
>> f=ans;
>> f('Hello!')
ans =
    'HW^adY'
>> f('test')
ans =
    'tmop'
>> f('42')
ans =
    '43'
>> f('StackExchange')
ans =
    'Sdccd_ccccddd'

```

# Answer
> 2 votes
# Mathematica, 75 bytes

```
FromCharacterCode@Floor[.5+Accumulate@#/Range@Length@#]&@ToCharacterCode@#&

```

# Answer
> 2 votes
# Mathcad, 60 "bytes"

Mathcad is mathematical application based on 2D worksheets comprised of "regions" each of which can be text, a mathematical expression, program, plot or scripted component.

A mathematical or programming instruction is picked from a palette toolbar or entered using a keyboard shortcut. For golfing purposes, an operation ("byte") is taken to be the number of keyboard operations necessary to create a name or expression (for example, to set the variable a to 3, we would write a:=3. The definition operator := is a single keypress ":", as are a and 3 giving a total of 3 "bytes". The programming ***for*** operator requires typing ctl-shft-# (or a single click on the programming toolbar) so again is equivalent to 1 byte.

In Mathcad the user enters programming language commands using keyboard shortcuts (or picking them from the Programming Toolbar) rather than writing them in text. For example, typing ctl-\] creates a while-loop operator that has two "placeholders" for entering the condition and a single line of the body, respectively. Typing = at the end of a Mathcad expressions causes Mathcad to evaluate the expression.

(Count bytes) By looking at it from a user input perspective and equating one Mathcad input operation (keyboard usually, mouse-click on toolbar if no kbd shortcut) to a character and interpreting this as a byte. csort = 5 bytes as it's typed char-by-char as are other variable/function names. The for operator is a special construct that occupies 11 characters (including 3 blank "placeholders" and 3 spaces) but is entered by ctl-shft-#, hence = 1 byte (similar to tokens in some languages). Typing ' (quote) creates balanced parentheses (usually) so counts as 1 byte. Indexing v = 3 bytes (type v\[k).

# Answer
> 2 votes
# 05AB1E, 15 bytes

```
.pvyDSÇOsg/îç}J

```

Try it online!

# Answer
> 2 votes
# Japt, 13 bytes

```
£T±Xc)/°Y r d

```

Test it online!

### How it works

```
£   T± Xc)/° Y r d
mXY{T+=Xc)/++Y r d}
                     // Implicit: U = input string, T = 0
mXY{              }  // Replace each char X and index Y in the string by this function:
    T+=Xc            //   Add X.charCodeAt() to T.
         )/++Y       //   Take T / (Y + 1).
               r d   //   Round, and convert to a character.
                     // Implicit: output result of last expression

```

# Answer
> 2 votes
# Japt, 11 bytes

```
c@V±X /°T r

```

Try it

# Answer
> 2 votes
**PHP**, **176 byte**

```
<?=(implode('',array_reduce(str_split($argv[1]),function($c,$k){array_push($c[1],chr(floor(((ord($k)+$c[0])/(count($c[1])+1))+0.5)));return[ord($k)+$c[0],$c[1]];},[0,[]])[1]));

```

Example:

```
>php cg.php Hello!
HW^adY
>php cg.php test
tmop
>php cg.php 42
43

```

The biggest solution so far, but based on php it can't get much shorter I think. 2 bytes could be saved by removing the newlines.

# Answer
> 2 votes
# Zig 0.6.0, 84 bytes

```
fn a(b:[]u8)void{var t:u64=0;for(b)|c,i|{t+=c;b[i]=@intCast(u8,(t+(i+1)/2)/(i+1));}}

```

Try it Online

Formatted:

```
fn a(b: []u8) void {
    var t: u64 = 0;
    for (b) |c, i| {
        t += c;
        b[i] = @intCast(u8, (t + (i+1)/2) / (i+1));
    }
}

```

# Answer
> 2 votes
# PHP 7, 79 bytes

As I don't have enough reputation to comment on cb0's answer to provide him hints to improve his answer (mainly using the char index method in a string and while to loop through a string). But I still bothered to post it due to the large reduction in byte count.

```
<?php $i=$b=0;while($a=ord($argv[1][$i++]??'')){$b+=$a;echo chr(round($b/$i));}

```

I didn't find a way though to use the `<?=` shortcut and avoid undefined errors without using command line flags (this is why i used `$i=$b=0;`). This answer does not work in PHP 5 due to the `??` syntax.

# Answer
> 2 votes
# Vyxal `s`, 7 bytes

```
CKvṁ.+C

```

Try it Online!

`.+` should be , but there's a bug.

# Answer
> 2 votes
# Knight, 62 bytes

```
;;=sP=i 0W<=i+1i+1Ls;=aGs=t 0i;Wa;=t+tAa=aGa 1LaO+A/+t/i 2i"\"

```

Try it online!

# Answer
> 2 votes
# Jelly, 7 bytes

```
OÆmƤ+.Ọ

```

Try it online!

```
OÆmƤ+.Ọ
O       - Get a list of character codes from the input string
   Ƥ    - Over prefixes:
 Æm     -  Get the mean
    +.  - To each, add 0.5
      Ọ - Convert from character codes to charcters. Decimals are rounded down.

```

# Answer
> 2 votes
# brev, 146 bytes

```
(as-list reverse(c pair-fold-right(fn(cons(integer->char(inexact->exact(floor(+(/(apply + x)(length x))0.5))))y))'())reverse(c map char->integer))

```

124 with banker's rounding:

```
(as-list reverse(c pair-fold-right(fn(cons(integer->char(round(/(apply + x)(length x))))y))'())reverse(c map char->integer))

```

Which is still a lot. It's clear that a huge painpoint in brev is the type converting (chars to integers, strings to lists etc).

# Answer
> 2 votes
# Dart, 76 bytes

```
t(a,[c=1,s=0])=>String.fromCharCodes([...a.runes.map((i)=>(s+=i+.5)~/c++)]);

```

Try it online!

# Answer
> 2 votes
# , 22 bytes

```
(0.5<.@++/%#)\&.(3&u:)

```

Try it online!

## Explanation

```
(0.5<.@++/%#)\&.(3&u:)
              &.(    )  do this, the left verb then the inverse of this:
                 3&u:     characters -> ordinates
(           )\          over the prefixes of the input:
        +/%#            take the average (sum divide length)
 0.5   +                add one-half
    <.@                 then floor

```

# Answer
> 1 votes
# C, 62 bytes

```
c;t;main(n){for(;(c=getchar())>0;n++)putchar(((t+=c)+n/2)/n);}

```

(ideone link)

The results are slightly different from the OP's examples, but only because this code rounds 0.5 down instead of up. Not any more!

# Answer
> 1 votes
# R, ~~135~~ 127 Bytes

This got long real quick and I really got it wrong the first time:) Need to read the questions properly.

```
cat(sapply(substring(a<-scan(,''),1,1:nchar(a)),function(x)rawToChar(as.raw(round(mean(as.integer(charToRaw(x)))+.5)))),sep='')

```

Test Run

```
cat(sapply(substring(a<-scan(,''),1,1:nchar(a)),function(x)rawToChar(as.raw(round(mean(as.integer(charToRaw(x)))+.5)))),sep='')
1: Hello!
2:
Read 1 item
HW^adY

```

# Answer
> 1 votes
### Ruby 59 ~~61~~

```
->w{s=c=0.0;w.chars.map{|l|s+=l.ord;(s/c+=1).round.chr}*''}

```

Test: http://ideone.com/dT7orT

# Answer
> 1 votes
# Java, 100

Much like many other answers here, I'm summing and averaging in a loop. Just here to represent Java :)

```
void f(char[]z){float s=0;for(int i=0;i<z.length;System.out.print((char)Math.round(s/++i)))s+=z[i];}

```

My original code is a 97, but it only returns the modified `char[]` rather than printing it:

```
char[]g(char[]z){float s=0;for(int i=0;i<z.length;z[i]=(char)Math.round(s/++i))s+=z[i];return z;}

```

Now, it's *just* long enough for scrollbars to appear for me, so here's a version with some line breaks, just because:

```
void f(char[]z){
    float s=0;
    for(int i=0;
            i<z.length;
            System.out.print((char)Math.round(s/++i)))
        s+=z[i];
}

```

# Answer
> 1 votes
# Perl 5, 41 bytes

```
say map{$s+=ord;chr($s/++$c+.5)}pop=~/./g

```

run as

```
$ perl -E 'say map{$s+=ord;chr($s/++$c+.5)}pop=~/./g' StackExchange
Sdccd_ccccddd

```

# Answer
> 1 votes
## TSQL, 118 bytes

```
DECLARE @ varchar(400) = 'StackExchange'

SELECT
top(len(@))char(avg(ascii(stuff(@,1,number,''))+.5)over(order by number))FROM
master..spt_values
WHERE'P'=type

```

Returning characters vertical

```
S
d
c
c
d
_
c
c
c
c
d
d
d

```

# Answer
> 1 votes
# \>\<\>, 30 bytes

```
i:0(?v
v &l~<
\+l2(?
\&,12,+o;

```
* The first line reads from stdin and puts the characters on the stack
* The second will remove the EOL char, take the size of the stack and put it in the `&` register
* The third line will add numbers on the stack while there are two or more of them
* The fourth line will divide the resulting number by the register's value, then add 1/2, output the value as a character and stop. When faced with a float value when displaying a char, \>\<\> will floor it, which is why we added 1/2

You can try it on the online interpreter but then you need to use the following version, because the online interpreter pads the code box to a rectangle and applies `?` to spaces.

```
i:0(?v
v &l~<
\+l2(   ?
\&,12,+o;

```

# Answer
> 1 votes
# Jelly, 16 bytes

```
S÷L+.Ḟ
OµḣLR$Ç€Ọ

```

Try it online!

Only if there were Average and Round built-ins...

# Answer
> 1 votes
# SmileBASIC, 65 bytes

```
LINPUT S$FOR I=1TO LEN(S$)A=A-A/I+ASC(S$[I-1])/I?CHR$(A+.5);
NEXT

```

# Answer
> 1 votes
## Clojure, 69 bytes

```
#(for[c(map /(reductions +(map int %))(rest(range)))](char(+ c 0.5)))

```

Returns a sequence of characters, arguably a string-like construct. Would need an `#(apply str(for[...]...))` to convert it into a string.

# Answer
> 1 votes
# Jelly, 8 bytes

```
OÆmƤ+.ḞỌ

```

Try it online!

# Answer
> 1 votes
# Husk, 10 bytes

```
zȯci/Nt∫mc

```

Try it online!

```
                                                    | "tuna"
         mc  -- map each character to ASCII value   | [116,117,110,97]
       t∫    -- prefix sums & drop leading 0        | [116,233,343,440]
z(   )N      -- zip the list with [1..] using       |
    /        --   divide                            | [116/1,233/2,343/3,440/4] == [116.0,116.5,114.̅3,110.0]
   i         --   round                             | [116,117,114,110]
  c          --   convert to character              | "turn"

```

# Answer
> 1 votes
# , 23 bytes

```
(0.5<.@++/%#)&.(a.&i.)\

```

Try it online!

### How it works

```
                      \  on prefixes
               (   i.)   index of the first occurence
               (  &  )   in
               (a.   )   the character set
            x&.y         apply y, then x, then the inverse of y,
(0.5        )              that is the element of a. with a given index
(       +/  )            sum
(          #)            number of elements
(         % )            division
(   <.@+    )            add, then floor

```

# Answer
> 1 votes
# Zsh, 52 bytes

```
for c (${(s::)1})printf ${(#)$((.5+(n+=0.+#c)/++i))}

```

Try it online!

In arithmetic mode, `#c` gets the code of the first character of `$c`. The parameter expansion `${(#) }` prints the character associated with the code.

# Answer
> 1 votes
# PowerShell, 59 bytes

```
-join($args|%{[char][int][Math]::Floor(($s+=+$_)/++$i+.5)})

```

Try it online!

# Answer
> 1 votes
# Dyalog APL, 25 bytes

```
{⎕UCS⌊.5+(+\C)÷⍳⍴C←⎕UCS⍵}

```

# Answer
> 1 votes
# PARI/GP, 45 bytes

```
s->t=i=0;Strchr([(t+=c)\/i++|c<-Vecsmall(s)])
```

Attempt This Online!

---

# PARI/GP, 52 bytes

```
s->Strchr(Vec(intformal(Ser(Vecsmall(s))/(1-x)))\/1)
```

Attempt This Online!

This one is longer, but I can't resist to do this:

* `Vecsmall(s)`: Converts the string to a vector of ASCII codes.
* `Ser(...)`: Converts the vector to a formal power series.
* `.../(1-x)`: Divides the result by \\$1-x\\$. This is equivalent to taking the cumsum.
* `intformal(...)`: Takes the integral with respect to \\$x\\$. This is equivalent to dividing the `n`-th term with `n`.
* `Vec(...)`: Converts the result back to a vector.
* `...\/1`: Rounds the result.
* `Strchr(...)` Converts the result back to a string.

# Answer
> 1 votes
# C (clang), 55 bytes

```
n;t;main(c){for(;read(0,&c,1);putchar(t/++n))t+=c+n%2;}

```

Try it online!

### How it works

```
n;t;           // t and n are initialized to 0
read(0,&c,1)   // Reads a character from stdin into c,
               // returns the number of characters read, 0 if EOF.
t+=c+n%2       // t is the accumulator, n%2 is used to round up.
putchar(t/++n) // increment n and use the new value to calculate the average.

```

---

# C (clang), 45 bytes

*Same idea, but as a function which modifies the string in-place.*

```
n;t;f(*s){for(n=t=0;*s;*s++=t/++n)t+=*s+n%2;}

```

Try it online!

# Answer
> 1 votes
# Burlesque, 21 bytes

```
)?^qavpa0.5?+)avqL[\m

```

Try it online!

```
)?^   # To codepoint
qavpa # Average on prefixes
0.5?+ # Add 0.5 to each
)av   # Floor each
qL[\m # Back to char

```

Should be 17 chars, but `R_` (round) rounds 0.5 down, not up.

# Answer
> 1 votes
# Prolog (SWI), 59 bytes

```
N+X+[A|R]:-L=X+A,T is round(L/N),put(T),N+1+L+R.
+A:-1+0+A.

```

Try it online!

Takes a list of codepoints and outputs to STDOUT.

A little longer, but using only one predicate:

## Prolog (SWI), 63 bytes

```
+A:-scanl(plus,A,0,Z),nth0(N,Z,E),N>0,T is round(E/N),\+put(T).

```

Try it online!

# Answer
> 1 votes
# Thunno 2 `B`, 5 bytes

```
ƒ€m.+

```

Attempt This Online!

#### Explanation

```
ƒ€m.+  # Implicit input
       # Convert to ordinals
ƒ      # Prefixes of ordinals
 €m    # Mean of each
   .+  # Add 0.5 to each
       # Convert to string
       # Implicit output

```

# Answer
> 1 votes
# Scala, 106 bytes

Port of @alephalpha's PARI/GP answer in Scala.

---

Golfed version. Attempt This Online!

```
s=>{var(t,i)=(0.0,1);s.map(c=>{t+=c;val a=math.round(t/i).toInt.max(32).min(126);i+=1;a.toChar}).mkString}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def f(s: String): String = {
    val vecsmall: Array[Int] = s.map(_.toInt).toArray
    var t = 0.0
    var i = 1
    var res = new StringBuilder

    for (c <- vecsmall) {
      t += c
      val ascii = Math.round(t / i).toInt.max(32).min(126) // ensure within printable ASCII range
      res += ascii.toChar
      i += 1
    }

    res.toString()
  }

  def main(args: Array[String]): Unit = {
    val strings = List("Hello!", "test", "42", "StackExchange")
    strings.foreach(s => println(s"$s -> ${f(s)}"))
  }
}

```

# Answer
> 0 votes
# JavaScript ES7, 122 bytes

```
s=>String.fromCharCode(...[for(i of s)i.charCodeAt()].map((l,i,a)=>Math.round(eval((t=a.slice(0,++i)).join`+`)/t.length)))

```

Mostly everything is happening in this bit

```
eval((t=a.slice(0,++i)).join`+`)/t.length)

```

The rest is looping / character code conversion

Split up:

```
s=>
 String.fromCharCode(...                        ) // Converts average character code array to string, ... allows it to take an array
   [for(i of s)i.charCodeAt()]                    // Converts string to char code array
   .map((l,i,a)=>                             )   // Loops through each character
     Math.round(                    /t.length)    // Rounds sum of previous char codes, divides by position + 1
       eval(                       )              // evals string of char codes seperated with +
            (                ).join`+`            // joins previous char codes with +
             t=a.slice(0,++i)                     // creates an array with all the char codes

```

---

If functions aren't allowed:

```
alert(String.fromCharCode(...[for(i of prompt())i.charCodeAt()].map((l,i,a)=>Math.round(eval((t=a.slice(0,++i)).join`+`)/t.length))))

```

<sub>**133 bytes**</sub>

---

ES5 Snippet:

```
function _toConsumableArray(r){if(Array.isArray(r)){for(var e=0,t=Array(r.length);e<r.length;e++)t[e]=r[e];return t}return Array.from(r)}function _taggedTemplateLiteral(r,e){return Object.freeze(Object.defineProperties(r,{raw:{value:Object.freeze(e)}}))}var _templateObject=_taggedTemplateLiteral(["+"],["+"]),f,t=function t(s){return String.fromCharCode.apply(String,_toConsumableArray(function(){var r=[],e=!0,t=!1,a=void 0;try{for(var n,i=s[Symbol.iterator]();!(e=(n=i.next()).done);e=!0){var o=n.value;r.push(o.charCodeAt())}}catch(l){t=!0,a=l}finally{try{!e&&i["return"]&&i["return"]()}finally{if(t)throw a}}return r}().map(function(l,i,a){return Math.round(eval((f=a.slice(0,++i)).join(_templateObject))/f.length)})))};

// Demo
document.getElementById('go').onclick=function(){
  document.getElementById('output').innerHTML = t(document.getElementById('input').value)
};
```

```
<div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Average of Words Snippet</h2><div><div  style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Text here..." style="resize:none;border:1px solid #DDD;" id="input"><button id='go'>Run!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div>
```

# Answer
> 0 votes
# Python 2, 106 bytes

It's not short enough. Since it's python it's way too verbose, you can even read what it does by looking code. But it's working.

```
a=[.0]+[ord(i)for i in raw_input()]
print"".join([chr(int(.5+(sum(a[:i+1])/i)))for i in range(1,len(a))])

```

# Answer
> 0 votes
# JavaScript ES6, 111 bytes

```
w=>w.replace(/./g,(_,i)=>String.fromCharCode([for(f of w.slice(0,++i))f.charCodeAt()].reduce((a,b)=>a+b)/i+.5))

```

This is annoyingly long thanks in part to JavaScript's long `String.fromCharCode` and `charCodeAt` functions. The stack snippet contains ungolfed, commented, testable code.

```
f=function(w){
  return w.replace(/./g,function(e,i){
    return String.fromCharCode(w.slice(0,++i).split('').map(function(f){
      return f.charCodeAt()
    }).reduce(function(a,b){
      // Adds all numbers in the array
      return a+b
      // String.fromCharCode automatically floors numbers, so we add .5 to round up
    })/i+.5)
  })
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run()
```

```
<input type="text" id="input" value="Hello!" /><button id="run">Run</button><br />
<pre id="output"></pre>
```

# Answer
> 0 votes
# Factor, 80 bytes

```
[ cum-sum [ dup zero? 1 0 ? + / ] map-index [ .5 + floor >fixnum ] map >string ]

```

# Answer
> 0 votes
# Jelly, 7 bytes

```
OÄ÷T+.Ọ
```

```
OÄ÷T+.Ọ  ~Main link
O        ~Cast to number
 Ä       ~Cumulative sum; add the values
  ÷T     ~Divide by indices
    +.   ~Add .5
      Ọ  ~Cast to characters

```

Attempt This Online!

# Answer
> 0 votes
# Python, 50 bytes

```
f=lambda s:s and f(s[:-1])+[int(.5+sum(s)/len(s))]

```

Attempt This Online!

Takes in an list of UTF-8 codepoints, return a list of UTF-8 codepoints.

# Answer
> 0 votes
# C#, 210 bytes

*Saved so many bytes thanks to the comment of @ceilingcat*

---

Golfed version. Try it online!

```
static string F(string s){int j=s.Length,i=j;var v=new int[j];var t=.0;var r="";for(;i-->0;)v[i]=Convert.ToInt32(s[i]);for(;++i<j;)r+=((char)Math.Min(Math.Max((int)Math.Round((t+=v[i])/-~i),32),126));return r;}

```

Ungolfed version. Run it on dotnetfiddle!

```
using System;
using System.Text;

public class Program
{
    public static string ConvertString(string s)
    {
        int[] vecsmall = new int[s.Length];
        for(int j = 0; j < s.Length; j++)
        {
            vecsmall[j] = Convert.ToInt32(s[j]);
        }

        double t = 0.0;
        int i = 1;
        StringBuilder res = new StringBuilder();

        foreach(int c in vecsmall)
        {
            t += c;
            int ascii = (int)Math.Round(t / i);
            ascii = Math.Max(ascii, 32); // ensure within printable ASCII range
            ascii = Math.Min(ascii, 126); // ensure within printable ASCII range

            res.Append((char)ascii);
            i += 1;
        }

        return res.ToString();
    }

    public static void Main(string[] args)
    {
        string[] strings = new string[] {"Hello!", "test", "42", "StackExchange"};

        foreach(string s in strings)
        {
            Console.WriteLine($"{s} -> {ConvertString(s)}");
        }
    }
}

```

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


title: Multiply Quaternions

text:
# Question
Title: Multiply Quaternions
Write a named function or program that computes the quaternion product of two quaternions. Use as few bytes as possible.

## Quaternions

Quaternions are an extension of the real numbers that further extends the complex numbers. Rather than a single imaginary unit `i`, quaternions use three imaginary units `i,j,k` that satisfy the relationships.

```
i*i = j*j = k*k = -1
i*j =  k
j*i = -k
j*k =  i
k*j = -i
k*i =  j
i*k = -j

```

(There's also tables of these on the Wikipedia page.)

In words, each imaginary unit squares to `-1`, and the product of two different imaginary units is the remaining third one with a `+/-` depending on whether the cyclic order `(i,j,k)` is respected (i.e., the right-hand-rule). So, the order of multiplication matters.

A general quaternion is a linear combination of a real part and the three imaginary units. So, it is described by four real numbers `(a,b,c,d)`.

`x = a + b*i + c*j + d*k`

So, we can multiply two quaternions using the distributive property, being careful to multiply the units in the right order, and grouping like terms in the result.

```
(a + b*i + c*j + d*k) * (e + f*i + g*j + h*k)
= (a*e - b*f - c*g - d*h)    +
  (a*f + b*e + c*h - d*g)*i  +
  (a*g - b*h + c*e + d*f)*j  +
  (a*h + b*g - c*f + d*e)*k

```

Seen this way, quaternion multiplication can be seen as a map from a pair of 4-tuples to a single 4-tuples, which is what you're asked to implement.

## Format

You should write either a *program* or *named function*. A program should take inputs from STDIN and print out the result. A function should take in function inputs and return (not print) an output.

Input and output formats are flexible. The input is eight real numbers (the coefficients for two quaternions), and the output consists of four real numbers. The input might be eight numbers, two lists of four numbers, a 2x4 matrix, etc. The input/output format don't have to be the same.The ordering of the `(1,i,j,k)` coefficients is up to you.

The coefficients can be negative or non-whole. Don't worry about real precision or overflows.

**Banned:** Function or types specifically for quaternions or equivalents.

## Test cases

These are in `(1,i,j,k)` coefficient format.

```
[[12, 54, -2, 23], [1, 4, 6, -2]]
 [-146, -32, 270, 331]

[[1, 4, 6, -2], [12, 54, -2, 23]]
 [-146, 236, -130, -333]

[[3.5, 4.6, -0.24, 0], [2.1, -3, -4.3, -12]]
 [20.118, 2.04, 39.646, -62.5]

```

## Reference Implementation

In Python, as function:

```
#Input quaternions: [a,b,c,d], [e,f,g,h]
#Coeff order: [1,i,j,k]

def mult(a,b,c,d,e,f,g,h):
    coeff_1 = a*e-b*f-c*g-d*h
    coeff_i = a*f+b*e+c*h-d*g
    coeff_j = a*g-b*h+c*e+d*f
    coeff_k = a*h+b*g-c*f+d*e

    result = [coeff_1, coeff_i, coeff_j, coeff_k]
    return result

```

# Answer
# CJam, ~~49~~ ~~45~~ 39 bytes

```
"cM-^\M-^G-^^KM-zP"256bGbq~m*f{=:*}4/{:-W*}/W*]`

```

The above uses caret and M notation, since the code contains unprintable characters.

At the cost of two additional bytes, those characters can be avoided:

```
6Z9C8 7YDXE4BFA5U]q~m*f{=:*}4/{:-W*}/W*]`

```

You can try this version online: CJam interpreter

### Test cases

To calculate `(a + bi + cj + dk) * (e + fi + gj + hk)`, use the following input:

```
[ d c b a ] [ h g f e ]

```

The output will be

```
[ z y x w ]

```

which corresponds to the quaternion `w + xi + yj + zk`.

```
$ base64 -d > product.cjam <<< ImOchy0eS/pQIjI1NmJHYnF+bSpmez06Kn00L3s6LVcqfS9XKl1g
$ wc -c product.cjam
39 product.cjam
$ LANG=en_US cjam product.cjam <<< "[23 -2 54 12] [-2 6 4 1]"; echo
[331 270 -32 -146]
$ LANG=en_US cjam product.cjam <<< "[-2 6 4 1] [23 -2 54 12]"; echo
[-333 -130 236 -146]
$ LANG=en_US cjam product.cjam <<< "[0 -0.24 4.6 3.5] [-12 -4.3 -3 2.1]"; echo
[-62.5 39.646 2.04 20.118]

```

### How it works

```
6Z9C8 7YDXE4BFA5U]  " Push the array [ 6 3 9 12 8 7 2 13 1 14 4 11 15 10 5 0].         ";
q~                  " Read from STDIN and interpret the input.                         ";
m*                  " Compute the cartesian product of the input arrays.               ";
f                   " Execute the following for each element of the first array:       ";
{                   " Push the cartesian product (implicit).                           ";
    =               " Retrieve the corresponding pair of coefficients.                 ";
    :*              " Calculate their product.                                         ";
}                   "                                                                  ";
4/                  " Split into chunks of 4 elements.                                 ";
{:-W*}/             " For each, subtract the first element from the sum of the others. ";
W*                  " Multiply the last integers (coefficient of 1) by -1.             ";
]`                  " Collect the results into an array and stringify it.              ";

```
> 4 votes

# Answer
## Python (83)

```
r=lambda A,B,R=range(4):[sum(A[m]*B[m^p]*(-1)**(14672>>p+4*m)for m in R)for p in R]

```

Takes two lists `A,B` in `[1,i,j,k]` order and returns a result in the same format.

The key idea is that with `[1,i,j,k]` corresponding to indices `[0,1,2,3]`, you get the product's index (up to sign) by XOR'ing the indices. So, the terms that get placed in index `p` are those who indices XOR to `p`, and are thus the products `A[m]*B[m^p]`.

It only remains to make the signs work out. The shortest way I found was to simply code them into a magic string. The 16 possibilities for `(m,p)` are turned into numbers `0` to `15` as `p+4*m`. The number `14672` in binary has `1`'s at the places where `-1` signs are needed. By shifting it the appropriate number of places , a `1` or `0` winds up at the last digit, making the number odd or even, and so `(-1)**` is either `1` or `-1` as needed.
> 7 votes

# Answer
# Python - ~~90 75 72~~ 69

**Pure Python, no libraries - 90:**

```
m=lambda a,b,c,d,e,f,g,h:[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

```

It's probably pretty hard to shorten this "default" solution in Python. But I'm very curious as to what other might come up with. :)

---

**Using NumPy - ~~75 72~~ 69:**

Well, since the input and output are rather flexible, we can use some NumPy functions and exploit the scalar-vector representation:

```
import numpy
m=lambda s,p,t,q:[s*t-sum(p*q),s*q+t*p+numpy.cross(p,q)]

```

Input arguments `s` and `t` are the scalar parts of the two quaternions (the real parts) and `p` and `q` are the corresponding vector parts (the imaginary units). Output is a list containing scalar part and vector part of the resulting quaternion, the latter being represented as NumPy array.

**Simple test script:**

```
for i in range(5):
    a,b,c,d,e,f,g,h=np.random.randn(8)
    s,p,t,q=a, np.array([b, c, d]), e, np.array([f, g, h])
    print mult(a, b, c, d, e, f, g, h), "\n", m(s,p,t,q)

```

(`mult(...)` being the OP's reference implementation.)

Output:

```
[1.1564241702553644, 0.51859264077125156, 2.5839001110572792, 1.2010364098925583]
[1.1564241702553644, array([ 0.51859264,  2.58390011,  1.20103641])]
[-1.8892934508324888, 1.5690229769129256, 3.5520713781125863, 1.455726589916204]
[-1.889293450832489, array([ 1.56902298,  3.55207138,  1.45572659])]
[-0.72875976923685226, -0.69631848934167684, 0.77897519489219036, 1.4024428845608419]
[-0.72875976923685226, array([-0.69631849,  0.77897519,  1.40244288])]
[-0.83690812141836401, -6.5476014589535243, 0.29693969165495304, 1.7810682337361325]
[-0.8369081214183639, array([-6.54760146,  0.29693969,  1.78106823])]
[-1.1284033842268242, 1.4038096725834259, -0.12599103441714574, -0.5233468317643214]
[-1.1284033842268244, array([ 1.40380967, -0.12599103, -0.52334683])]

```
> 3 votes

# Answer
# Haskell, 85

```
m a b c d e f g h=[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

```

Porting it to Haskell saves us a few chars ;)
> 2 votes

# Answer
## Mathematica ~~83~~ 50

Probably can be golfed more..

```
p = Permutations;
f = #1.(Join[{{1, 1, 1, 1}}, p[{-1, 1, -1, 1}][[1 ;; 3]]] p[#2][[{1, 8, 17, 24}]]) &

```

Spaces and newlines not counted & not needed.

Usage:

```
f[{a,b,c,d},{e,f,g,h}]        (* => {x,w,y,z}   *)

```

**EDIT** How this works.

The Mathematica function `Permutations` makes all possible permutations of `#2` (the second argument). There are 24 permutations, but we only need `{e,f,g,h}`, `{f,e,h,g}`, `{g,h,e,f}`, and `{h,g,f,e}`. These are the first, 8th, 17th and 24th permutations. So the code

```
p[#2][[{1,8,17,24}]]

```

exactly selects these from the permutations of the second argument and returns them as a matrix. But then they don't have the correct sign yet. The code `p[{-1,1,-1,1}][[1;;3]]` returns a 3x4 matrix with the correct sign. We prepend it with `{1,1,1,1}` by using `Join`, and making a normal multiplication (`Times`, or as is the case here by just writing them after each other) between two matrices makes an element-by-element multiplication in Mathematica.

So finally, the result of

```
(Join[{{1, 1, 1, 1}}, p[{-1, 1, -1, 1}][[1 ;; 3]]] p[#2][[{1, 8, 17, 24}]])

```

is the matrix

```
 e  f  g  h
-f  e -h  g
-g  h  e -f
-h -g  f  e

```

Making a matrix multiplication between `{a,b,c,d}` (the first argument `#1`) and the former matrix gives the desired result.

**EDIT 2** Shorter code

Inspired by the Python code of Falko, I split up the quaternion in a scalar and a vector part, and use Mathematica's built in command `Cross` to calculate the cross product of the vector parts:

```
f[a_, A_, b_, B_] := Join[{a*b - A.B}, a*B + b*A + Cross[A, B]]

```

Usage:

```
f[a,{b,c,d},e,{f,g,h}]        (* => {x,w,y,z}   *)

```
> 2 votes

# Answer
## Python, 58 56 chars

```
m=lambda x,y,z,w:(x*z-y*(2*w.real-w),x*w+y*(2*z.real-z))

```

I take *very* liberal use of the input/output format wiggle room. The inputs are 4 complex numbers, encoded thusly:

```
x = a+b*i
y = c+d*i
z = e+f*i
w = g+h*i

```

It outputs a pair of complex numbers in a similar format, the first of the pair encodes the real and `i` part, the second encodes the `j` and `k` parts.

To see this works, note that the first quaternion is `x+y*j` and the second is `z+w*j`. Just evaluate `(x+y*j)*(z+w*j)` and realize that `j*t` = `conj(t)*j` for any imaginary number `t`.
> 2 votes

# Answer
## Python, 94

The most straightforward way isn't too long.

```
def m(a,b,c,d,e,f,g,h):return[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

```
> 1 votes

# Answer
## JavaScript ES6 - 86

```
f=(a,b,c,d,e,f,g,h)=>[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

```
> 1 votes

# Answer
# Lua - 99

Might as well.

```
_,a,b,c,d,e,f,g,h=unpack(arg)print(a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e)

```

Lua's "unpack()" frees the elements of a table. So the table 'arg' is where all the command line input is stored (including `arg[0]` which is the program's file name, it gets discarded).
> 1 votes

# Answer
# Whispers v2, 396 bytes

```
> 1
> 2
> 0
> 4
> Input
> Input
>> 6ᶠ2
>> 6ᵗ2
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
>> 7‖8
>> 11‖14
>> 8‖7
>> 14‖11
>> 15‖16
>> 19‖17
>> 20‖18
>> 4⋅5
>> L⋅R
>> Each 23 22 21
> [1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,-1,1]
>> Each 23 24 25
>> 26ᶠ4
>> 26ᵗ4
>> 28ᶠ4
> 8
>> 26ᵗ30
>> 31ᶠ4
>> 31ᵗ4
>> ∑27
>> ∑29
>> ∑32
>> ∑33
>> Output 34 35 36 37

```

Try it online!

Takes input in the form

```
[a, b, c, d]
[e, f, g, h]

```

and outputs as

```
w
x
y
z

```

to represent \\$q = w + xi + yj + zk\\$

The structure tree of this answer is:

A good chunk of this answer comes from two main faults in Whispers:

* No function to reverse an array
* The usage of sets in the computation of the Cartesian product

Therefore, we can split the code into 3 sections.

## How it works

We'll use the following definitions for clarity and conciseness:

$$q = a + bi + cj + dk$$ $$p = e + fi + gj + hk$$ $$r = w + xi + yj + zk, \\: (q \cdot p = r)$$ $$A = \[a, b, c, d\]$$ $$B = \[e, f, g, h\]$$ $$C = \[w, x, y, z\]$$

### Section 1: Permuting \\$A\\$ and \\$B\\$

The first section is by far the longest, stretching from line **1** to line **22**:

```
> 1
> 2
> 0
> 4
> Input
> Input
>> 6ᶠ2
>> 6ᵗ2
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
>> 7‖8
>> 11‖14
>> 8‖7
>> 14‖11
>> 15‖16
>> 19‖17
>> 20‖18
>> 4⋅5

```

The main purpose of this section is to permute \\$B\\$ so that simple element-wise multiplication between \\$A\\$ and \\$B\\$ is possible. There are four different arrangements of \\$B\\$ to multiply the elements of \\$A\\$ with:

$$B\_1 = \[e, f, g, h\]$$ $$B\_2 = \[f, e, h, g\]$$ $$B\_3 = \[g, h, e, f\]$$ $$B\_4 = \[h, g, f, e\]$$

The second input, \\$B\\$, is stored on line **6**. We then split \\$B\\$ down the middle, as each possible arrangement of \\$B\\$ is grouped in pairs. In order to reverse these pairs (to get the correct orders in \\$B\_2\\$ and \\$B\_4\\$), we take the first and last element, then concatenate them in reverse order:

```
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9

```

(forming \\$\[f, e\]\\$) and

```
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12

```

(forming \\$\[h, g\]\\$). We now have all the halves needed to form the arrangements, so we concatenate them together to form \\$B\_1, B\_2, B\_3\\$ and \\$B\_4\\$. Finally, we concatenate these four arrangements together to form \\$B\_T\\$. We then quickly make \\$A\_T\\$, defined as \\$A\\$ repeated \\$4\\$ times:

$$A\_T = \[a, b, c, d, a, b, c, d, a, b, c, d, a, b, c, d\]$$ $$B\_T = \[e, f, g, h, f, e, h, g, g, h, e, f, h, g, f, e\]$$

When each element of \\$B\_T\\$ is multiplied by the corresponding element in \\$A\_T\\$, we get the (signless) values in \\$q \cdot p\\$

## Section 2: Signs and products

As said in Section 1, the values in \\$A\_T\\$ and \\$B\_T\\$ correspond to the signless (i.e. positive) values of each of the coefficients in \\$q \cdot p\\$. No obvious pattern is found in the signs that would be shorter than simply hardcoding the array, so we hardcode the array:

```
> [1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,-1,1]

```

We'll call this array \\$S\\$ (signs). Next, we zip together each element in \\$A\_T, B\_T\\$ and \\$S\\$ and take the product of each sub-array e.g. \\$\[\[a, e, 1\], \[b, f, -1\], \dots, \[e, f, -1\], \[d, e, 1\]\] \to D = \[ae, -bf, \dots, -ef, de\]\\$.

## Section 3: Partitions and final sums.

Once we have the array of coefficients of \\$q \cdot p\\$, with signs, we need to split it into 4 parts (i.e. the four factorised coefficients of \\$q \cdot p\\$), and then take the sums. This leads us to the only golfing opportunity found: moving the

```
> 4

```

to line **4** rather than **26**, as it is used 6 times, each time saving a byte by moving it. Unfortunately, this costs a byte changing the **9** to a **10**, so only \\$5\\$ bytes are saved. The next section takes slices of size \\$4\\$ from the front of \\$D\\$, saving each slice to the corresponding row and passing on the shortened list of \\$D\\$. Once 4 slices are taken, we the take the sum of each, before outputting them all.
> 1 votes

# Answer
# Sidef, 10 bytes

```
{|a,b|a*b}

```

Sidef has a built-in Quaternion type, as does Odin. Neither language versions used by TIO support this, however.

```
var f = {|a,b|a*b}
say f(Quaternion(12, 54, -2, 23), Quaternion(1, 4, 6, -2))
#=> Quaternion(-146, -32, 270, 331)

say f(Quaternion(1, 4, 6, -2), Quaternion(12, 54, -2, 23))
#=> Quaternion(-146, 236, -130, -333)

say f(Quaternion(3.5, 4.6, -0.24, 0), Quaternion(2.1, -3, -4.3, -12))
#=> Quaternion(10059/500, 51/25, 19823/500, -125/2)

```
> 1 votes

# Answer
# Go, 119 bytes

```
type F=float64
func f(a,b,c,d,e,f,g,h F)[]F{return[]F{a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e}}

```

Attempt This Online!

The very straightforward solution
> 0 votes

# Answer
# Mathematica, 2 bytes

```
**

```

Definitely Mathematica has `NonCommutativeMultiply` for quaternions.

Reference: Official Documentation

```
Needs["Quaternions`"];

q1 = Quaternion[12, 54, -2, 23];
q2 = Quaternion[1, 4, 6, -2];
q3 = Quaternion[3.5, 4.6, -0.24, 0];
q4 = Quaternion[2.1, -3, -4.3, -12];

q1 ** q2
q2 ** q1
q3 ** q4

```

```
Quaternion[-146, -32, 270, 331]
Quaternion[-146, 236, -130, -333]
Quaternion[20.118, 2.04, 39.646, -62.5]

```
> 0 votes

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


title: Simulate Keyboard Inputs

text:
# Question
Title: Simulate Keyboard Inputs
## Background

You know how in text editors and just text fields in general, there's always that blinking bar where you type? Yeah, simulate typing there.

You'll be given 3 inputs: The current text field, the position of the cursor, and the input sequence.

Here's an example:

```
Hello, World!
5
[U];[U];[B];[B];[B];[B];[B];[U];i;[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];.
=> Hi, World.

```

Firstly, the number 5 tells us that the cursor is here, represented by the asterisk: `Hello*, World!`. If you take the string as zero-indexed, and choose the left side, you will find the cursor's starting point.

Next, we have 2 `[U]`s. `[U]` is a special input, representing undo. However, there is nothing to undo, so nothing happens.

Then, we have 5 `[B]`s. `[B]` is another special input, representing backspace. This tells us to erase 5 characters to the left of the cursor, one at a time. This gives `*, World!`.

Next, we have `[U]`. This tells us to cancel out the previous input (if there's anything to cancel out). If you have two `[U]`s, then you cancel out the last two instructions before the `[U]`s. Logic extends to all number of `[U]`s. Cancelling out the previous input, we have `H*, World!`.

Next, we have `i`. If there are no square brackets around the character, just add it to the text as a string, to the left of the cursor: `Hi*, World!`.

Now, we have 9 `[R]`s. `[R]` represents Move Cursor Right, so we move the cursor right 9 times: `Hi, World!*`. Note how it only actually takes 8 `[R]`s to get to the end, so the final `[R]` doesn't do anything.

Now, a `[B]`. This gives us `Hi, World*`.

Finally, `.`. This gives us `Hi, World.`.

//

The list of special inputs is shown here:

```
[B] = Backspace
[U] = Undo
[R] = Move Cursor Right
[L] = Move Cursor Left

```

Of course, within reason, you can change these special inputs (as long as it won't conflict with any non-special inputs.)

//

With regards to other rules:

* Left or Backspace when the cursor is furthest left does nothing.
* Right when the cursor is furthest right also does nothing.
* Undo when there's nothing to undo also does nothing.

In terms of undoing, `[L];[U]` and `[R];[U]` moves the cursor to its original position, before the `[L]` or `[R]`. `[B];[U]` reverts the backspace.

In terms of stacking undos, *an undo will not undo another undo*. That is, considering the following:

`z;a;b;[U];[U];c;[U];[U]`

The first two undos would get rid of a and b. The third would get rid of c. Finally, the last undo would get rid of the z. You can think of it like a stack, where every undo removes itself and the input below it.

However, in the special case the previous input does nothing:

`a;[R];[U]`

The undo should also do nothing.

## Your Task

* Sample Input:

1. The current text field
2. The position of the text cursor (\<= length of current text field)
3. The input sequence

Wrt the input sequence, in my examples I have used a string where each instruction is separated by semicolons. You can take the input sequence in any reasonable format - but note that the no input can contain this character. You can expect the non-special inputs and the text field to contain no `\n`s or `\t`s. They will also not contain any `[B]`s (and other), `[`, or whatever you're using for making the special input unique.

* Output: Return the final text field, after the sequence has been executed.

**Test Cases**

```
Input => Output

Hello, World!
5
[U];[U];[B];[B];[B];[B];[B];[U];i;[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];.
=> Hi, World.

This is [tag:code-golf], so shortest answer wins.
13
[R];[R];[R];[R];[R];[R];[B];c;h;s;[U];a;[R];[R];[B];[B];[R];L;[U];[L];llenge;[R];r;[L];[B];[R];[B];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];[B];[B];[B];[B];b;[R];[R];[L];[U];[R];[R];response or ;[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];[B];[B];[B];ill accepted as answer.;[U];ill be accepted as answer!
=> This is [tag:code-challenge], so best response or answer will be accepted as answer!

```

This is , so shortest answer wins. (# of bytes)

# Answer
# Ruby, 145 bytes

Not sure if it breaks the rules to have the special commands as integers. `U=0, L=-1, R=1, B=8`

The only reason `B=8` is because the control code for backspace is `\x08` lol

```
->s,l,i{i[(x=i.index 0)-[1,x].min..x]=[]while[]!=[0]&i
i.map{|e|l=l.clamp 0,s.size;e.ord==e ?e<5?l+=e:(s[l-=1]=''if l>0):(s[l,0]=e;l+=e.size)}
s}

```

Try it online!

# Ruby, 153 bytes

Version that uses characters only in case the above answer breaks the rules: `U=\x00, L=\x01, R=\x03, B=\x08`

```
->s,l,i{i[(x=i.index"\0")-[1,x].min..x]=[]while[]!=[?\0]&i
i.map{|e|l=l.clamp 0,s.size;c=e.ord;c<9?c<5?l+=c-2:(s[l-=1]=''if l>0):(s[l,0]=e;l+=e.size)}
s}

```
> 1 votes

# Answer
# Q, 248 bytes

```
w:{s:{x like"[[]",y,"[]]"};if[10=(@:)z;z:";"vs z];while[z[0]~"[U]";z:1_z];$[0=(#:)z;x;not(^:)r:(*:)(&:)s[z;"U"];w[x;y;_[z _ r;r-1]];s[o:z 0;"R"];w[x;(#:)[x]&y+1;1_z];s[o;"L"];w[x;0|y-1;1_z];s[o;"B"];w[x _ y-1;0|y-1;1_z];w[#[y;x],o,_[y;x];y+1;1_z]]}

```

**ungolfed**:

```
wp: { [text; cursor; input]
    if[10h=type input; input: ";" vs input];                    // convert semicolon-delimited string to list of strings
    special: {x like "[[]",y,"[]]"};                            // function to check whether a string is like e.g. "[E]"
    while[input[0]~"[U]"; input: 1 _ input];                    // remove leading undo's since there's nothing to undo
    if[not null rm: first where special[input; "U"];            // find the first "[U]" operation -- re-call this function after removing it and the preceding operation
        : wp[text; cursor; _[input _ rm;rm-1]];
    ];
    if[0=count input; : text];                                  // base case -- return text if there are no more operations
    op: input 0;
    if[special[op; "R"];                                        // re-call this function with 1 added to cursor (capping at length of text)
        : wp[text; count[text]&cursor+1; 1_input]];
    if[special[op; "L"];                                        // re-call this function with 1 removed from the cursor (capping at 0)
        : wp[text; 0|cursor-1; 1_input]];
    if[special[op; "B"];                                        // re-call this function with a) the character before the cursor removed from text and b) 1 removed from the cursor (capping at 0)
        : wp[text _ cursor-1; 0|cursor-1; 1_input]];
    : wp[ #[cursor;text],op,_[cursor;text]; cursor+1; 1_input]; // re-call this function with the characters added after the cursor in text
    }

```
> 0 votes

# Answer
# Python 3.8 (pre-release), 228 bytes

```
def f(s,c,Z,d=[]):
 for i in Z:d=d[:-1]if i[0]and'T'<i[1]else d+[i]
 for S,D in d:
  if S:
   if'Q'<D:c=min(c+1,len(s))
   elif'K'<D:c=max(c-1,0)
   else:s=s[:(f:=max(c-1,0))]+s[c:];c=f
  else:s=s[:c]+D+s[c:];c+=len(D)
 return s

```

Try it online!

The first `for` loop uses the stack `d` to get rid of all the undos. The second `for` loop loops over each instruction and modifies the string `s` accordingly. Almost definitely still golfable.

Inputs: list of tuples: (opcode, string). The opcode is 1 if the string is a special command, and 0 otherwise. Ex: `[(1, 'R'), (1, 'U'), (0, 'hi')]` This may be stretching the acceptable input format a bit, so I made a version which can accept the input format that the OP used:

# Python 3.8 (pre-release), 267 bytes

```
def f(s,c,Z,d=[]):
 for i in Z.split(';'):g='['in i;i=i[1]if g else i;d=d[:-1]if g and'T'<i else d+[(g,i)]
 for S,D in d:
  if S:
   if'Q'<D:c=min(c+1,len(s))
   elif'K'<D:c=max(c-1,0)
   else:s=s[:(f:=max(c-1,0))]+s[c:];c=f
  else:s=s[:c]+D+s[c:];c+=len(D)
 return s

```

Try it online!
> 0 votes

# Answer
# Charcoal, 88 bytes

```
Ｓθ≔⁻ＬθＮηＷＳ≡ι´⟲≔∧υ⊟υι⊞υιＦυ≡ι´←≧⁺‹ηＬθη´→≧⁻‹⁰ηη´⮌≔⁺✂θ⁰±⊕η¹✂θ⁻ＬθηＬθ¹θ≔⁺⁺✂θ⁰⁻Ｌθη¹ι✂θ⁻ＬθηＬθ¹θθ

```

Try it online! Link is to verbose version of code. Takes the input sequence as a list of newline-terminated strings where  is undo,  is left,  is right, and  is backspace. Explanation:

```
Ｓθ≔⁻ＬθＮη

```

Input the starting string and position, but calculate the position as a count from the end of the string, because that remains invariant under insertion and deletion.

```
ＷＳ

```

Loop through each command string.

```
≡ι´⟲≔∧υ⊟υι⊞υι

```

If it's a  then remove the previous command if any otherwise add the command.

```
Ｆυ≡ι

```

Loop through the remaining commands.

```
´←≧⁺‹ηＬθη

```

Handle left.

```
´→≧⁻‹⁰ηη

```

Handle right.

```
´⮌≔⁺✂θ⁰±⊕η¹✂θ⁻ＬθηＬθ¹θ

```

Handle backspace.

```
≔⁺⁺✂θ⁰⁻Ｌθη¹ι✂θ⁻ＬθηＬθ¹θ

```

Handle everything else.

```
θ

```

Output the resulting string.
> 0 votes

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


title: Sum every second digit in a number

text:
# Question
Title: Sum every second digit in a number
I have a number like this:

```
n = 548915381

```

The output should be the sum of every second digit of that number. In this case 26:

```
4+9+5+8 = 26

```

Rules:

* This is a , so the shortest code in bytes wins.
* The input consists only of numbers bigger than 10 (at least 2 digits) but smaller than a 32-bit integer.
* The input will be a number, not a string

Test cases:

| Input | Output |
| --- | --- |
| 10 | 0 |
| 101011 | 1 |
| 548915381 | 26 |
| 999999 | 27 |
| 2147483647 | 29 |
| 999999999 | 36 |

# Answer
# Vyxal, 2 bytes

```
y∑

```

well.

Try it Online! | 1 byte with `s`

**Explanation**

```
y∑
y   Uninterleave, push two lists with every second and every second+1 digit
 ∑  Sum the first list

```
> 12 votes

# Answer
## Python 3, 28 37 32 30 35 bytes

```
lambda n:sum(map(int,str(n)[1::2]))

```

Assuming input is a string number
> 9 votes

# Answer
# JavaScript (ES6), 30 bytes

*-1 by @l4m2*

```
f=n=>n&&f(i=n/10|0)+i++%2*n%10

```

Try it online!

---

# JavaScript (ES6), 31 bytes

```
f=n=>n?f(n/10|0)+i++%2*n%10:i=0

```

Try it online!

### Commented

```
f = n =>            // f is a recursive function taking the input n
  n ?               // if n is not equal to 0:
    f(n / 10 | 0) + //   do a recursive call with floor(n / 10)
                    //   it's important to understand that:
                    //     1) n is defined in the local scope of f
                    //     2) i is defined in the global scope
                    //     3) we're not going to execute the code that
                    //        follows until the recursion stops and i
                    //        has been initialized
    i++ % 2 *       //   take the parity of i (increment it afterwards)
    n % 10          //   and multiply by the least significant decimal
                    //   digit of n
  :                 // else:
    i = 0           //   stop the recursion and initialize i to 0

```
> 8 votes

# Answer
# Raku, 15 bytes

```
{sum m:g/.<(./}

```

Try it online!

Simple regex based sum of every other digit
> 8 votes

# Answer
# Japt `-hx`, 3 bytes

```
ì ó

```

Try it

```
ì ó     :Implicit input of integer
ì       :Convert to digit array
  ó     :Uninterleave
        :Implicit output of sum of last element

```
> 8 votes

# Answer
# , ~~40~~ ~~38~~ 36 bytes

*Edit: -2 bytes thanks to @Giuseppe.*

```
\(x)sum(x%/%10^(nchar(x):0)%%10*1:0)

```

Attempt This Online!
> 8 votes

# Answer
# Python 2, ~~39~~ 32 bytes

-7 (pxeger suggested lambda)

```
lambda n:sum(map(int,`n`[1::2]))

```

TIO

EDIT: new test cases
> 7 votes

# Answer
# Zsh, 33 bytes

```
for _ c (`fold -1`)let t+=c;<<<$t

```

Attempt This Online!

-3 bytes thanks to roblogic

Inputs as a string, because there is no way to input as a number in Zsh.
> 7 votes

# Answer
# \>\<\>, 14 bytes

```
0i~i:c%@0(?n+!

```

Try it online!

**Explanation**

```
0               # init sum as 0
 i~             # discard an input
   i:           # duplicate an input
     c%@        # mod the copy by 12 and move down on stack
        0(?n    # if the other copy was negative, print the sum
            +!  # else add copy to sum and skip the next instruction

```
> 7 votes

# Answer
# Excel, ~~39~~ 32 bytes

```
=SUM(--(0&MID(A1,2*ROW(A:A),1)))

```
> 7 votes

# Answer
# Pip, 10 7 bytes

```
$+@SUWa

```

First pip answer, so don't sue me plz.

Try It Online!

**Explanation**

```
$+@SUWa
  @SUWa  Uninterweave a, take the second item of the two "every second element" lists
$+       Sum the string

```
> 7 votes

# Answer
# Perl `-p`, 18 bytes

```
s/.(.)/$\+=$1/ge}{

```

Try it online!

Input via STDIN.
> 6 votes

# Answer
# Ruby, ~~40~~ ~~32~~ 31 bytes

-8 bytes thanks to G B
-1 byte thanks to Armand Fardeau

```
->n{eval"#{n}".scan(/.(.)/)*?+}

```

Attempt This Online!
> 6 votes

# Answer
# Pyth, 9 bytes

```
tssM%2+1z

```

Try it online!

```
      +1z    # Append '1' before the input
    %2       # Every 2nd element of
 ssM         # Map to integer and take sum
t            # Decrease by 1

```
> 5 votes

# Answer
# Jelly, 5 bytes

```
D0ÐoS

```

Try it online!

Also 5 bytes

```
DŻm2S

```

Try it online!

Also also 5 bytes

```
Ds2SṪ

```

Try it online!

### How they work

```
D0ÐoS - Main link. Takes an integer on the left
D     - Digits
  Ðo  - To digits in odd positions:
 0    -   Set them to 0
    S - Sum

```

```
DŻm2S - Main link. Takes an integer on the left
D     - Digits
 Ż    - Prepend a zero
  m2  - Take every second element
    S - Sum

```

```
Ds2SṪ - Main link. Takes an integer on the left
D     - Digits
 s2   - Slice into pairs
   S  - Sums
    Ṫ - Tail

```
> 5 votes

# Answer
# Julia 1.0, 30 bytes

```
!n=sum(i->i-'0',"$n"[2:2:end])

```

Try it online!
> 5 votes

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

```
[ >dec <odds> 48 v-n Σ ]

```

Try it online!

```
       ! 548915381
>dec   ! "548915381"
<odds> ! "4958"
48     ! "4958" 48
v-n    ! { 4 9 5 8 }
Σ      ! 26

```
> 5 votes

# Answer
# flax, 2 bytes

```
ΣẎ

```

Try It Online!
> 5 votes

# Answer
# , 15 bytes

All credit goes to Raul.

```
[:+/_2}.\,.&.":

```

Attempt This Online!

```
[:+/_2}.\,.&.":
         ,.&.":  NB. equivalent to ". ,. ": y, convert to digit list
    _2}.\        NB. behead each non-overlapping window of size 2
[:+/             NB. sum the resulting column

```

# My original 19 bytes from 11 bytes

```
1(#.]*0 1$~#),.&.":

```

Updated to reflect challenge requirements. Thanks to Jonah for the modifications.

Attempt This Online!

```
1(#.]*0 1$~#),.&.":
             ,.&.":  NB. same as above
1(          )        NB. dyadic hook
           #         NB. use length of right arg to
      0 1$~          NB. reshape 0 1, reuses elements to create alternating 1's
    ]*               NB. multiply by the right arg
  #.                 NB. 1 #. y sums the result

```
> 5 votes

# Answer
# pl – Perl One-Liner Magic Wand, 12 bytes

Use **-o** to loop over command line arguments. Global matching regexp returns every other character, in this case digit. By default List::Util::sum is imported, `e(cho)` its result. On the blog, hover the ▶ button, or the blue code box, to see the result:

```
pl -o 'e sum/.(.)/g' 10 101011 548915381 999999 2147483647 999999999

```
> 4 votes

# Answer
# Dart (2.18.4), ~~92~~ 77 bytes

```
f(n,[i=1])=>[for(;i<(n='$n').length;i+=2)int.parse(n[i])].reduce((v,e)=>v+e);

```
> 4 votes

# Answer
# Python 3, 35 bytes

```
lambda n:sum(map(int,f'{n}'[1::2]))

```

Try it online!
> 4 votes

# Answer
# sclin, 13 bytes

```
2/`1.: map +/

```

Try it here!

For testing purposes:

```
"548915381" ; n>o
2/`1.: map +/

```

## Explanation

Prettified code:

```
2/` 1.: map +/

```
* `2/`` chunk into pairs
* `1.: map` get second element of each pair
* `+/` sum
> 4 votes

# Answer
# Retina 0.8.2, 12 bytes

```
.(.?)
$1$*
.

```

Try it online! Link includes test cases. Takes input as a string because Retina has no integer types. Explanation:

```
.(.?)
$1$*

```

Convert alternate digits to unary, dropping the other digits.

```
.

```

Take the sum and convert back to decimal.
> 4 votes

# Answer
# Charcoal, 7 bytes

```
ＩΣΦＳ﹪κ²

```

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

```
   Ｓ    Cast the input to string
  Φ     Filter characters where
     κ  Current index
    ﹪ ² Is odd
 Σ      Take the sum
Ｉ       Cast to string
        Implicitly print

```
> 4 votes

# Answer
# Octave, 31 bytes

```
@(s)sum(num2str(s)(2:2:end)-48)

```

Try it online!

This converts the number to a string, sums up the character codes in the string, then subtracts the ASCII code for `0` (48) from each character.
> 4 votes

# Answer
# BQN, 18 bytes

```
1⊑·+˝⌊‿2⥊'0'-˜•Fmt

```

Anonymous tacit function that takes a number and returns a number. Try it at BQN online!

### Explanation

```
1⊑·+˝⌊‿2⥊'0'-˜•Fmt
               •Fmt  Format as string
          '0'-˜      Subtract '0' character from each, giving a list of digits as numbers
     ⌊‿2⥊           Reshape into an array with two columns, dropping the last digit if
                     there is an odd number of digits
  ·+˝                Sum down each column
1⊑                   Take the element at index 1 (0-indexed) in the resulting list

```
> 4 votes

# Answer
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
S]y

```

Try it online!

Port of Vyxal.

```
S]y
    # Uninterleave
 ]  # Get last
S   # Sum

```

# Fig, \\$6\log\_{256}(96)\approx\\$ 4.939 bytes

```
S-n2'0

```

Try it online!

My original answer before seeing Vyxal.

```
S-n2'0 # Input as a digit list
  n    # For every
   2   # Second item
    '  # Replace
     0 # With a 0
 -     # Subtract this from the original list
S      # Sum

```
> 4 votes

# Answer
# Kotlin, 51 bytes

```
{it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}}

```

No TIO link as it doesn't have an updated version, ATO borks with it for some reason.

```
{it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}} // String input
{                                                 } // Lambda expression
 it.map{it.code-48}                                 // Subtract 48 from each char, turning the string into a list of digits
                   .foldIndexed(0){i,a,c->       }  // Fold over the list, starting with 0. i is the index, a is accumulator, and c is the digit
                                          i%2*c     // Multiply the current digit by the index mod 2. If it is even, it resolves to 1*c, otherwise 0*c
                                               +a   // Add to accumulator

```
> 4 votes

# Answer
# K (ngn/k), 13 bytes

```
+/(2!!#:)#10\

```

Try it online!

* `10\` convert (implicit) input integer to a list of its digits
* `(2!!#:)#` only keep elements at odd indices (0-indexed)
* `+/` calculate (and implicitly return) the sum
> 4 votes

# Answer
# Julia, 28 bytes

```
f(n)=sum(digits(n)[2:2:end])

```
> 4 votes

# Answer
# C (gcc), 35 bytes

```
i;f(n){n=n?f(i=n/10)+i++%2*n%10:0;}

```

Try it online!

Port of js solution
> 3 votes

# Answer
# Haskell, 49 bytes

```
f s=sum[read[x]|(i,x)<-zip[0..]$show s,mod i 2>0]

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
2ι`SO

```

Try it online!

### Explanation

```
2ι`SO  # Implicit input                          TOP OF STACK:
2ι     # Get every second character              ["58131", "4958"]
  `    # Dump onto the stack                     "4958"
   S   # Cast to a list of characters            ["4", "9", "5", "8"]
    O  # Sum it up (implicit cast to integer)    26

```
> 3 votes

# Answer
# jonesforth, 104 bytes

```
: F DUP UWIDTH 1 AND IF BASE @ / THEN 0 SWAP BEGIN BASE @ /MOD -ROT + SWAP BASE @ / DUP NOT UNTIL DROP ;

```

Less obfuscated version:

```
: F
    \ make sure we have an even number of digits
    DUP UWIDTH
    1 AND
    IF BASE @ / THEN

    0 SWAP
    ( accumulator value )
    BEGIN
        \ add the smallest digit to the accumulator
        BASE @ /MOD ( acc rem quot )
        -ROT + SWAP
        \ discard the new smallest digit
        BASE @ / ( acc v )
        \ loop until the value is 0
        DUP NOT
    UNTIL
    DROP
;

```

This answer needs UWIDTH, which gforth doesn't have, so I specified jonesforth because it definitely works on jonesforth.

It compiles to 124 bytes, which drops to 116 if you have constants defined for 0 and 1. On a 16 bit forth it would theoretically be half that. Also it has the added bonus of working in any base between 2 and 36.
> 3 votes

# Answer
# Desmos, 61 bytes

```
D=floor(logk)
f(k)=∑_{n=0}^Dmod(n+D,2)mod(floor(k/10^n),10)

```

Try It On Desmos!

Try It On Desmos! - Prettified

There must be some better way to do this other than separating out the `D=floor(logk)` lol.
> 2 votes

# Answer
# Brachylog, ~~8~~ 6 bytes

```
ġ₂z₁t+

```

Try it online!

*-2 bytes thanks to @DLosc*.

### Explanation

```
ġ₂         Group consecutive digits into sublists of 2 elements
  z₁       Zip
     t     Tail
       +   Sum

```
> 2 votes

# Answer
# *Acc!!*, 176 bytes

```
48
Count i while _%60/48 {
_+_%60*59-2880+0*N+N
}
_/60
Count d while _/10^d {
Count i while 9/(_/10^d)*(d-i+1) {
Write _/10^(d-i)%10+48
}
}
_+1
Count z while 1/_ {
Write 48
2
}

```

Try it online!

### Explanation

As often happens with *Acc!!*, the majority of the code is taken up by decimal I/O.

```
### INPUT AND COMPUTATION ###
# Load a spurious 0 digit into the accumulator
48
# Loop while we just read a digit character and not a newline/eof
Count i while _%60/48 {
  # Add the digit represented by the character code in _%60 to the running tally in _/60
  _-_%60+60*(_%60-48)
  # Read the next character and do nothing with it
  _+0*N
  # Read the next character and store it in _%60
  _+N
}
# Set the accumulator to the value in _/60
_/60

### OUTPUT ###
# Figure out how many digits the accumulator value has
Count d while _/10^d {
  # Once we're on the leftmost digit, loop a number of times equal to the number of digits
  Count i while 9/(_/10^d)*(d-i+1) {
    # Output each digit from most significant to least significant
    Write _/10^(d-i)%10+48
  }
}
# But if the value was zero, this didn't output anything, so...
# Convert 0 -> 1, other values to numbers greater than 1
_+1
# Loop while accumulator is 1
Count z while 1/_ {
  # Write a 0 character
  Write 48
  # Set accumulator to 2 to break out of the loop
  2
}

```
> 2 votes

# Answer
# Bash +coreutils, 29 bytes

```
fold -2|cut -c2|paste -sd+|bc

```

Try it online!

---

**Alternatives** (38b, 46b)

```
echo `sed -E s'/(.)([0-9])/\2+/g'`0|bc

```

```
for z in `fold -1`;{((t+=i++%2?z:0));};echo $t

```
> 2 votes

# Answer
# jq -R, 28 bytes

```
[scan("..")|tonumber%10]|add

```

Try it online!
> 2 votes

# Answer
# Arturo, ~~32~~ 29 bytes

```
$[n][0loop digits n[a,b][+b]]

```

Try it
> 2 votes

# Answer
# vemf, ~~25~~ 8 bytes

*-17 bytes thanks to language creator*

Well this is a fun one.

```
ª‼│%2╕º+

```

try it online \- uses 8472 as an example

## Explanation

```
ª‼│%2╕º+

ª        ' convert to string
 ‼       ' repeat each character...
  │%2    ' (index mod 2) times
     ╕º  ' convert them back to numbers
       + ' sum

```

---

Old answer (25 bytes):

```
{`l←╢αª♣ó╕=_1·αª╕‼.l,-:48+

```

try it online

## Explanation

```
{`l←╢αª♣ó╕=_1·αª╕‼.l,-:48+

{                          ' define function. (closing } optional)

 `l←                       ' make a list:
    ╢                      ' (group next 9 characters)
         ╕                 ' for each element of
       ♣                   ' the domain of
     αª                    ' left argument as string,
        ó                  ' is (-1)^x
          =_1              ' equal to -1?
             ·             ' discard the return value

              αª╕          ' for each character,
                 ‼         ' repeat it
                  .l       ' by the corresponding list entry
                    ,      ' concatenate the resulting list
                     -:48  ' subtract 0x30 from each entry, so 1 maps to 0x01 etc
                         + ' sum

```
> 2 votes

# Answer
# Python 3, 41 bytes

```
lambda n:sum(int(i)for i in str(n)[1::2])

```

Try it online!
> 1 votes

# Answer
# Python 3, 45 bytes

```
e=lambda n:sum([int(x)for x in str(n)[1::2]])

```

Try it online!
> 1 votes

# Answer
# Pyt, 7 bytes

```
ąĐƩ⇹ƧƩ-

```

Try it online!

```
ąĐƩ⇹ƧƩ-
ą         implicit input (n); convert n to array of digits
 Đ        duplicate top of stack
  Ʃ       sum the digits of n
    ⇹     swap the top two items on the stack
     ƧƩ   sum every other digit of n, starting with the first
      -   subtract; implicit print

```
> 1 votes

# Answer
# Prolog (SWI), 53 bytes

```
\X:-get(_),get(C),C>0,Z is X+C-48,\Z;write(X).
:- \0.

```

Try it online!

Full program.
> 1 votes

# Answer
# Nibbles, 4.5 bytes

```
+`%~>>`@~

```

Attempt This Online!

## Explanation

```
+   Sum of
`%~  select every second element, starting at first, in
>>    remove first element of
`@~    base 10 digits of
        input

```
> 1 votes

# Answer
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
dZlAKS

```

Attempt This Online!

**Explanation:**

```
dZlAKS  # Implicit input
d       # Cast to digits
 Zl     # Uninterleave
   AK   # Get last element
     S  # Sum this list
        # Implicit output

```
> 1 votes

# Answer
# JavaScript, 42 bytes

Without recursion:

```
n=>[...''+n].reduce((s,n,i)=>s+=i%2&&+n,0)

```

Try it:

```
f=n=>[...''+n].reduce((s,n,i)=>s+=i%2&&+n,0)

console.log(f(10))         // 0
console.log(f(101011))     // 1
console.log(f(548915381))  // 26
console.log(f(999999))     // 27
console.log(f(2147483647)) // 29
console.log(f(999999999))  // 36
```
> 1 votes

# Answer
# Java 8 (OpenJDK 8), 110 ~~112~~ bytes

> -2 bytes thanks to @ceilingcat !

Solution using only a single inline Stream, and using a 2-cell array as the accumulator of the `reduce` to carry both the sum and the index of the current cell.
This could easily be outgolfed by a more classic Java solution.

```
n->(n+"").chars().mapToObj(e->new int[]{e-48}).reduce(new int[2],(a,b)->new int[]{a[0]+a[1]%2*b[0],++a[1]})[0]

```

Try it online!
> 1 votes

# Answer
# Lua, 43 bytes

```
a=0(...):gsub('.(.)',load'a=...+a')print(a)

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `S`, 1 byte

```
^

```

Try it online!

## Thunno 2, 2 bytes

```
^S

```

Try it online!

#### Explanation

```
^S  # Implicit input  ->  548915381
^   # Uninterleave    ->  [5,8,1,3,1], [4,9,5,8]
 S  # Sum the list    ->  [5,8,1,3,1], 26
    # Implicit output

```
> 1 votes

# Answer
# Kamilalisp, 38 bytes (APL SBCS)

```
λ x \⌿⊙← + \⍠¨ *&[$(^mod 2)#0]\⌹⊙ 10 x

```

Attempt This Online!
> 1 votes

# Answer
# Racket, 112 bytes

```
((λ(l)(for/sum([i(range(length l))]#:when(odd? i))(-(char->integer(list-ref l i))48)))(string->list(~a(read))))

```

Try it online!

---

## Explanation

Creates an anonymous function that receives user input as a list of characters. It then iterates through the length of the list. If the index is an odd number, we transform the current charater into a digit and add it to the sum.

```
((lambda (lst)
   (for/sum ([index (range (length lst))]
             #:when (odd? index))
     (- (char->integer (list-ref lst index)) 48)))
 (string->list (~a (read))))

```

### The mysterious "89" with no input

If you supply this program with no input, you will notice that the final sum would be 89.

That is because we convert the result of `read` directly into a string.

```
(~a (read))

```

When there is no input, the `read` function returns `#<eof>`. Our code converts the `#<eof>` symbol to a string, `"#<eof>"`. Then it loops through all the characters that have odd indices, giving us a list of `'(#\< #\o #\>)`. After that, the characters are converted into ASCII numbers. Since the ASCII value of "0" is 48, we subtract 48 from the result:

```
; (x - 48 becomes y)
'((#\<  12)
  (#\o  63)
  (#\>  14))

```

The numbers are then summed together to get 89.

---

*Have a wonderful week ahead!*
> 1 votes

# Answer
# Matlab, 166 bytes

```
n = input('Input : ', 's');
d = str2double(regexp(n,'\d','match')); %convert n to a unidimensional matrix
total = 0; %stores total sum
    for i = 2:2:length(d) %traverse the unidimensional matrix [ vector ]
        total = total + d(i); %sum of every second n
    end
disp(['Output : ', num2str(total)]);

```
> 0 votes

# Answer
# Java 19, 100 bytes

Partial program assuming `n` is the given number:

```
var m=0;var s=String.valueOf(n);for(var i=1;i<s.length();i+=2)m+=s.charAt(i)-48;System.out.print(m);

```

Full program using standard input:

```
interface A{
    static void main(String[]a){
        var n=Integer.parseInt(a[0]);
        //
        var m=0;
        var s=String.valueOf(n);
        for(var i=1;i<s.length();i+=2)m+=s.charAt(i)-48;
        System.out.print(m);
        //
    }
}

```
> 0 votes

# Answer
# Commodore BASIC (C64/128, C16/+4, VIC-20, PET, THEC64 Mini/THEC64/THEVIC20) - 88 BASIC Bytes

```
0 inputn$:iflen(n$)=0thenend
1 iflen(n$)<2orval(n$)<9then3
2 fori=2tolen(n$)step2:n=n+val(mid$(n$,i,1)):next
3 printn

```

A quick explanation

* Line zero waits for an input; if there is no input, then the program is ended
* Line one checks if the length of the input is 1 character, or the value is fewer than 9, if so, we branch to line 3
* Line two iterates over the string from the second character, and each second character thereafter until the end of the string. The value of each is added to `n` (which will be zero before the `for/next` loop).
* Line 3 outputs the total sum on `n`
> 0 votes

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