title: Implement String Projection

text:
# Question
Title: Implement String Projection
Given two strings: a string `s` and an alphabet `a`, implement string projection in the **shortest code** possible.

String projection returns a string `o` that contains the characters in `s` that are in `a`. The order of the characters in `o` must match the order of characters in `s`. So if `s = "abcd"` and `a = "12da34"`, `o = "ad"`, since only `"ad"` is shared between `s` and `a`.

You will need to handle when `a` is empty (outputs empty string, since no character in `s` can match empty string).

## Test Cases

```
"string", "alphabet" => "output"
-------------------------------
"abcd", "12da34" => "ad"
"hello, world!", "aeiou" => "eoo"
"hello, world!", "abcdefghijklmnopqrstuvwxyz" => "helloworld"
"Hello, World!", "abcdefghijklmnopqrstuvwxyz" => "elloorld" (case sensitivity)
"Hello, World!", "abcdef" => "ed"
"Hello, World!", "!,. \n\t" => ", !" (newline, tab)
"172843905", "abc123" => "123"
"fizzbuzz", "" => ""
"fizzbuzz", "fizzbuzz" => "fizzbuzz"
"", "fizzbuzz" => ""
"fizzbuzz", "zzzzz" => "zzzz"
"", "" => "" (two empty strings)

```

## Winning Criteria

This is , so shortest code wins!

# Answer
# Rust, 20 bytes

```
str::matches::<&[_]>
```

Attempt This Online!

This mixes up *three* I/O methods for strings: the first parameter is a plain string slice `&str`, the second is a slice of chars `&[char]`, and the output is an iterator yielding single-char string slices `impl Iterator<Item=&str>`.

Doc for `str::matches`. It can take several kinds of patterns (i.e. anything that implements `Pattern`) for non-overlapping substring search:

* single `char`: matches that char
* a `&str` or equivalent: matches that exact string
* a slice of chars `&[char]` or equivalent: matches any char out of the ones listed
* (and any 3rd party type that implements `Pattern`, e.g. `Regex`)

We use the third variety in this challenge, which is indicated by the `::<&[_]>` part. `_` is a kind of wildcard type, and it resolves to `char` by the compiler because `&[char]` is the only type matching `&[_]` that implements `Pattern`.
> 11 votes

# Answer
# Regex (ECMAScript or better), 20 bytes

```
s/(.)(?!.*␀.*\1)//sg

```

Try it online! \- ECMAScript 2018
Try it online! \- Perl
Try it online! \- PCRE2
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- .NET

This is a single regex substitution, to be applied once. Input is taken in the form of the two strings delimited by NUL (ASCII 0).

Above and below,  represents what is actually a raw NUL character in the regex.

```
s/              # Begin substitution - match the following:
      (.)       # \1 = one character
      (?!       # Negative lookahead - match if the following can't match:
          .*    # Skip over as many characters as possible, minimum zero, to make
                # the following match:
          ␀     # Skip over the NUL delimiter
          .*    # Skip over as many characters as possible, minimum zero, to make
                # the following match:
          \1    # Match the character we captured in \1
      )
/               # Substitution - replace with the following:
                # Empty string
/               # Flags:
s               # single line - "." will match anything, including newline
g               # global - find and replace all matches, going from left to right

```

This automatically erases the NUL and everything following it, because NUL and all characters following it are themselves not followed by NUL, so the negative lookahead matches for each of them.

(More test harnesses to come.)

As far as ECMAScript goes, this requires ECMAScript 2018 (aka ES9) due to the use of the `s` flag.

In Ruby, the `m` flag is used, which is the Ruby equivalent of what is `s` in most other regex engines.

## \\$\large\textit{Anonymous functions}\\$

# Perl, 42 bytes

```
sub{$_=join'␀',@_;s/(.)(?!.*␀.*\1)//sg;$_}

```

Try it online!

Takes the two strings as arguments.

Beaten by a **35 byte** solution based on an unposted solution by Sisyphus: Try it online!

# Ruby, ~~42~~ 41 bytes

*-1 byte thanks to Steffan*

```
->s,a{(s+?␀+a).gsub /(.)(?!.*␀.*\1)/m,''}

```

Try it online!

# PowerShell, 42 bytes

```
$args-join'␀'-creplace'(?s)(.)(?!.*␀.*\1)'

```

Try it online!

Takes the two strings as arguments.

# JavaScript (ES9), 43 bytes

```
a=>a.join`␀`.replace(/(.)(?!.*␀.*\1)/sg,'')

```

Try it online!

Takes a list containing the two strings.

# Java, 52 bytes

```
s->a->(s+"␀"+a).replaceAll("(?s)(.)(?!.*␀.*\\1)","")

```

Attempt This Online!

## \\$\large\textit{Full programs}\\$

# Perl, 37 bytes

```
$_=join'',<>;s/(.)(?!.*␀.*\1)//sg;say

```

Try it online!

Takes multiline input (terminated by EOF) using NUL as a delimiter between the two strings.

Beaten by a **19 byte** solution based on an unposted solution by Sisyphus: Try it online! (they should really post it), or 25 bytes to insert `chomp;` at the beginning if being picky about the output being followed by a NUL.
> 9 votes

# Answer
# Jelly, 1 byte

```
f

```

**Try it online!**

This is exactly what Jelly's "filter-keep" dyadic atom does - takes a list on the left and a list on the right and keeps those in the left that appear in the right.
> 8 votes

# Answer
# Haskell, 16 bytes

```
filter.flip elem

```

Try it online!

Takes arguments in reverse order.
> 8 votes

# Answer
# C (clang) `-m32`, ~~54 53~~ 45 bytes

*-1 byte thanks to @ceilingcat*
*-8 bytes thanks to @jdt*

```
f(*s,a){for(;*s;)write(1,s,!!index(a,*s++));}

```

Try it online!

### Explanation

```
f(*s,a){      // function f() takes a wide-character string (s) and an int (a)
 for(;*s;)    // while we're not at the end of the string
  write(1,s,N // write N bytes from s to stdout
   !!<expr>   // if <expr> is NULL, return 0, otherwise 1
    index(a,c // if the character `c` is found in `(const char *) a`,
              //   return a pointer to it's occurrence, otherwise `NULL`
     *s++     // return the current character and increment s
    )         // end call to index(3)
  );          // end call to write(2)
}             // end function f()

```

### Caveat

There is undefined behavior in the form of an unsequenced modification and access to `s`, but clang happened to evaluate `s` (the second parameter to `write`) before incrementing it in the call to `index(3)` so in this case it works.
> 5 votes

# Answer
# , 15 bytes

```
\(s,a)s[s%in%a]
```

Attempt This Online!

Takes input and outputs through vectors of character codes (as in linked test suite) or vectors of characters.
> 5 votes

# Answer
# Brachylog, 4 bytes

```
dᵗ∋ᵛ

```

Try it online!

Takes a list `[s, a]`, and generates a list constituting the projection.

```
dᵗ      Deduplicate a,
  ∋ᵛ    then yield some c from a pair of elements [c, c] from s and a.

```

Deduplicating a is necessary in order to not generate multiple pairs from the same element of s.
> 5 votes

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

Uses set difference (^) to compute the intersection: x∩y = x-(x-y)

```
^/^\

```

Try it online!
> 5 votes

# Answer
# Python, ~~35~~ 28 bytes

```
lambda a,b:filter(b.count,a)
```

Attempt This Online!

Takes in either strings or lists of characters, outputs a list of characters.

---

-7 bytes from @dingledooper by using `filter` \+ `count` instead of list comprehension and `in`
> 4 votes

# Answer
# Dyalog APL, 1 byte

Attempt This Online!
> 4 votes

# Answer
# sh + coreutils, 6 bytes

```
tr -cd

```

Takes string `s` from `stdin`, alphabet `a` as an argument.
> 4 votes

# Answer
# Pip, 5 bytes

```
a@X^b

```

Try It Online!

### Explanation

```
    b  Second command-line argument
   ^   Split into characters
  X    Convert to regex that matches any of those characters
 @     Find all matches of the regex in
a      First command-line argument

```

By default, the list of matches is concatenated together and output.
> 4 votes

# Answer
# Factor, 6 bytes

```
within

```

Try it online!
> 3 votes

# Answer
# C#, 33 bytes

```
(s,t)=>s.Where(c=>t.Contains(c));

```

Try it online!
> 3 votes

# Answer
# BQN, 3 bytes

```
∊/⊣

```

Try it at BQN REPL

```
 /      # Replicate elements of
  ⊣     # left argument
        # by
∊       # 1 if each element of left argument is in right argument
        # 0 otherwise

```
> 3 votes

# Answer
# PARI/GP, 27 bytes

```
f(a,b)=[c|c<-a,[d==c|d<-b]]
```

Attempt This Online!

Input and output lists of characters.
> 2 votes

# Answer
# 05AB1E, 1 byte

```
Ã

```

Another 1-byte builtin. Takes the inputs in the order `alphabet,string`.

Try it online or verify all test cases.
> 2 votes

# Answer
# Charcoal, 5 bytes

```
Φθ№ηι

```

Try it online! Link is to verbose version of code. Explanation: Trivial port of @dingledooper's golf to adam's Python answer.

```
 θ      First input
Φ       Filtered where
  №     Count of
    ι   Current character
   η    In second input
        Implicitly print

```

Newlines and other unprintables need to be entered using JSON format.
> 2 votes

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

```
s=>a=>[...s].filter(c=>a.includes(c)).join``

```

Try it online!

Unfortunately, using `.filter(a.includes)` for 38 (wow!) throws `String.prototype.includes called on null or undefined`
> 2 votes

# Answer
# CJam, 10 bytes

Loosely inspired by this answer to another challenge.

```
l~:A;{A&}/

```

Input is a line containing the two strings separated by a space. If a string contains special characters it needs to be defined explicitly as an array of chars.

Try it online! Or verify all test cases.

### How it works

```
l~          e# Read line and evaluate: pushes the two strings onto the stack
  :A;       e# Copy the second string into variable A, then pop
     {  }/  e# For each character in the first string, do the following
            e# Implicitly push current character of the first string
      A     e# Push the second string
       &    e# Set intersection. This gives the current char or an empty string
            e# Implicitly display stack contents

```
> 2 votes

# Answer
# Nibbles, 2 bytes (4 nibbles)

```
|@?@

```

```
|       # filter
 @      # the (second) input array
        # for truthy results of the function:
  ?     # index (or 0 if not found)
   @    # in the (first) input array

```
> 2 votes

# Answer
# Raku, 22 bytes

```
{$^a.trans($^b=>""):c}

```

Try it online!

`trans` is Raku's beefed-up version of Perl 5's transliteration operator `tr`.
> 2 votes

# Answer
# Ruby, 29 bytes

```
->s,a{s.gsub(/./){a[_1]&&_1}}

```

Previous version which had flaws indicated by Deadcode:

```
->s,a{s.tr(s.tr(a,""),"")}

```

Try it online!
> 2 votes

# Answer
# Haskell, 20 bytes

```
a#b=filter(`elem`b)a

```
> 1 votes

# Answer
# Rust, 70 bytes

```
|a:&str,b:&[u8]|a.bytes().filter(|d|b.contains(d)).collect::<Vec<_>>()
```

Attempt This Online!
> 1 votes

# Answer
# Vyxal `r`, 3 bytes

```
F¹F

```

Try it Online!

Unfortuantely, the builtin doesn't work with duplicates.
> 1 votes

# Answer
# Haskell, 21 bytes

```
s#a=[c|c<-s,elem c a]

```

Try it online!
> 1 votes

# Answer
# Knight, 63 bytes

```
;=aP;=bP Wa;=c b;=dF;Wc;I?AcAa=dT0=cGc 1Lc;IdO+A Aa"\"0=aGa 1La

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
Cases[#|##&@@#]&

```

Try it online!

Input and output two lists of characters `[alphabet][string]`.
> 1 votes

# Answer
# Dart (2.18.4), 55 bytes

```
f(s,a)=>s.split('').where((e)=>!!a.contains(e)).join();

```
> 1 votes

# Answer
# MATLAB, 25 bytes

```
f=@(a,b)a(ismember(a,b))
```

Technically, only the call of `a(ismember(a,b))` is required to fulfill the task, but to make it a callable function a function handle is created. Also, the inputs have to be of type char, not string, as a char is an array whereas a string is more like a complete unit in MATLAB.

Try it online!
> 1 votes

# Answer
# Haskell + hgl, 5 bytes

```
fl<fe
```

Attempt This Online!

Pretty straight forward. `fl` filters `fe` checks if something is an element. Ends up being the same as the vanilla Haskell answer.

## Reflection

This is a very simple task so there's not a lot to be said but:

* I'm not sure why `e` was given the shorter name than `fe`. `fe` is almost certainly the more useful of the two and probably they should be swapped.
* Since this is such a simple task, hgl should probably follow the lead of the golfing langs and make this a builtin.
* There are a bunch of builtins that are similar to this task like `nx`, but the descriptions were not the clearest.
> 1 votes

# Answer
# Red, 48 bytes

```
func[a b][foreach x a[if find/case b x[prin x]]]

```

Try it online!
> 1 votes

# Answer
# GolfScript, 15 bytes

```
~`{1$?)\''if}+%

```

Try it online!
> 1 votes

# Answer
# Scala, 8 bytes

```
_.filter

```

Try it online!

This is an expression of type `String => Set[Char] => String`. It uses the fact that a `Set[T]` is a function `T => Boolean`, which is used the predicate here.
> 1 votes

# Answer
# brev, 34 bytes

```
(as-list(c lset-intersection eq?))

```

Brev imports all of srfi-1 by default. The partial application combinator c applies eq? and then the as-list combinator makes the list operator work on (and return) strings (and other stuff) as if they were lists.
> 1 votes

# Answer
# Japt, ~~3~~ 2 bytes

```
fV

```

Try it

Takes input strings as character arrays

3 bytes w/ strings for input:

```
oV1

```

Try it

```
oV1
o     : only keep characters in first input and
 V    : second input
  1   : case sensitive

```
> 1 votes

# Answer
# Go, 104 bytes

```
import."strings"
func f(s,a string)(o string){for i:=range s{r:=s[i:i+1]
if Contains(a,r){o+=r}}
return}

```

Attempt This Online!
> 1 votes

# Answer
# POSIX Shell + Utilities, 26 bytes

```
printf %s "$1"|tr -cd "$2"

```

Fundamentally, the operation is `tr -cd alphabet`, all of 11 bytes on the right side of the pipe; more than half of the space is spent on turning the specified calling convention into data in a file. Unclear if taking the input from the standard input stream is allowed.

The tr alphabet accepts `\n` and `\t` for line and tab, but the spec does comment that it means a literal one, I think? Either work, but.

Transcript of test cases:

$ cat c.sh; echo; wc -c c.sh
printf %s "$1"|tr -cd "$2"
26 c.sh
$ ./c.sh "abcd" "12da34"; echo
ad
$ ./c.sh "hello, world!" "aeiou"; echo
eoo
$ ./c.sh "hello, world!" "abcdefghijklmnopqrstuvwxyz"; echo
helloworld
$ ./c.sh "Hello, World!" "abcdefghijklmnopqrstuvwxyz"; echo
elloorld
$ ./c.sh "Hello, World!" "abcdef"; echo
ed
$ ./c.sh "Hello, World!" "!,.
        "; echo
, !
$ ./c.sh "172843905" "abc123"; echo
123
$ ./c.sh "fizzbuzz" ""; echo

$ ./c.sh "fizzbuzz" "fizzbuzz"; echo
fizzbuzz
$ ./c.sh "" "fizzbuzz"; echo

$ ./c.sh "fizzbuzz" "zzzzz"; echo
zzzz
$ ./c.sh "" ""
```
</code></pre>
> 1 votes

# Answer
# Thunno 2, 2 bytes

```
Ƈị

```

Try it online!

I/O as a list of characters.

#### Explanation

```
    # Implicit input
 ị  # Keep only the characters of the first input
Ƈ   # which are contained in the second input
    # Implicit output

```
> 1 votes

# Answer
# Racket, 79 bytes

```
(define(p s a)(apply string(for/list([c s]#:when(string-contains? a(~a c)))c)))

```

Try it online!

---

## Explanation

We create a function called `p` that receives two inputs `s` and `a` which are the string to match and the string of what to match respectively. We loop through the characters of `s` and see whether each character appears in `a`. When a character does appear, we accumulate that character into a list. Once the list is obtained, we convert the characters to a single string.

```
(define (projection s a)
  (apply string
    (for/list ([char s] #:when (string-contains? a (~a char)))
      char)))

```

---

## Conclusion

*Have an amazing weekend!*
> 1 votes

# Answer
# , <sup>5</sup> 4 bytes

```
e.#[

```

Try it online!

*-1 byte thanks to seeing the word "filter" in Jonathan's Jelly answer*

Filter by `#` element of `e.`.
> 0 votes

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

Presently invalid as does not handle alphabets containing `-` or `]`. (as pointed out by Deadcode)

```
s=>a=>s.replace(RegExp(`[^${a}]`,'g'),'')

```

Attempt This Online!
> 0 votes

# Answer
# Burlesque, 2 bytes

```
IN

```

Try it online!

Builtin intersection.
> 0 votes

# Answer
`awk` 24-bytes solution — it's not *all that* short but it gets the job done\*

— **some bugs still exist*

```
echo 'abcd 12da34' |

```

> ```
> awk 'gsub("[^"$NF"]",_,$--NF)'
>
> ```

```
ad

```

#

```
echo 'hello, world!=naeiou' |

```

> ```
> awk 'gsub("[^"$NF"]",_,$--NF)' FS== |
> awk NF=NF FS= OFS='\n' | awk '!__[$_]++' ORS=
>
> ```

* or

> ```
> awk 'gsub("[^"$!_ "]",_,$NF)
>      gsub("[^"$NF"]",_,$!_)($_=$NF)' FS==
>
> ```

```
eo

```
> 0 votes

# Answer
# Arturo, 38 bytes

```
$[s,a]->join select split s'c[in? c a]

```

Try it
> 0 votes

# Answer
# Uiua, 3 bytes

```
▽∊,

```

Try it!

```
▽∊,
  ,  # over
 ∊   # member
▽    # keep

```
> 0 votes

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


title: Alphabet Checksum

text:
# Question
Title: Alphabet Checksum
### Your task

Given a string of lowercase letters, output the "alphabet checksum" of that string, as a letter.

### Example

Let's say we have the string *"helloworld"*. With `a = 0`, `b = 1`, `c = 2` ... `z = 25`, we can replace all of the letters with numbers:

```
h  e  l  l  o  w  o  r  l  d
7  4  11 11 14 22 14 17 11 3

```

Now, we can sum these:

```
7+4+11+11+14+22+14+17+11+3 = 114

```

If we mod this by 26, we get:

```
114 % 26 = 10

```

Now, using the same numbering system as before, get the 10th letter, `k`. This is our answer.

### Test cases

```
Input          Output

helloworld     k
abcdef         p
codegolf       h
stackexchange  e
aaaaa          a

```

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

# Answer
> 4 votes
# 05AB1E, 6 bytes

```
ADIkOè

```

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
A       # Push the lowercase alphabet
 D      # Duplicate it
  I     # Push the input-list
   k    # Get the index of each character in the (top) alphabet
    O   # Sum these together
     è  # (Modular 0-based) index it into the alphabet
        # (after which this character is output as result)

```

# Answer
> 9 votes
# Excel (ms365), ~~59~~, 58 bytes

-1 Thanks to @TheThonnu

```
=CHAR(MOD(SUM(CODE(MID(A1,SEQUENCE(LEN(A1)),1))+7),26)+97)

```

# Answer
> 6 votes
# JavaScript (Node.js), 51 bytes

```
s=>(B=Buffer)([B(s).map(c=>t+=c+7,t=0)|97+t%26])+''

```

Try it online!

# Answer
> 6 votes
# MATL, 10 bytes

```
2Y2j97-sQ)

```

Try it online! Or verify all test cases.

### Explanation

```
2Y2j97-sQ)
2Y2         % Push predefined literal: string 'abc···xyz'
            % STACK: 'abc···xyz'
   j        % Take input as a string
            % STACK: 'abc···xyz', 'helloworld'
    97-     % Push 97 (ASCII code of 'a'), and subtract element-wise
            % STACK: 'abc···xyz', [7 4 11 11 14 22 14 17 11 3]
       s    % Sum
            % STACK: 'abc···xyz', 114
        Q)  % Add 1, and use as index (1-based, modular). Implicit display
            % STACK: 'k'

```

# Answer
> 5 votes
# Go, 68 bytes

```
func(s string)(t int){for _,r:=range s{t+=int(r)-97}
return t%26+97}

```

Attempt This Online!

# Answer
> 5 votes
# Mathematica, ~~60~~ 48 bytes

```
FromLetterNumber[Tr[LetterNumber@#-1]~Mod~26+1]&

```

View it on Wolfram Cloud!

*-12 bytes thanks to JSorngard!*

# Answer
> 5 votes
# brainfuck, ~~142~~ 126 bytes

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

```

Try it online!

Edit: -16 bytes due to common sense. Remembered I didn't have to load 97 into its own cell before adding/subtracting.

My first time golfing in brainfuck! Here's the ungolfed code for your viewing displeasure:

```
,					GET EACH CHARACTER IN THE INPUT
[
	>++++++++[-<------------>]<-	SUBTRACT 97 (8 TIMES 12 PLUS 1) FROM CELL 0
	[->>>>+<<<<]			ADD CELL 0 TO CELL 4
	, 				INPUT TO CELL 0
]
>>>>					GO TO CELL 4
>+++++[->+++++<]>+<<			LOAD 26 (5 TIMES 5 PLUS 1) INTO CELL 6
[>+>->+<[>]>[<+>-]<<[<]>-]		TAKE CELL 4 MOD CELL 6
>>>					GO TO RESULT IN CELL 7
>++++++++[-<++++++++++++>]<+		ADD 97 (8 TIMES 12 PLUS 1) TO CELL 7
.					DISPLAY

```

# Answer
> 5 votes
# v4.2.0, 63 59

*-4 thanks to Dominic van Essen*

```
\(x,l=letters)l[(sum(match(el(strsplit(x,"")),l)-1)%%26)+1]

```

The input string `x` is parsed as characters, and `match` is used to retrieve the index of each character in the `letters` builtin, minus one to convert from 1-based to 0-based.

# Answer
> 5 votes
# Gaia, ~~16~~ 15 bytes

```
⟨c97%⟩¦Σ26%97+c

```

Try it online!

Pretty standard implementation of what the challenge asks.

I was able to save a byte thanks to the golfing advice given by
Dominic van Essen!

## Explained

```
⟨c97%⟩¦Σ26%97+c
⟨    ⟩¦           # To each letter in the input {
 c97%            #  modulo the character code by 96
                 #  }
       Σ26%      # Get the sum of that list and modulo 26
          97+c   # and add 97 to turn it back into an ascii letter

```

# Answer
> 4 votes
# Python 3, 43 bytes

-1 byte from @Arnauld

```
lambda s:chr(sum(ord(c)+7for c in s)%26+97)

```

Try it online!

# Answer
> 4 votes
# Factor \+ `math.unicode`, <sup> ~~25~~ </sup> 24 bytes

```
[ 7 v+n Σ 26 mod 97 + ]

```

-1 byte thanks to some black magic from Arnauld!

Try it online!

```
     ! "helloworld"
7    ! "helloworld" 7
v+n  ! { 111 108 115 115 118 126 118 121 115 107 }
Σ    ! 1154
26   ! 1154 26
mod  ! 10
97   ! 10 97
+    ! 107

```

# Answer
> 4 votes
# Jelly, 8 bytes

```
O+7S‘ịØa

```

A monadic Link that accepts a list of characters and yields a character.

**Try it online!** Or see the test-suite.

### How?

```
O+7S‘ịØa - Link: list of characters, Message
O        - ordinals (Message)
 +7      - add seven (vectorises)
   S     - sum
    ‘    - increment
      Øa - "abc...xyz"
     ị   - index into (1-based and modular)

```

# Answer
> 4 votes
# jq, 37 bytes

```
explode|map(.-97)|[add%26+97]|implode

```

Try it online!

# Answer
> 4 votes
# Raku, 27 bytes

```
{chr sum(.ords X-97)%26+97}

```

Try it online!

# Answer
> 4 votes
# Nibbles, 7 bytes (14 nibbles)

```
+%+.$-$;'a'26

```

```
   .            # map over
    $           # the input:
     -          #   subtract
        'a'     #   the letter 'a'
       ;        #   (and save it)
      $         #   from each letter
                #   (which gives its 0-based index)
  +             # now sum this list
 %         26   # apply modulo-26
+               # and add back the saved letter 'a'

```

# Answer
> 4 votes
# Julia 1.0, ~~36~~ 26 bytes

```
!s=sum([s...].-'a')%26+'a'

```

Try it online!

-10 MarcMush

# Answer
> 4 votes
# K (ngn/k), ~~16~~ 14 bytes

```
`c$97+26!+/97!

```

Try it online!

*-2 bytes thanks to coltim!*

Explanation:

```
`c$97+26!+/97!  Main function. Takes implicit input
           97!  Modulo by 97 to each character in the string
                to convert them into the 0..25 system
                (In K, every character in a string is also an ASCII charcode)
         +/     Sum
      26!       Modulo by 26
   97+          + 97 to each of them to convert them back to ASCII charcode
`c$             And convert them back to characters

```

# Answer
> 3 votes
# Ruby, ~~33~~ 32 bytes

-1 byte thanks to Arnauld

```
->a{(a.sum{_1.ord+7}%26+97).chr}

```

Attempt This Online!

# Answer
> 3 votes
# Vyxal, 9 bytes

```
øA‹∑₄%›øA

```

Try it Online!

```
øA‹∑₄%›øA
øA          Letter to number (1-indexed)
  ‹         Decrement each value in list
   ∑        Sum it up
    ₄%›     Modulo by 26 and increment
       øA   Number to letter

```

# Answer
> 3 votes
# simply, 76 bytes

It is a pretty long one...

Creates an anonymous function that outputs the expected result.

```
fn($S){$X=0each$S as$C;$X=&add($X&sub(&ord($C)97))out!ABCL[$_=&mod($X,26)];}

```

Yes, that's right, I'm assigning the result of `&mod` into a variable.
Without it, it gives a syntax error, because ... I made mistakes in the compiler...

# Using the code

Simply call the function.

```
$fn = fn($S){$X=0each$S as$C;$X=&add($X&sub(&ord($C)97))out!ABCL[$_=&mod($X,26)];}

// should output "h"
call $fn("codegolf");

```

# Ungolfed

Somewhat code-y looking:

```
$fn = fn($string) => {
    $sum = 0;
    each $string as $char {
        $sum = &add($sum, &sub(&ord($char), 97));
    }

    $index = call &mod($sum, 26);

    echo !ABCL[$index];
}

```

Plain English-ish/Pseudo-code looking:

```
Set $fn to an anonymous function($string).
Begin.
    Set $sum to 0.

    Loop through $string as $char.
    Begin.
        Set $sum to the result of calling the function &add(
            $sum,
            Call the function &sub(
                Call the function &ord($char),
                97
            )
        ).
    End.

    Set $index to the result of calling the function &mod($sum, 26).

    Show the value !ABCL[$index].
End.

```

Both versions do exactly the same.

# Answer
> 3 votes
# Japt, 8 bytes

```
;x!aC gC

```

Try it

Input as an array of characters.

Explanation:

```
;x!aC gC
;        # C = "abcdefghijklmnopqrstuvwxyz"
 x       # Compute the following for each character, then sum the results:
  !aC    #  Find its index in C
      gC # Get the character at that index in C (wrapping)

```

You can also rearrange things like this for a different 8 byte solution which works almost exactly the same way.

# Answer
> 3 votes
# Brachylog, 14 bytes

```
ạ+₇ᵐ+%₂₆+₉₇g~ạ

```

Try it online!

### Explanation

```
ạ                 String to char codes
 +₇ᵐ              Add 7 to each code (a <-> 97 becomes 104 = 0 (mod 26))
    +             Sum
     %₂₆          Mod 26
        +₉₇       Add 97
           g      Wrap into a list
            ~ạ    Char code to string

```

# Answer
> 3 votes
# Pushy, 7 bytes

```
L7*SvOq

```

Try it online!

```
         The input is implicitly converted into bytecodes on the stack.
L7*      Push the length of the input, times 7.
   S     Push the sum of the stack.
    vO   Send this to the 'output stack'.
      q  Index into the ASCII lowercase alphabet (mod 26) and print the result.

```

Pushing 7 times the length comes from the fact that `a` has bytecode 97, and \\$ -97 \equiv 7 \ (\text{mod} \\, 3) \\$. So it's equivalent to subtracting 97 from each bytecode.

# Answer
> 3 votes
# Java (OpenJDK 8), 132 bytes

```
interface T{static void main(String[]a){int i=a[0].length(),s=0;for(;i-->0;s+=a[0].charAt(i)+7);System.out.print((char)(97+s%26));}}

```

Try it online!

# Answer
> 3 votes
## C# (.Net 6), 64 bytes

```
int i=0,j=0;for(;i<a.Length;)j+=a[i++]-97;return(char)(97+j%26);

```

Try it here

# Answer
> 3 votes
# , 19 bytes

```
(26|+/)&.(_97+3&u:)

```

Attempt This Online!

```
(26|+/)&.(_97+3&u:)
       &.            NB. F&.G y applies G⁻¹(F(G x)) to y, rank is decided by G
         (_97+3&u:)  NB. fork converting str to char codes and subtracting 97 from each
(26|+/)              NB. fork that sums the arg and mods the result by 26
                     NB. +/ can be used because u: operates on y as a whole
                     NB. The inverse of G in this case would be to add 97 to
                     NB. the result of F and then convert char code to str

```

# Answer
> 3 votes
# Bits, 130 bits = 16.25 bytes

```
1110000111000001110001011111110111010100000001100111110101011100011000000110001011001101101110000000110100111001111101010111111100

```

This was very painful.

### Explanation

```
11100001   // Get a string input
1100000    // Push 0 to the stack [this will be our running sum]
11100010   // For each character in the input string:
111111101  //   Get ord(c)
1101010    //   Add [to the running sum]
000000     //   Separator so the numbers don't get joined together
1100111    //   Push 7
1101010    //   Add [to the running sum]
11100011   // ENDFOR
000000     // Separator so the numbers don't get joined together
1100010    // Push 2
1100110    // Push 6 [this gets joined into 26]
1101110    // Mod our running sum by 26
000000     // Separator so the numbers don't get joined together
1101001    // Push 9
1100111    // Push 7 [this gets joined into 97]
1101010    // Add [to the result of the mod]
111111100  // Get chr(x)
           // [implicit output of the item on the top of the stack]

```

### Output

# Answer
> 3 votes
# , ~~44~~ ~~43~~ 42 bytes

```
letters[sum(utf8ToInt(scan(,""))+7)%%26+1]

```

Try it online!

(or 38 bytes as a function in  ≥ 4.1).

# Answer
> 2 votes
# Thon (Symbols) <sup>`s` flag</sup>, 10 bytes

```
$åị$Σ26%å`

```

### Explanation

```
$åị$Σ26%å`   // (implicit input as a string)
$  $         // For each character in the input string:
 åị          //   Get the index in the alphabet
             // (implicitly create a list of all of these indexes)
    Σ        // Sum the list
     26%     // Mod by 26
        å`   // Get that letter of the alphabet
             // (implicit output)

```

# Answer
> 2 votes
# Python, 74 bytes

```
from string import*
f=lambda s,l=ascii_lowercase:l[sum(map(l.index,s))%26]

```

Try it online!

# Python \+ `golfing-shortcuts`, 47 bytes

```
lambda S:Sl[s(m(Sl.index,S))%26]
from s import*

```

(Is this one a competitive answer?)

# Answer
> 2 votes
# Fig, \\$10\log\_{256}(96)\approx\\$ 8.231 bytes

```
ica%26S+7C

```

Using Arnauld's logic. Accepts a list of characters

Try it online!

```
ica%26S+7C
         C # str -> char code, vectorises
       +7  # add 7 to each item
      S    # sum
   %26     # sum % 26
 ca        # lowercase alphabet
i          # index intro ca using result

```

# Alternate \\$13\log\_{256}(96)\approx\\$ 10.701 bytes

```
ica%26SM'lxca

```

Try it online!

```
ica%26SM'lxca
           ca  # lowercase alphabet
          x    # input
       M'l     # map find over x where we look for each char in ca, returns index
      S        # sum
   %26         # sum % 26
ica            # index into ca using the result

```

# Answer
> 2 votes
# Zsh, 41 bytes

```
a=(+##${(s..)^1}+7)
<<<${(#)$((a%26+97))}

```

Try it online!

`(s..)`plit, `^` RC-style expand as `+##${1[1]}+7 +##${1[2]}+7 ...`. Then `(#)` evaluate the expression as character codes.

# Answer
> 2 votes
# ARM Thumb machine code, 18 bytes

```
61 20 04 c9 61 3a 10 44 fb d5 1a 38 fd d2 7b 30
70 47

```

Assembler source:

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl alpha_checksum
    .thumb_func
    // Input: r1: null terminated UTF-32LE string
    // Output: r0
    // Clobbers: r0-r2
alpha_checksum:
    // Initial accumulator. Start at 'a' to cancel the checksum
    // loop adding '\0' - 'a' when the null terminator is reached.
    movs   r0, #'a'
.Lloop:
    // Load character, increment pointer
    ldmia  r1!, {r2}
    // Subtract 'a' to convert to a number, set flags
    // In the case of the null terminator, this will result in
    // -'a', which ends the loop condition below.
    subs   r2, #'a'
    // Add to the checksum, without setting the flags
    add    r0, r2
    // Loop if the subs didn't return negative,
    // which happens only with the null terminator.
    bpl    .Lloop
.Lend:
    // Calculate (checksum % 26) - 26 using a naive subtraction loop
.Lmodulo:
    // Subtract 26
    subs   r0, #26
    // Loop while it was >= 26
    bhs    .Lmodulo
    // Add 26 to correct the modulo, and 'a' to convert to ASCII.
    adds   r0, #'a' + 26
    // Return
    bx     lr

```

This can be called from C using a dummy parameter to place `ptr` in `r1`.

`ptr` is expected to be a pointer to a null terminated UTF-32LE string.

```
char32_t alpha_checksum(int dummy, const char32_t *ptr);

```

# Answer
> 2 votes
# C (gcc), 46

```
t;f(char*s){for(t=0;*s;)t+=*s++-97;t=t%26+97;}

```

Try it online!

# Answer
> 2 votes
# Clojure, 65 bytes

```
(defn a[s](char(+(mod(apply + (map #(- % 97)(map int s)))26)97)))

```

Try it online!

Ungolfed:

```
(defn alpha-checksum [s]
  (char (+ (mod (apply + (map #(- % 97) (map int s))) 26) 97)))

```

# Answer
> 2 votes
# Wren, 47 bytes

```
Fn.new{|s|(s.bytes.reduce{|x,y|x+7+y}+7)%26+97}

```

Try it online!

# Answer
> 2 votes
# Charcoal, 8 bytes

```
§βΣＥＳ⌕βι

```

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

```
    Ｓ       Input string
   Ｅ        Map over characters
       ι    Current character
     ⌕      Find index in
      β     Predefined variable lowercase alphabet
  Σ         Take the sum
§           Cyclically indexed into
 β          Predefined variable lowercase alphabet
            Implicitly print

```

# Answer
> 2 votes
# Retina 0.8.2, 25 bytes

```
0T1>`l`L
+T`l__L`zlL_`^..

```

Try it online! Link includes test cases. Explanation:

```
0T1>`l`L

```

Uppercase all letters after the first.

```
+T`l__L`zlL_`^..

```

While there are at least two letters, repeatedly rotate the first letter backwards and the second letter forwards in the alphabet, however the first letter rotates back from `a` to `z` while the second letter drops off when it passes `Z`, allowing subsequent letters to be processed.

The `l` and `L` in the patters expand to the lowercase and uppercase alphabet respectively. The `_` in the source pattern is just a placeholder to allow the use of `l` and `L` in the destination pattern, while in the destination pattern it indicates that the character is to be deleted.

# Answer
> 2 votes
# Pip, 20 bytes

```
C(($+(7+A*a))%26+97)

```

Try It Online!

Probably could be shorter, I feel like there are just way too many parentheses.

# Answer
> 2 votes
# BQN, 15 bytes

```
'a'+26|·+´-⟜'a'

```

Try it at BQN REPL

```
'a'+26|·+´-⟜'a'
          -⟜'a'     # subtract 'a' from each letter of input
        +´          # sum
       ·            # (no-op to preserve train syntax)
    26|             # modulo 26
'a'+                # add 'a'

```

# Answer
> 2 votes
## x86‑64 assembly machine code, 30 B

### input

* unsigned length of string in 64‑bit register `rdi`
* address of string buffer in 64‑bit register `rsi`

### code listing

```
 1                 alphabet_checksum:
 2 0000 6A61        push 'a'                    ; push(97)
 3 0002 58          pop rax                     ; pop(rax)
 4 0003 F7E7        mul edi                     ; edx○eax ≔ eax × edi
 5
 6 0005 F7D8        neg eax                     ; eax ≔ −eax; CF ≔ eax ≠ 0
 7 0007 7310        jnc .adjust                 ; if ¬CF then goto adjust
 8                 .sum:
 9 0009 0FB64C3EFF  movzx ecx, byte [rsi+rdi-1] ; ecx ≔ (rsi + rdi − 1)↑
10 000E 01C8        add eax, ecx                ; eax ≔ eax + ecx
11 0010 FFCF        dec edi                     ; edi ≔ edi − 1; ZF ≔ edi = 0
12 0012 75F5        jnz .sum                    ; if ¬ZF then goto sum
13
14 0014 6A1A        push 26                     ; push(26)
15 0016 5F          pop rdi                     ; pop(rdi)
16 0017 F7F7        div edi                     ; edx ≔ edx○eax mod edi
17                 .adjust:
18 0019 92          xchg eax, edx               ; eax ≔ edx
19 001A 83C061      add eax, 'a'                ; eax ≔ eax + 97
20 001D C3          ret

```

### output

* alphabet checksum as ASCII character in 64‑bit register `rax`

### limitations

* length of string must be ≤ 44,278,013, else the `mul` spills into `edx`, yet the algorithm relies on `edx` being `0` in the case of a zero-length string

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

```
([...s])=>String.fromCharCode(s.map(c=>t+=c.charCodeAt()+7,t=0)|t%26+97)

```

Try it online!

# Answer
> 2 votes
# Gema, 77 characters

```
?=@set{s;@add{${s;};@add{@char-int{?};7}}}
\Z=@int-char{@add{@mod{$s;26};97}}

```

(Yepp. Arithmetic operations are a pain in Gema.)

Sample run:

```
bash-5.1$ echo -n helloworld | gema '?=@set{s;@add{${s;};@add{@char-int{?};7}}};\Z=@int-char{@add{@mod{$s;26};97}}'
k

```

Try it online!

# Answer
> 2 votes
# PowerShell, 54 bytes

```
$s.tochararray()|%{$r+=([char]$_)-97};[char]($r%26+97)

```

Try it online!

# Answer
> 2 votes
# Pip, 16 bytes

```
zPK$+(A*a-97)%26

```

Try It Online!

# Answer
> 2 votes
# Haskell, 43 bytes

```
f s=['a'..]!!mod(sum[fromEnum c-97|c<-s])26

```

Try it online!

### Same-length alternative:

```
f s=['a'..]!!mod(sum$do c<-s;1<$['b'..c])26

```

Try it online!

# Answer
> 2 votes
# Knight (v2), 36 bytes

```
;=sP;=i@O;Ws;=i+~-97iAs=s]sA+97%i 26

```

Try it online!

I feel like you can golf better but i tried for awhile and gave up

# Answer
> 2 votes
# \>\<\> (Fish), ~~26~~ 24 bytes

* -2 bytes thanks to @Eminga. I didn't want to change the input mode to stack though so I didn't use all the golfing potential. Also I wanted to exit properly and not just error.

```
0i:0(?v+7+2d*%!
o+"a"~<;

```

Animated Version

## Explanation:

```
0

```

Push 0, the starting value

```
i:0(?v

```

Check if the input is negative, if so go down.

```
+7+2d*%

```

Add 7+the input to the accumulator, then mod 26

```
!

```

Skip the 0 the second time, since the accumulator is already set

```
~"a"+o;

```

(Reversed in the program) Print "a" + the accumulator.

# Answer
> 2 votes
# Uiua, 11 bytes

```
+@a◿26/+-@a

```

Try it!

```
+@a◿26/+-@a
        -@a  # convert string to code points
      /+     # sum
   ◿26       # modulo 26
+@a          # add the letter a

```

# Answer
> 1 votes
# C++ (gcc), ~~76~~ 73 bytes

-3 thanks to @ceilingcat

I think this is as much golf as you can get without using a completely different method. Other people ~~will probably prove me wrong the moment I hit "Post."~~ have in fact proven me wrong.

```
#import<ios>
int f(char*s){int t=0;for(;*s;t+=*s++-97);putchar(t%26+97);}

```

Try it online!

### Ungolfed

We used `#import<ios>` so we can `putchar()`.

```
int f(char* s) {
    int t = 0;                      // Running total
    for(;*s != 0;t += *s++ - 97);   // Loop through string until we get to null byte, add to running total
    putchar(t % 26 + 97);           // Add 97 to final result and print
}

```

# Answer
> 1 votes
# Arturo, 29 bytes

```
$[a][+97(sum map a=>[+7])%26]

```

Try it

# Answer
> 1 votes
# brainfuck, 91 bytes

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

```

Try it online!

```
++[++[->+>+<<]>>[--<<+>>]<]    Init memory with 1,2,3,...,127
,[[-[->+<]>]>>>>>>>,]          Reading each byte, move right that many steps
+[<<<<<<<<<<<<<<<<<<<<<<<<<<+< Go left 26 and check if empty
[-----.[>]]>]                  If not empty, give shift, output and halt

```

# Answer
> 1 votes
# Dyalog APL v18, 28 bytes\*

```
{a[1+26|+/1-⍨(a←¯1∘⎕C⎕A)⍳⍵]}

```

Assuming that indices start from one (`⎕IO←1`).

<sup>\________________
\*: APL can be written in its own legacy charset (defined by `⎕AV`) instead of Unicode; therefore an APL program that only uses ASCII characters and APL symbols can be scored as 1 char = 1 byte. </sup>

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
Ä⁻S⁺ÄL

```

Try it online!

#### Explanation

```
Ä⁻S⁺ÄL  # Implicit input
Ä       # 1-based index in alphabet
 ⁻      # Decrement to make 0-indexed
  S     # Sum the resulting list
   ⁺    # Increment for 1-indexing
    Ä   # 1-based convert to letter
     L  # Lowercase it
        # Implicit output

```

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


title: Repeat List Until Longer

text:
# Question
Title: Repeat List Until Longer
## The Challenge

The challenge is simple: given an input list `a` and another list `b`, repeat `a` until it is longer than `b`.

As an example, call the repeated list `ra`. Then the following condition must hold true: `len(b) < len(ra) <= len(b) + len(a)`. That is, `a` must not be repeated more than is required.

## Sample Python Implementation

```
def repeat(a, b):
    ra = a.copy()
    while len(b) >= len(ra):
        ra += a
    return ra

```

Try it online!

## Examples

```
[1,2,3], [2,4] -> [1,2,3]
[1,2,3], [2,3,4] -> [1,2,3,1,2,3]
[1,2,3], [18,26,43,86] -> [1,2,3,1,2,3]
[2,3,5], [1,2,3,4,5,6,7] -> [2,3,5,2,3,5,2,3,5]
[1,123], [1,12,123,1234] -> [1,123,1,123,1,123]

```

## Scoring

This is , shortest answer in bytes wins. Have fun!

# Answer
> 18 votes
# Python 3, 29 bytes

```
lambda x,y:len(y)//len(x)*x+x

```

Try it online!

# Answer
> 10 votes
# Husk, 6 bytes

```
*¹→¤÷L

```

Try it online!

```
   ¤     # combin: ¤ f g x y = f (g x) (g y)
     L   #    where g = length
    ÷    #    and f = integer divide
         # so ¤÷L calculates the (integer) ratio of input lengths;
   →     # then increment the result,
 *¹      # and repeat input 1 that many times

```

# Answer
> 8 votes
# Vyxal `r`, 7 bytes

```
₅?Lḭ›ẋf

```

Try it Online!

**How it works:**

```
₅?Lḭ›ẋf
₅        # Push first list and its length
 ?Lḭ     # Integer-divide by length of second list
    ›    # Increment ^
     ẋ   # Repeat first list that many times
      f  # Flatten into a single list

```

# Answer
> 8 votes
# APL (Dyalog Unicode), ~~20~~ 18 bytes

```
{(A×⌈(⍴⍵,1)÷A←⍴⍺)⍴⍺}

```

Try it online!

Thanks to Adám for golfing some bytes and helping me to fix errors in chat. `⎕←,⍣2⍨'thanks'`

-2 thanks to AZTECCO `⎕←'thanks'`

# Answer
> 7 votes
# , ~~15~~ 14 bytes

*-1 byte thanks to Jonah's very clever idea!*

```
];@;<.@%&##<@]

```

Try it online!

Takes input as `b f a`, if `f` is the name you assign the verb to.

## Explanation

```
];@;<.@%&##<@]
       %          divide
        &#        the lengths of the lists by each other
    <.@           and floor it;
           <@]    box b
          #       and repeat it that many times
]  ;              prepend b to this boxed array
 ;@               and raze the result, collapsing it into a single list

```

Instead of incrementing the division result, as I did in the first version below, we simply prepend the input list to the resulting tiled box list, which is equivalent.

## Old Answer

```
]$~#@]*1<.@+%&#

```

Try it online!

### Explanation

```
]$~#@]*1<.@+%&#
            %      divide
             &#    the lengths of the lists by each other
       1   +       increment
        <.@        and floor
      *            multiplied by
   #@]             length of a
]$~                and reshape a to be that length

```

Unfortunately, `#` doesn't work here, as it doesn't preserve the order. (`1 1 1 2 2 2 3 3 3 -: 3 # 1 2 3`.)

# Answer
> 7 votes
# Curry, ~~57~~ 42 bytes

This being my first Curry answer, I'm pretty certain its not quite optimal, but as it is our current lang of the month, I figured I'd give at least a half-hearted try at it.

```
l=length
a!b|l a>l b=a|1>0=a++a!drop(l a)b

```

Edit: Try it online!

A bit longer than I'd like, my first idea involved the recursive return being `r(a++a)b`, but I realized that didn't work unless the correct number of repetitions was a power of two.

Edit -15 bytes from some good tips by WheatWizard

# Answer
> 6 votes
# Haskell + hgl, 18 bytes

```
m**frt$P1<<fdv.*l

```

Divide the lengths, add 1 and then repeat that many times.

# Reflection

This is kind of long, but also pretty compact. Part of the issue is that variable reuse is always going to be a bit long. We also have to use both `frt` and `fdv` which are unfortunately 3 bytes each. It's totally possible to do this without flipping via `rt` and `dv`

```
m jn$rt<<P1<<dv.*l

```

But that ends up being a byte longer.

It seems mostly like a quirk of the specific problem that flipping is required.

The only real improvement I can see here is to combine some of the glue used to make things more compact.

* `m jn` used in the 19 byte solution could be 1 function. It has a useful type. If it were 3 bytes it would save 1 byte overall

```
mjn$rt<<P1<<dv.*l

```
* `l2 m` is a little more niche but could be added. As a 3 byte prefix it would actually have *costed* a byte here

```
l2m frt$P1<<fdv.*l

```

It could also be an infix, but that also costs a byte.

```
frt**<(P1<<fdv.*l)

```

However in better circumstances it could potentially save a byte.

# Answer
> 6 votes
# 05AB1E, 6 bytes

```
gIg÷>и

```

Takes the input-lists in the order \\$b,a\\$.

Try it online or verify all test cases.

**Explanation:**

```
g       # Push the length of the first (implicit) input-list `b`
 Ig     # Push the length of the second input-list `a`
   ÷    # Integer-divide the length by `b` by that of `a`
    >   # Increase it by 1
     и  # Repeat the second (implicit) input-list `a` that many times
        # (after which the result is output implicitly)

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
ẋɓL:L}‘

```

Try it online!

Nothing all too original.

```
ẋ          Repeat a by
 ɓL        the length of b
   :L}     floor divided by the length of a
      ‘    plus 1.

```

# Answer
> 4 votes
# Pyth, <sup>~~10~~</sup> 9 bytes

```
*h/l.).Ql

```

Try it online!

```
*h/l.).Ql

   l.).Q    # get the length of the second list
  /     l   # integer divide it by the length of the first list
 h          # increment the result of the division
*           # multiply by the first list (like int * list in Python)

```

# Answer
> 4 votes
# Perl 5, 29 bytes

```
sub{(@{$a=shift})x(1+@_/@$a)}

```

Try it online!

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

Expects `(a)(b)`. This code assumes that both lists are filled with positive integers (as allowed by the OP).

```
a=>g=(b,...c)=>c[b.length]?c:g(b,...c,...a)

```

Try it online!

# Answer
> 4 votes
# K (ngn/k), 18 bytes

```
{(~(#y)<#:)(x,)/x}

```

Try it online!

Appends copies of `x` until the length is greater than the length of `y`.

* `(cond)(code)/x` set up a while-reduce, beginning with `x`, the input. the "code" part is repeated until the "cond" part returns a non-truthy value
    + `(~(#y)<#:)` check whether or not the current list is longer than `y`
    + `(x,)` prepend a copy to the current list

An alternative version, with the same byte count, instead uses the do-reduce overload, swapping `(~(#y)<#:)` for `((-#x)!#y)`.

# Answer
> 4 votes
# , ~~33~~ 31 bytes

```
\(a,b,`-`=length)rep(a,1+-b/-a)
```

Attempt This Online!

-2 bytes thanks to pajonk.

# Answer
> 4 votes
# Desmos, ~~55~~ 49 bytes

```
f(a,b)=[lforl=a,i=[0...floor(b.length/a.length)]]

```

Try It On Desmos!

Try It On Desmos! - Prettified

~~I had to write `l=a[1...]` instead of just `l=a` because apparently Desmos defaults to recognizing function arguments as numbers, which the list comprehension doesn't like. The workaround is to force Desmos to recognize it as a list by slicing it in such a way that it just returns the entire list, resulting in +6 bytes.~~

Apparently the workaround wasn't even necessary because I *think* `a.length` forces Desmos to recognize `a` as a list, rather than a number. Thanks @att for helping me realize this.

# Answer
> 4 votes
# Exceptionally, ~~25~~ 18 bytes

```
GV}lL}nGVL/nIU*lP/

```

Attempt This Online!

### Explanation

```
' Get an input
G
' Eval it
V
' Store that in ls
} ls
' Get its length
L
' Store that in num
} num
' Get an input
G
' Eval it
V
' Get the length
L
' Divide by num
/ num
' Truncate to integer
I
' Increment
U
' Repeat ls that many times
* ls
' Print
P
' Attempt to divide the list by itself, ending the program
/

```

# Answer
> 4 votes
# Factor \+ `sequences.repeating`, ~~45~~ 42 bytes

```
[ length over length tuck /i 1 + * cycle ]

```

## Explanation

```
          ! { 2 3 5 } { 1 2 3 4 5 6 7 }
length    ! { 2 3 5 } 7
over      ! { 2 3 5 } 7 { 2 3 5 }
length    ! { 2 3 5 } 7 3
tuck      ! { 2 3 5 } 3 7 3
/i        ! { 2 3 5 } 3 2
1         ! { 2 3 5 } 3 2 1
+         ! { 2 3 5 } 3 3
*         ! { 2 3 5 } 9
cycle     ! { 2 3 5 2 3 5 2 3 5 }

```

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

*-1 byte thanks to Unrelated String in chat*

```
lᵐ÷<;?tᵗj₍

```

Takes input as a single list containing the two input lists in reverse order. Try it online!

### Explanation

Ports the common strategy of using int-division to calculate the rep-count:

```
lᵐ÷<;?tᵗj₍
lᵐ          Length of each list in the input
  ÷         Int-divide
   <        Next greater integer
    ;?      Pair with input
      tᵗ    Replace the last element with its tail (i.e. the second input list)
        j₍  Repeat the last element a number of times equal to the first element

```

For example, with input `[[1, 2, 3, 4, 5], [8, 9]]`:

```
lᵐ          [5, 2]
  ÷         2
   <        3
    ;?      [3, [[1, 2, 3, 4, 5], [8, 9]]]
      tᵗ    [3, [8, 9]]
        j₍  [8, 9, 8, 9, 8, 9]

```

### Old solution, 11 bytes

Implements the spec pretty directly, using Brachylog's backtracking:

```
hj↙İ.&tl<~l
h            The first of the inputs
 j           Concatenated to itself
  ↙İ         an unspecified number of times
    .        is the output
     &       And
      t      The second of the inputs
       l     Length of ^
        <    is less than a number
         ~l  which is the length of
             the output (implicit)

```

# Answer
> 4 votes
# Mathematica/Wolfram Language, (44) 41 Bytes

`PadLeft[#,Ceiling[Tr[1^#2]+1,Tr[1^#]],#]&`

*-3 bytes from alephalpha on something I really should have caught*

I feel like this could still be shorter, but it works as-is. Uses Tr\[1^x\] as a way of getting Length for cheap, and takes advantage of Ceiling having a two-argument mode. Other than that, it would probably take a full rewrite to improve, since I can't use \[LeftCeiling\] to shave bytes with the two-argument mode.

Try It Online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), 33 bytes

```
Table[##&@@#,Tr[1^#2]/Tr[1^#]+1]&

```

Try it online!

# Answer
> 3 votes
# Charcoal, ~~9~~ 8 bytes

```
Ｗ¬›ⅉＬηＩθ

```

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

```
Ｗ¬›ⅉＬη

```

Until the number of output lines exceeds the length of the second input...

```
Ｉθ

```

... output each element of the first input on its own line.

# Answer
> 3 votes
# Ruby, 26 bytes

```
->x,y{x*(y.size/x.size+1)}
```

Attempt This Online!

# Answer
> 3 votes
# TI-Basic, 26 bytes

```
Prompt A,B
ʟA
While dim(Ans)≤dim(ʟB
augment(Ans,ʟA
End
Ans

```

Output is stored in `Ans` and displayed.

# Answer
> 3 votes
# Julia 1.0, 31 bytes

```
~=length
A%B=repeat(A,~B÷~A+1)

```

Try it online!

# Answer
> 2 votes
# APL+WIN, 18 bytes

Prompts for a nested vector comprising of list b followed by list a

```
∊(∊1+⌊÷/⍴¨v)⍴1↓v←⎕

```

Try it online! Thanks to Dyalog APL Classic

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

```
(a,b)=>Array(~~(b.length/a.length)+1).fill``.map(_=>a).flat()

```

Try it online!

Way longer than the other answers but who cares. Should work in the browser too but TIO only supports `Array.flat()` in Node.

# Answer
> 2 votes
# Perl 6, 34 bytes

```
{|@^a xx 1+@^b.elems div@^a.elems}

```

Try it online!

# Answer
> 2 votes
# C (clang), ~~62~~ 61 bytes

*-1 thanks to @ceilingcat*

```
f(*a,b,c,d){for(;b=++d%c;);for(;d--;)printf("%d ",a[b++%c]);}

```

Try it online! Inputs are list `a`, list `b`, and their respective lengths in that order (as C doesn't store length information in arrays); outputs are sent to stdout.

# Answer
> 2 votes
# BQN, 17 bytes

```
⊑⥊˜≠∘⊑×1+·⌊∘÷˜´≠¨

```

Anonymous tacit function that takes a single argument, a list containing the two input lists. Try it at BQN online

### Explanation

```
⊑⥊˜≠∘⊑×1+·⌊∘÷˜´≠¨
                ≠¨  Length of each list
               ´    Fold that two-integer list on
              ˜     Reversed-order
           ⌊∘÷      Division-and-floor
          ·         Then
        1+          Add 1
       ×            Multiply by
    ≠∘⊑             Length of the first list
 ⥊˜                Reshape to that length
⊑                  The first list

```

# Answer
> 2 votes
# Pip, 12 bytes

```
Ty#>b{Yy.a}y

```

Try It Online!

How?

```
Ty#>b{Yy.a}y
T    {    }  - Till
 y#>b        - Length of y greater than length of b(2nd input)
      Y        - Yank (equivalent to (y:a))
       y.a     - y concatenated with a
           y - Return y

```

# Answer
> 2 votes
# Thunno, \\$ 10 \log\_{256}(96) \approx\\$ 8.23 bytes

```
LsL|1+z0A*

```

Attempt This Online!

**Explanation:**

```
LsL|1+z0A*  # Implicit input
LsL         # Length of both lists
   |1+      # Integer divided and incremented
      z0    # Push the first list
        A*  # Repeat that many times
            # Implicit output

```

# Answer
> 2 votes
# Uiua, 8 bytes

```
▽+1⌊÷∩⧻,

```

Try it!

```
▽+1⌊÷∩⧻,
       ,  # over
     ∩⧻   # length of both
    ÷     # divide
   ⌊      # floor
 +1       # increment
▽         # keep

```

# Answer
> 1 votes
# JavaScript (Node.js), ~~43~~ 48 bytes

+5 bytes, realised it doesn't work

```
a=>b=>{for(A=[...a];!a[b.length];a.push(...A));}

```

Try it online!

An alternative JS answer. Takes curried input `a` and `b` and extends `a` until it's longer than `b`.

# Answer
> 1 votes
# Arturo, 33 bytes

```
$[a,b][repeat a 1+/size b size a]

```

Try it

Integer divide the length of b by the length of a, add one, and repeat a that many times.

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
,ḷẸ÷⁺ọ

```

Try it online!

#### Explanation

```
,ḷẸ÷⁺ọ  # Implicit input
,ḷ      # Length of both
  Ẹ÷    # Floor divide
    ⁺   # Increment
     ọ  # Repeat first list
        # Implicit output

```

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

```
a=>b=>b.flatMap((_,i)=>~i%a.length*i?[]:a)

```

Try it online!

Assumes `len(a)>1`

# JavaScript (Node.js), 46 bytes

```
a=>b=>[...b,a].flatMap((_,i)=>i%a.length?a:[])

```

Try it online!

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


title: Do Matrix Multiplication!

text:
# Question
Title: Do Matrix Multiplication!
In mathematics, matrix multiplication or the matrix product is a binary operation that produces a matrix from two matrices. The definition is motivated by linear equations and linear transformations on vectors, which have numerous applications in applied mathematics, physics, and engineering. In more detail, if A is an n × m matrix and B is an m × p matrix, their matrix product AB is an n × p matrix, in which the m entries across a row of A are multiplied with the m entries down a columns of B and summed to produce an entry of AB. When two linear transformations are represented by matrices, then the matrix product represents the composition of the two transformations.

Source: Wikipedia

In other words, to multiply two matrices, for example:

```
1 2 3   1 4
2 3 4 × 3 1 =
3 4 5   4 6

```

First, take row number 1 in the first matrix, column number 1 in the second matrix, and multiply `1` by `1`, `2` by `3`, and `3` by `4`.

```
1 × 1 = 1
2 × 3 = 6
3 × 4 = 12

```

Now add them together to get your first item:

```
1 2 3   1 4   19
2 3 4 × 3 1 =
3 4 5   4 6

```

For the second number in the first column of the result, you will need to take row number 2 instead of row number 1 and do the same thing.

```
1 × 2 = 2
3 × 3 = 9
4 × 4 = 16
      = 27

```

After you do the entire first column, the result looks like this:

```
1 2 3   1 4   19
2 3 4 × 3 1 = 27
3 4 5   4 6   35

```

Now, do the same exact thing again, but take the second column instead of the first column, resulting in:

```
1 2 3   1 4   19 24
2 3 4 × 3 1 = 27 35
3 4 5   4 6   35 46

```

## Your task

Given two matrices (max dimensions 200x200), containing numbers in the range -10000 to 10000, where the number of columns on the first one equals the number of rows on the second, multiply the first one by the second one. (Matrix multiplication is non-commutative.)

You may take input and give output as an array of arrays (or equivalent), a matrix (if your language has that format) or a multiline string.

You may not use any built-ins for matrix multiplication.

## Test cases

```
1 2   1 2 3 4 5    13 16 19 22 25
3 4 × 6 7 8 9 10 = 27 34 41 48 55
5 6                41 52 63 74 85

2 3   3 5   15 13
3 4 × 3 1 = 21 19

5 3            11    27
1 3      1 3   7     15
9 3    × 2 4 = 15    39
1 -1000        -1999 -3997

```

Remember, this is , so the code with the fewest bytes wins.

# Answer
# Jelly, ~~7~~ 5 bytes

```
Z×þḅ1

```

Takes **B** and **A** as arguments and returns **A × B**.

Try it online!

### How it works

```
Z×þḅ1  Main link. Left argument: B. Right argument: A

Z      Zip; transpose B's rows and columns.
 ×þ    Table multiplication; multiply all columns of B (rows of B's transpose) by
       all rows of A, element by element. Results are grouped by the rows of A.
   ḅ1  Unbase 1; compute the sum of all flat arrays in the result.

```
> 6 votes

# Answer
# Python 2, ~~69~~ 66 Bytes

This just follows the standard formula, but lambda-d for conciseness :) The ungolfed code is extremely straightforward!

```
lambda x,y:[[sum(map(int.__mul__,r,c))for c in zip(*y)]for r in x]

```

*Thanks to Alexi Torhamo for saving 3 bytes! :)*

Ungolfed code:

```
x = [[1,2],[3,4],[5,6]]
y = [[1,2,3,4,5],[6,7,8,9,10]]

output = []
for row in x:
    nrow = []
    for col in zip(*y):                             # zip(*[]) transposes a matrix
        nrow += [sum(a*b for a,b in zip(row,col))]  # multiplication for each pair summed
    output += [nrow]

print output

```
> 5 votes

# Answer
# 05AB1E, 13 bytes

```
vyU²øvyX*O})ˆ

```

Try it online!

**Explanation**

```
v               # for each row in the first matrix
 yU             # save the row in X
   ²øv          # for each row in the transposition of the second matrix
      yX*       # multiply the rows
         O      # sum the elements of the resulting row
          }     # end inner loop
           )    # wrap elements of the new row in a list
            ˆ   # push to global list
                # implicitly output global list

```
> 4 votes

# Answer
# Haskell, ~~57 56~~ 54 bytes

```
e=[]:e
z=zipWith
a!b=[sum.z(*)r<$>foldr(z(:))e b|r<-a]

```

Try it online!

Usage:

```
Prelude> [[1,2],[3,4],[5,6]] ! [[1,2,3,4,5],[6,7,8,9,10]]
[[13,16,19,22,25],[27,34,41,48,55],[41,52,63,74,85]]

```

`foldr(zipWith(:))e` with `e=[]:e` is a shorter form of `transpose`.
> 4 votes

# Answer
# Haskell, 45 bytes

```
map.(foldr1(z(+)).).flip(z$map.(*))
z=zipWith

```

Try it online!

Takes arguments in reversed order.
> 4 votes

# Answer
# Mathematica, 20 bytes

```
Inner[1##&,##,Plus]&

```

Anonymous function. Takes two rank-2 lists of numbers as input, and returns a rank-2 list of numbers as output. For those curious, `Inner` is a function that does a matrix-multiplication-like application of two functions to two tensors.
> 3 votes

# Answer
# J, ~~13~~ 9 bytes

Saved 4 bytes thanks to miles!

```
[:+/*"#:~

```

This is a capped fork:

```
[: +/ *"#:~

```

Which is equivalent to:

```
[: +/ (*"#:)~
[: +/ (*"_ 1 0)~

```

Which performs the desired multiplication; these are then summed.

With a dot product built in, 5 bytes: `+/ .*`

## Test cases

```
   f =: [: +/ *"#:~
   (3 3$1 2 3 2 3 4 3 4 5)f(3 2$1 4 3 1 4 6)
19 24
27 35
35 46
   (3 3$1 2 3 2 3 4 3 4 5);(3 2$1 4 3 1 4 6)
+-----+---+
|1 2 3|1 4|
|2 3 4|3 1|
|3 4 5|4 6|
+-----+---+
   (2 2$2 3 3 4)f(2 2$3 5 3 1)
15 13
21 19
   (2 2$2 3 3 4);(2 2$3 5 3 1)
+---+---+
|2 3|3 5|
|3 4|3 1|
+---+---+

```
> 3 votes

# Answer
# Husk, ~~7~~ 6 bytes

```
mMδṁ*T

```

Please note the argument order, try it online!

-1 byte thanks to @Zgarb!

### Explanation

Basically just doing what the definition of matrix-multiplication sais:

```
mMδṁ*T  -- takes arguments in reverse order, eg: [[1],[0],[-1]] [[1,2,3],[4,5,6]]
     T  -- transpose the first argument: [[1,0,-1]] [[1,2,3],[4,5,6]]
m       -- map the following function (example element [1,0,-1])
 M      --   map the following function applied to [1,0,-1] (example element [1,2,3])
  δṁ    --     accumulate a sum of element-wise..
    *    --    ..multiplication: -2
          -- [[-2],[-2]]

```
> 3 votes

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

```
+/'*\:

```

Try it online!

Because arraylang FTW.

### How it works

```
+/'*\:    Dyadic train; x: m×n matrix; y: n×p matrix
   *\:    Multiply eachleft; multiply each row of x to whole of y
          each row of x (xr) = length-n vector
          each element of xr is multiplied to each row of y
          the result is m×n×p cube
+/'       Sum each; sum across the 2nd axis to get the m×p matrix

```

Jelly port is `×"€S€` which only ties with the existing solution.
> 3 votes

# Answer
# , 7 bytes

```
+/@:*"$

```

Try it online!

Port of the more well-known K idiom `(+/*)\:` (for each row of x1 and entirety of x2, first-axis multiply and sum). `"$` is the shorthand for `"1 _`, which satisfies the "for each row of x1 and entirety of x2" part.
> 3 votes

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

```
7L&!*Xs6Be!

```

Matrices are input using `;` as row separator.

**Try it online!**

Matrix multiplication without the builtin was part of my answer to *Showcase of languages*. However, when trying to reuse the original code for this answer I realized it had a bug (row vector output was incorrectly converted to a column vector). This is now corrected, both here and there. For an explanation of how the code works, see the referred post (length-11 snippet).
> 2 votes

# Answer
# C#, ~~168~~ 167 bytes

```
(A,B)=>{int n=A.Length,p=B[0].Length,i=0,j=0,k=0,s;var R=new int[n,p];while(i++<n)for(j=0;j<p;){s=0;for(k=0;k<A[0].Length;)s+=A[i][k]*B[k++][j];R[i,j++]=s;}return R;};

```

Thank you @Mukul Kumar for saving 1 byte, the while loop was actually shorter this time :P

Full program with test cases:

```
using System;
class Matrix
{
    static void Main()
    {
        Func<int[][], int[][], int[,]> a = null;

        a = (A,B)=>
        {
            int n=A.Length,p=B[0].Length,i=0,j=0,k=0,s;
            var R=new int[n,p];
            while(i++<n)
                for(j=0;j<p;)
                {
                    s=0;
                    for(k=0;k<A[0].Length;)
                        s+=A[i][k]*B[k++][j];
                    R[i,j++]=s;
                }
            return R;
        };

        int[,] t1 = a(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } },
            new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 } } );
        int[,] t2 = a(new int[][] { new int[] { 2, 3 }, new int[] { 3, 4 } },
            new int[][] { new int[] { 3, 5 }, new int[] { 3, 1 } });
        int[,] t3 = a(new int[][] { new int[] { 5, 3 }, new int[] { 1, 3 }, new int[] { 9, 3 }, new int[] { 1, -1000 } },
            new int[][] { new int[] { 1, 3 }, new int[] { 2, 4 } });

        Console.WriteLine(IsCorrect(t1, new int[,] { { 13, 16, 19, 22, 25 }, { 27, 34, 41, 48, 55 }, { 41, 52, 63, 74, 85 } } ));
        Console.WriteLine(IsCorrect(t2, new int[,] { { 15, 13 }, { 21, 19 } } ));
        Console.WriteLine(IsCorrect(t3, new int[,] { { 11, 27 }, { 7, 15 }, { 15, 39 }, { -1999, -3997 } } ));

        Console.Read();
    }

    static bool IsCorrect(int[,] answer, int[,] valid)
    {
        if (answer.Length != valid.Length)
            return false;
        for (int i = 0; i < answer.GetLength(0); i++)
            for (int j = 0; j < answer.GetLength(1); j++)
                if (answer[i, j] != valid[i, j])
                    return false;
        return true;
    }
}

```
> 2 votes

# Answer
## R, 66 bytes

```
function(A,B)apply(B,2,function(i)apply(A,1,function(j)sum(j*i)))

```

Unnamed function taking two R-matrices as input and returns the product. It makes use of `apply` which is used to apply functions across margins of arrays. It works just as a double `for` loop in this case: for each column of `B` and for each row of `A`, return the sum of the (vectorized) products.

Compare to the pure for loop approach (`101` bytes):

```
function(A,B){M=matrix(NA,m<-nrow(A),n<-ncol(B));for(i in 1:n)for(j in 1:m)M[j,i]=sum(A[j,]*B[,i]);M}

```
> 2 votes

# Answer
# C++14, ~~173~~ ~~168~~ ~~156~~ 146 bytes

* -5 bytes for returning via reference parameter
* -12 bytes for using foreach and `C.back()` instead counting on `i`
* -10 bytes for dropping `C.clear()` and requiring `C` to be empty at start

As unnamed lambda:

```
[](auto A,auto B,auto&C){int j,k,s=B[0].size();for(auto a:A){C.emplace_back(s);for(j=-1;++j<s;)for(k=-1;++k<B.size();C.back()[j]+=a[k]*B[k][j]);}}

```

Requires input and output as `vector<vector<int>>` and output must be empty beforehand.

Ungolfed:

```
auto f=
[](auto A, auto B, auto&C){
 int j,k,s=B[0].size();
 for (auto a:A){
  C.emplace_back(s);
  for (j=-1;++j<s;)
   for (k=-1;++k<B.size();
    C.back()[j]+=a[k]*B[k][j]
   );
 }
}
;

```

Sample:

```
int main() {
 using M=std::vector<std::vector<int>>;
 M a = {
  {1,2,3},
  {2,3,4},
  {3,4,5},
 };
 M b = {
  {1,4},
  {3,1},
  {4,6},
 };
 M c;
 f(a,b,c);
 for (auto&r:c){
  for (auto&i:r) std::cout << i << ", ";
  std::cout << "\n";
 }
}

```
> 2 votes

# Answer
## JavaScript (ES6), 66 bytes

```
(a,b)=>a.map(c=>b[0].map((_,i)=>b.reduce((s,d,j)=>s+d[i]*c[j],0)))

```
> 1 votes

# Answer
## C#, 131 bytes

```
(A,B)=>new List<List<int>>(A.Select(x=>new List<int>
    (B[0].Select((f,i)=>B.Select(r=>r[i])).Select(y=>x.Zip(y,(p,q)=>p*q).Sum()))));

```

I stole Yodle's solution with the assumption that I could write this more efficiently using LINQ (as opposed to for loops). Took a few attempts but crunched it down somewhat.

Here it is broken down somewhat:

```
a = (A, B) => new List<List<int>>(
            from x in A
            select new List<int>(
                from y in B.First().Select((f, i) => B.Select(r => r.ElementAt(i)))
                select x.Zip(y, (p, q) => p * q).Sum()));

```

The only real 'trick' here is the matrix transpose, `B.First().Select((f, i) => B.Select(r => r.ElementAt(i)))`. Once we transpose the second matrix, we have two arrays `A[i,x]` and `B[j,x]`. Take the cartesian product (`i*j`) and Zip each of those `x` length arrays together.

Test code:

```
using System;
class Matrix
{
    static void Main()
    {
        Func<int[][], int[][], List<List<int>>> a = null;
        a = (A, B) => new List<List<int>>(A.Select(x => new List<int>(B[0].Select((f, i) => B.Select(r => r[i])).Select(y => x.Zip(y, (p, q) => p * q).Sum()))));

        List<List<int>> t1 = a(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } },
            new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 } });
        List<List<int>> t2 = a(new int[][] { new int[] { 2, 3 }, new int[] { 3, 4 } },
            new int[][] { new int[] { 3, 5 }, new int[] { 3, 1 } });
        List<List<int>> t3 = a(new int[][] { new int[] { 5, 3 }, new int[] { 1, 3 }, new int[] { 9, 3 }, new int[] { 1, -1000 } },
            new int[][] { new int[] { 1, 3 }, new int[] { 2, 4 } });

        Console.WriteLine(IsCorrect(t1, new int[,] { { 13, 16, 19, 22, 25 }, { 27, 34, 41, 48, 55 }, { 41, 52, 63, 74, 85 } }));
        Console.WriteLine(IsCorrect(t2, new int[,] { { 15, 13 }, { 21, 19 } }));
        Console.WriteLine(IsCorrect(t3, new int[,] { { 11, 27 }, { 7, 15 }, { 15, 39 }, { -1999, -3997 } }));

        Console.Read();
    }

    static bool IsCorrect(List<List<int>> answer, int[,] valid)
    {
        if (answer.Count*answer[0].Count != valid.Length)
            return false;
        for (int i = 0; i < answer.Count; i++)
            for (int j = 0; j < answer[0].Count; j++)
                if (answer[i][j] != valid[i, j])
                    return false;
        return true;
    }

}

```
> 1 votes

# Answer
# Haskell, 49 bytes

```
z=zipWith
m a=map(\x->foldr1(z(+))$z(map.(*))x a)

```

Try it online!

Input and output are lists of columns. Maps each column of the second matrix to that row, zipped with the columns of the first matrix and scaling each, summed as a vector.

I feel that there's gotta be a nice way to make this pointfree and save a handful of bytes, but I'm not seeing it yet.
> 1 votes

# Answer
# ayr, 9 bytes

An array lang I'm currently working on. It's not complete, but it can solve this just fine.

```
+/&*\@;:=

```

# Explanation

```
A = left matrix, B = right matrix

        =  Transpose B
    \      Table of A and =B
+/&*       Reduction via sum after multiplying
     @;:   After squishing (rank-2 matrix to rank-1 vector) both args

```

I'm probably going to add inner product eventually, so this solution will eventually be `+ .*` or `+/ .*`, haven't decided which yet. I can't make use of the k idiom, as multiplication between a vector and matrix is currently unsupported, resulting in a rank error.
> 1 votes

# Answer
# Uiua, 5 bytes

```
∺'/+×

```

Try it online!

Takes two matrices in reverse order, because `∺ distribute` evaluates on the entirety of the first arg and each row of the second, and there is no mirror version of it. Other than that, this also works like the K idiom.

```
∺'/+×    input: matrix A(m*k), matrix B(n*m)
∺        map over the entirety of A(m*k) and each row of B(m):
 '  ×    multiply each row of A and each element of B and
  /+     sum each column

```
> 1 votes

# Answer
# Javascript, 128 bytes

```
m=(a,b)=>{$=[];q=0;for(x in b){c=[];j=0;for(y in a[0]){_=i=0;for(z in b[0]){_+=a[i][j]*b[q][i];i++}c.push(_);j++}$.push(c);q++}}

```

You get the result by just checking $ - it's kinda cheating, but hey, it saved a few bytes.
> 0 votes

# Answer
# PHP, 110 bytes

```
function f($a,$b){foreach($a as$n=>$x)foreach($b as$m=>$y)foreach($y as$p=>$v)$z[$n][$p]+=$v*$x[$m];return$z;}

```

Three loops for the elven arrays. This is so straight forward ... but there´s not much to golf.
> 0 votes

# Answer
# Actually, 14 bytes

Golfing suggestions welcome! Try it online!

```
┬@;l)∙`i♀*Σ`M╡

```

**Ungolfing**

```
         Implicit input A, then B.
┬        Transpose B's rows and columns. Call it B_T.
@        Swap A to TOS.
;l)      Get len(A) and move to BOS for later.
∙        Push the Cartesian product of A and B_T. Call it cart_prod.
`...`M   Map the following function over cart_prod. Variable xs.
  i        Flatten xs onto the stack, getting a row of A and column of B.
  ♀*       Multiply each element of A_row by each element of B_column.
  Σ        Sum the resulting list to get an element of A*B.
         The result of the map returns every element of A*B, but in one flat list.
╡        Push a list containing len(A) non-overlapping sublists of A*B.
         This separates A*B into rows.
         Implicit return.

```
> 0 votes

# Answer
# C, 618 bytes

```
M(char*a,char*b){char*P[2];P[0]=malloc(strlen(a));P[1]=malloc(strlen(b));for(int A=0;A<strlen(a);A++){P[0][A]=a[A];};for(int B=0;B<strlen(b);B++){P[1][B]=b[B];};int H[200][200],B[200][200];int O,N,m,J;for(int Y=0;Y<2;Y++){int y=0,z=0,r=0;char j[7];int p=strlen(P[Y]);for(int i=0;i<=p;i++){if(P[Y][i]==' '||P[Y][i]==','||i==p){(Y<1)?H[y][z]=atoi(j):(B[y][z]=atoi(j));memset(j,'\0',4);(P[Y][i]==' ')?z++:y++;z=(P[Y][i]==',')?0:z;r=0;}else{j[r]=P[Y][i];r++;};};(Y<1)?O=z+1,N=y:(m=y,J=z+1);};for(int U=0;U<N;U++){for(int F=0;F<J;F++){int T=0;for(int d=0;d<O;d++){T+=H[U][d]*B[d][F];};printf("%d ",T);T=0;};printf("\n");};}

```

A named function and by *far* the longest submission here, partly due to the fact that converting the character array inputs into C 2-dimensional integer arrays is taking up the most bytes, and also because I have not golfed in C in the longest time. I am still working on shortening this as much as I can, and any tips in doing so are much appreciated.

Now, with that out of the way, this takes input through the command line with the two matrices represented by two strings, with each one containing the rows separated by commas and each row represented by space separated integers. For example, the matrices:

```
   1 2 3     44 52
A= 4 5 6  B= 67 -79
   7 8 9     83 90

```

would be input as:

`./a.out "1 2 3,4 5 6,7 8 9" "44 52,67 -79,83 90"`

The resulting matrix is output to STDOUT as a multiline string. For example, the output for the above input would be:

```
 427 164
1009 353
1591 542

```
> 0 votes

# Answer
## Clojure, 60 bytes

```
#(for[a %](for[b(apply map vector %2)](apply +(map * a b))))

```

Many bytes spent on transposing the 2nd argument.
> 0 votes

# Answer
# Ruby, 59 bytes

```
->m,n{m.map{|r|n.transpose.map{|c|r.zip(c).sum{|i,j|i*j}}}}

```

Try it online!
> 0 votes

# Answer
# Raku, 55 bytes

```
{cross(with=>{sum @^x Z*@^y},@^a,[Z] @^b).rotor(@b[0])}

```

Try it online!
> 0 votes

# Answer
# Julia 1.0, 49 bytes

```
% =axes
a\b=[sum(a[i,:].*b[:,j]) for i=a%1,j=b%2]

```

Try it online!

~~1 byte~~
> 0 votes

# Answer
# Nibbles, 5.5 bytes (11 nibbles)

```
.$.`'_+!$_*

```

Attempt This Online!

```
.$           # map over the rows of matrix 1
  .          #   map over the rows of
   `'        #   transpose of
     _       #   matrix 2
      +      #     sum of
       !     #     zip together
        $_   #     both rows
          *  #       by multiplication

```
> 0 votes

# Answer
# Nekomata, 4 bytes

```
ᵐ*ᵐ∑

```

Attempt This Online!

```
ᵐ*ᵐ∑
ᵐ       Map
 *      Multiply
  ᵐ     Map
   ∑    Sum

```

If a built-in for dot product is allowed, then it can be 2 bytes:

```
ᵐ∙

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, math, matrix
---


title: Filter out and add up

text:
# Question
Title: Filter out and add up
### Task

The task is very simple. Given a non-empty string containing **numbers**, **uppercase** and **lowercase letters**, output the sum of the remaining numbers. For example:

```
a1wAD5qw45REs5Fw4eRQR33wqe4WE

```

Filtering out all the letters would result into:

```
 1   5  45   5  4    33   4

```

The sum of these numbers is `1 + 5 + 45 + 5 + 4 + 33 + 4 = 97`. So the output would be `97`.

### Test Cases

```
a > 0
0 > 0
5 > 5
10 > 10
a0A > 0
1a1 > 2
11a1 > 12
4dasQWE65asAs5dAa5dWD > 79
a1wAD5qw45REs5Fw4eRQR33wqe4WE > 97

```

This is , so the submission with the least amount of bytes wins!

# Answer
> 23 votes
# GS2, 2 bytes

```
Wd

```

Try it online!

### How it works

```
W     Read all numbers.
      For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
 d    Compute their sum.

```

# Answer
> 13 votes
## Labyrinth, 8 bytes

Take that, Pyth...

```
?+
;,;!@

```

Try it online!

### Explanation

The usual primer (stolen from Sp3000):

* Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
* When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.

What comes in really handy here is that Labyrinth has two different input commands, `,` and `?`. The former reads a single byte from STDIN, or `-1` at EOF. The latter reads an integer from STDIN. It does so skipping everything that *isn't* a number and then reads the first decimal number it finds. This one returns `0` at EOF, so we can't use it to check for EOF reliably here.

The main loop of the program is this compact bit:

```
?+
;,

```

With `?` we read an integer (ignoring all letters), with `+` we add it to the running total (which starts out as one of the implicit zeroes at the stack bottom). Then we read another character with `,` to check for EOF. As long as we're not at EOF, the read character will be a letter which has a positive character code, so the IP turns right (from its point of view; i.e. west). `;` discards the character because we don't need it and then we enter the loop again.

Once we're at EOF, `,` pushes a `-1` so the IP turns left (east) instead. `;` again discards that `-1`, `!` prints the running total as an integer and `@` terminates the program.

# Answer
> 7 votes
# MATL, 8 bytes

```
1Y4XXXUs

```

**Try it online!**

```
1Y4      % predefined literal: '\d+'
XX       % implicit input. Match regular expression. Returns a cell array of strings
         % representing numbers
XU       % convert each string to a double. Returns a numeric array
s        % sum of numeric array

```

# Answer
> 6 votes
## CJam, 13 bytes

Fixed to work with input without numbers thanks to Dennis! Also saved a byte by replacing the letters array with an array of ASCII above code point 64. And then another byte saved by Dennis!

```
q_A,s-Ser~]1b

```

Simple transliteration from letters to spaces, then eval and sum. Try it online.

# Answer
> 6 votes
# JavaScript ES6, 35 bytes

```
s=>eval(s.replace(/\D+/g,'+')+'.0')

```

### How it works

First, we replace each string of non-digits with `"+"`. There are basically four different ways that this could end up:

```
1. 1b23c456   => 1+23+456
2. a1b23c456  => +1+23+456
3. 1b23c456d  => 1+23+456+
4. a1b23c456d => +1+23+456+

```

Cases 1 and 2 are taken care of already. But we somehow need to fix the last `+` so that it doesn't cause an error. We could remove it with `.replace(/\+$,"")`, but that's too expensive. We could append a `0` to the end, but that would affect the last number if the string does not end with a `+`. A compromise is to append `.0`, which is both a valid number on its own and doesn't affect the value of other integers.

Here's a few other values that would work as well:

```
.0
-0
 +0
-""
-[]
0/10
0e-1
.1-.1

```

### Alternate version, also 35 bytes

```
s=>s.replace(/\d+/g,d=>t+=+d,t=0)|t

```

### Another alternate version, 36 bytes

```
s=>s.split(/\D/).map(d=>t+=+d,t=0)|t

```

# Answer
> 5 votes
# Retina, ~~22~~ 11

```
\d+
$0$*1
1

```

Try it online!

11 bytes (!) saved thanks to Martin!

Basically just decimal to unary then count the `1`s.

# Answer
> 5 votes
# Japt, 2 bytes

```
Nx

```

Test it online!

### How it works

```
N    // Implicit: N = (parse input for numbers, "strings", and [arrays])
x    // Sum. Implicit output.

```

# Answer
> 4 votes
## Pyth, ~~12~~ ~~11~~ 10 bytes

```
ssM:z"\D"3

```

```
    z        autoinitialized to input()
   : "\D"3   split on non-digits
 sM          convert all elements of resulting array to ints
s            sum

```

Fortunately, `s` (convert to int) returns `0` when applied to the empty string, so I don't have to worry about the fact that `split("a1b", "\D+")` returns `["", "1", ""]`. Similarly, `split("a", "\D+")` returns `["", ""]`.

This even allows me to split on every non-digit individually, since `1 + 0 + 0 + 0 + 0 + 2` is the same thing as `1 + 2`.

Thanks to Thomas Kwa for a byte!

# Answer
> 4 votes
# Gol\>\<\>, 4 bytes

```
iEh+

```

So short I need dummy text...

# Answer
> 4 votes
# Perl 6, 18 bytes

```
{[+] .comb(/\d+/)}
{[+] .split(/\D/)}

```

### Usage:

```
my &code = {[+] .comb(/\d+/)}

say code 'a'; # 0
say code '0'; # 0
say code '5'; # 5
say code '10'; # 10
say code 'a0A'; # 0
say code '1a1'; # 2
say code '11a1'; # 12
say code '4dasQWE65asAs5dAa5dWD'; # 79
say code 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'; # 97

```

# Answer
> 3 votes
# Jelly, 6 bytes

```
&-ṣ-ḌS

```

Try it online!

### How it works

```
&-ṣ-ḌS  Main link. Input: L (string)

&-      Take the bitwise AND of L's characters and -1.
        This attempts to cast to int, so '0' & -1 -> 0 & -1 -> 0.
        On failure, it returns the integer argument (if any), so 'a' & -1 -> -1.
  ṣ-    Split the resulting list at occurrences of -1.
    Ḍ   Convert each chunk from decimal to integer. In particular, [] -> 0.
     S  Compute the sum of the results.

```

# Answer
> 3 votes
# Perl, 21 + 1 = 22 bytes

```
$_=eval join"+",/\d+/g

```

Requires the `-p` flag:

```
$ perl -pe'$_=eval join"+",/\d+/g' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97

```

# Answer
> 3 votes
# Julia, 35 bytes

```
s->sum(parse,matchall(r"\d+","0"s))

```

This is an anonymous function that accepts a string and returns an integer. To call it, assign it to a variable.

We use `matchall` to get an array consisting of matches of the regular expression `\d+`, which are just the integers in the string. We have to tack on a 0 to the front of the string, otherwise for cases like `"a"`, we'd be summing over an empty array, which causes an error. We then apply `parse` to each string match, which converts to integers, and take the sum.

# Answer
> 3 votes
# Vyxal `s`, 4 bytes

```
⁽±Ḋ⌊

```

Try it Online!

# Answer
> 3 votes
# Ruby `-n`, 23 bytes

Based on Ventero’s answer here.

```
p eval$_.scan(/\d+/)*?+

```

Attempt This Online!

# Answer
> 2 votes
# Javascript, ~~32~~ 39 bytes

```
s=>eval((s.match(/\d+/g)||[0]).join`+`)

```

```
f=
s=>eval((s.match(/\d+/g)||[0]).join`+`)

F=s=>document.body.innerHTML+='<pre>f(\''+s+'\') -> '+f(s)+'\n</pre>'

F('a')
F('5')
F('10')
F('1a1')
F('11a1')
F('4dasQWE65asAs5dAa5dWD')
F('a1wAD5qw45REs5Fw4eRQR33wqe4WE')
```

# Answer
> 2 votes
# Mathematica, 51 bytes

```
Total@ToExpression@StringCases[#,DigitCharacter..]&

```

Catching the wrong end of the verbose Mathematica builtins. 1 Byte off with the help of @DavidC

# Answer
> 2 votes
# PHP, 64 bytes

```
<?php preg_match_all("/\d+/",$argv[1],$a);echo array_sum($a[0]);

```

Run it as

```
php -f filterOutAndAddUp.php <test_case>

```

https://eval.in/517817

# Answer
> 2 votes
# R, ~~46~~ 43 bytes

```
sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))

```

**Explanation**

```
                    scan(,'')                  # Take the input string
           strsplit(         ,'\\D')           # Returns list of all numeric parts of the string
                                    [[1]]      # Unlists to character vector
    strtoi(                              )     # Converts to numeric vector
sum(                                      )    # Sums the numbers

```

**Sample run**

```
> sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))
1: a1wAD5qw45REs5Fw4eRQR33wqe4WE
2:
Read 1 item
[1] 97

```

Edit: Replaced `[^0-9]` with `\\D`.

# Answer
> 2 votes
# Factor \+ `math.unicode sorting.human`, 36 bytes

```
[ find-numbers [ real? ] filter Σ ]

```

Attempt This Online!

```
                  ! "11a1"
find-numbers      ! { "" 11 "a" 1 }
[ real? ] filter  ! { 11 1 }
Σ                 ! 12

```

# Answer
> 1 votes
## PowerShell, ~~28~~ 26 bytes

```
$args-replace"\D",'+0'|iex

```

Takes input `$args` then does a regex `-replace` to swap the letters with `+0`, then pipes that to `iex` (short for `Invoke-Expression` and similar to `eval`).

```
PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97

```

---

**Alternatively**

If you're OK with some extraneous output, you can do the following, also at ~~28~~ 26 bytes:

```
$args-split"\D"|measure -s

```

This will take the input string `$args` and `-split` it into an array-of-strings on the non-numbers (removing them in the process). For example, `1a2b33` would turn into `['1','2','33']`. We pipe that to `Measure-Object` with the `-Sum` parameter. Output would be like the below:

```
PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'

Count    : 21
Average  :
Sum      : 97
Maximum  :
Minimum  :
Property :

```

<sub>Edit -- durr, don't need the `[ ]` in the regex since I'm no longer specifying a list of possible matches ... </sub>

# Answer
> 1 votes
# Gema, 39 characters

```
<D>=@set{s;@add{${s;};$0}}
?=
\Z=${s;0}

```

Sample run:

```
bash-4.3$ gema '<D>=@set{s;@add{${s;};$0}};?=;\Z=${s;0}' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'

```

# Answer
> 1 votes
## Seriously, 13 bytes

```
,ú;û+@s`≈`MΣl

```

Try it online!

Explanation:

```
,ú;û+@s`≈`MΣl
,              push input
 ú;û+          push "abc...zABC...Z" (uppercase and lowercase English letters)
     @s        split on letters
       `≈`M    convert to ints
           Σ   sum
            l  length (does nothing to an integer, pushes 0 if an empty list is left, in the case where the string is all letters)

```

# Answer
> 1 votes
# Java, 70 bytes

```
s->{int n=0;for(String i:s.split("\\D+"))n+=Long.valueOf(i);return n;}

```

# Answer
> 1 votes
# TI-Basic, 106 bytes

Works on TI-83/84 calculators!

```
Input Str1
"{0,→Str2
Str1+"N0→Str1
For(I,1,length(Ans
sub(Str1,I,1
If inString("0123456789",Ans
Then
Str2+Ans→Str2
Else
If ","≠sub(Str2,length(Str2),1
Str2+","→Str2
End
End
sum(expr(Ans

```

# Answer
> 1 votes
# Clojure/ClojureScript, 35 bytes

```
#(apply +(map int(re-seq #"\d+"%)))

```

# Answer
> 1 votes
# Bash + GNU utilities, 29

```
grep -Eo [0-9]+|paste -sd+|bc

```

---

If it is required to support input with no numbers (e.g. `a`), then we can do this:

# Bash + GNU utilities, 38

1 byte saved thanks to @TobySpeight.

```
(grep -Eo [0-9]+;echo 0)|paste -sd+|bc

```

# Answer
> 1 votes
# R, 50 bytes

Requires having `gsubfn` installed

```
sum(gsubfn::strapply(scan(,''),'\\d+',strtoi)[[1]])

```

Uses `strtoi` to coerce to numeric

# Answer
> 1 votes
# Ruby 45 bytes

```
$*[0].split(/[a-z]/i).map(&:to_i).inject 0,:+

```

(First attempt at work, will revisit this)

# Answer
> 1 votes
# POSIX sh + tr + dc, 27 25 bytes

```
dc -e "0d`tr -sc 0-9 +`p"

```

Converts any run of non-digits (including the terminating newline) to `+` operator, pushes two zeros onto the stack (in case input begins with non-digit), adds them all and prints the result. There may be an extra zero remaining at bottom of stack, but we don't care about that.

# Answer
> 1 votes
## Lua, 51 Bytes

Pretty short for once! Even shorter than Java! The input must be a command-line argument for it to work.

```
a=0 arg[1]:gsub("%d+",function(c)a=a+c end)print(a)

```

### Ungolfed

```
a=0                 -- Initialize the sum at 0
arg[1]:gsub("%d+",  -- capture each group of digits in the string
  function(c)       -- and apply an anonymous function to each of them
  a=a+c             -- sums a with the latest group captured
end)
print(a)            -- output a

```

# Answer
> 1 votes
# Python 2, 70 bytes

I am putting a Python answer just for fun.

```
import re
j=0
for i in map(int,re.findall('\d+',input())):j+=i
print j

```

Very simple and uses regex to find all the numbers in the input. Try it online!

# Answer
> 1 votes
# Oracle SQL 11.2, 105 bytes

```
SELECT NVL(SUM(TO_NUMBER(COLUMN_VALUE)),0)FROM XMLTABLE(('"'||regexp_replace(:1,'[a-zA-Z]','","')||'"'));

```

The regex convert alpha characters to ','

XMLTABLE create one row per item in the string using ',' as the separator.

SUM the rows to get the result.

NVL is needed to account for a string with no digit.

# Answer
> 1 votes
# Python 2, 71 bytes

I just had to make one-liner, though it costs a whole byte more than @TanMath's answer

```
sum(map(int,"".join([i*i.isdigit()or" "for i in raw_input()]).split()))

```

Explaination:

```
raw_input()                             - Input
"".join([i*i.isdigit()or" "for i in _]) - Replace non-digits with spaces
map(int, _.split())                     - Split on spaces, and convert to number
sum(_)                                  - Sum the resulting list

```

# Answer
> 1 votes
# J-uby, 19 bytes

```
~:scan&/\d+/|:sum+Z

```

Attempt This Online!

# Answer
> 1 votes
# Japt v2.0a0 `-x`, 3 bytes

'Cause ETH's solution is a bit cheaty!

```
q\D

```

Try it

```
q\D     :Implicit input of string
q       :Split on
 \D     :  RegEx /\D/ (or /[^0-9]/)
        :Implicit output of sum of resulting array

```

# Answer
> 1 votes
# Pip, 6 bytes

```
$+a@XI

```

Try It Online!

### Explanation

```
    XI  Built-in regex matching integers
   @    Find all matches in
  a     Command-line input
$+      Fold on addition

```

# Answer
> 1 votes
# jq -R, 31 bytes

```
[splits("\\D")|tonumber?]|0+add

```

Try it online!

# Answer
> 1 votes
# \+ `regex`, 21 bytes

```
1#.0,'\d+'".&>@rxall]

```

Attempt This Online!

```
1#.0,'\d+'".&>@rxall]
     '\d+'     rxall]  NB. find all matches of /\d+/ in right arg ]
              @        NB. then execute the monadic verb...
          ".&>         NB. eval each boxed match and unbox result
   0,                  NB. prepend 0 in case of no match
1#.                    NB. sum integer array

```

If adding the script to the language isn't allowed, then that adds `14` bytes for a total of `35`.

```
1#.0,'\d+'".&>@rxall(load'regex')]]

```

The only difference is the fork `(load'regex')]]` that loads the library and simply returns the function arg using dyadic `]`.

# Answer
> 1 votes
# Uiua, ~~19~~ 12 bytes

```
/+⊜parse≤@9.

```

Try it!

-7 thanks to Bubbler

```
/+⊜parse≤@9.
           .  # duplicate
        ≤@9   # where are the characters less than or equal to 9?
  ⊜parse      # partition to an array of integers
/+            # sum

```

# Answer
> 0 votes
# 05AB1E (legacy), 3 bytes

```
á¡O

```

Try it online or verify all test cases.

In the new version of 05AB1E it would have been 2 bytes longer, because `¡` now supports substrings to split on (in the legacy version a string argument would be interpret as a list of characters implicitly) and will keep empty strings:

```
áS¡þO

```

Try it online or verify all test cases.

**Explanation:**

```
       # Example input: "a1wAD5qw45REs5Fw4eRQR33wqe4WE"

       # (legacy version)
á      # Only keep the letters of the (implicit) input-string
       #  STACK: "awADqwREsFweRQRwqeWE"
 ¡     # Split the (implicit) input-string on those characters
       #  STACK: ["1","5","45","5","4","33","4"]
  O    # Sum the remaining numbers
       #  STACK: 97
       # (which is output implicitly as result)

       # (new version)
á      # (same as above)
 S     # Split it to a list of characters
       #  STACK: ["a","w","A","D","q","w","R","E","s","F","w","e","R","Q","R","w","q","e","W","E"]
  ¡    # Split the (implicit) input-string on those characters
       #  STACK: ["","1","","","5","","45","","","5","","4","","","","33","","","4","",""]
   þ   # Remove all empty strings, by only keeping numbers
       #  STACK: ["1","5","45","5","4","33","4"]
    O  # (same as above)

```

# Answer
> 0 votes
# , ~~41~~ 20 bytes

```
sum value .Q.n .Q.n?

```

# k, ~~23~~ 14 bytes

```
+/. .Q.n .Q.n?

```

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