title: Alphabet completion rate

text:
# Question
Title: Alphabet completion rate
## Introduction

How much of the English alphabet does a given string use? The previous sentence uses 77%. It has 20 unique letters (howmucftenglisapbdvr), and 20/26 ≃ 0.77.

## Challenge

For an input string, return the percentage of letters of the English alphabet present in the string.

* The answer can be in percentage or in decimal form.
* The input string can have upper and lower case, as well as punctuation. However you can assume they have no diacritics or accentuated characters.

## Test cases

Input

```
"Did you put your name in the Goblet of Fire, Harry?" he asked calmly.

```

Some valid outputs

```
77%, 76.9, 0.7692

```

Input:

```
The quick brown fox jumps over the lazy dog

```

All valid outputs:

```
100%, 100, 1

```

The expected output for `"@#$%^&*?!"` and `""` is 0.

# Answer
# Python 3, 42 bytes

```
lambda s:len({*s.upper()}-{*s.lower()})/26

```

Try it online!

We filter all the non-alphabetic characters out of the string by taking the (set) difference of the uppercase and lowercase representations. Then, we take the length and divide by 26.

# Python 3, 46 bytes

```
lambda s:sum(map(str.isalpha,{*s.lower()}))/26

```

Try it online!

Count the unique alphabetic (lowercase) characters, and divide by 26. In Python 2 it would require 3 more characters; two for changing `{*...}` to `set(...)`, and one for making 26 a float: `26.`, to avoid floor division.

# Python 3, 46 bytes

```
lambda s:sum('`'<c<'{'for c in{*s.lower()})/26

```

Try it online!

Same length, essentially the same as the previous one, but without "built-in" string method.
> 21 votes

# Answer
# MATL, 8 bytes

```
2Y2jkmYm

```

Try it at MATL Online

**Explanation**

```
2Y2    % Predefined literal for 'abcdefghijklmnopqrstuvwxyz'
j      % Explicitly grab input as a string
k      % Convert to lower-case
m      % Check for membership of the alphabet characters in the string.
       % Results in a 26-element array with a 1 where a given character in
       % the alphabet string was present in the input and a 0 otherwise
Ym     % Compute the mean of this array to yield the percentage as a decimal
       % Implicitly display the result

```
> 11 votes

# Answer
# Octave / MATLAB, 33 bytes

```
@(s)mean(any(65:90==upper(s)',1))

```

Try it online!

### Explanation

```
@(s)                               % Anonymous function with input s: row vector of chars
             65:90                 % Row vector with ASCII codes of uppercase letters
                    upper(s)       % Input converted to uppercase
                            '      % Transform into column vector
                  ==               % Equality test, element-wise with broadcast. Gives a
                                   % matrix containing true and false
         any(                ,1)   % Row vector containing true for columns that have at
                                   % least one entry with value true
    mean(                       )  % Mean

```
> 8 votes

# Answer
# 05AB1E, ~~8~~ ~~7~~ 6 bytes

```
lASåÅA

```

-1 byte thanks to *@LuisMendo*.

Try it online or verify a few more test cases.

**6 bytes alternative provided by *@Grimy*:**

```
láÙg₂/

```

Try it online or verify a few more test cases.

Both programs output as decimal.

**Explanation:**

```
l       # Convert the (implicit) input-string to lowercase
 AS     # Push the lowercase alphabet as character-list
   å    # Check for each if it's in the lowercase input-string
        # (1 if truthy; 0 if falsey)
    ÅA  # Get the arithmetic mean of this list
        # (and output the result implicitly)

l       # Convert the (implicit) input-string to lowercase
 á      # Only leave the letters in this lowercase string
  Ù     # Uniquify it
   g    # Get the amount of the unique lowercase letters by taking the length
    ₂/  # Divide this by 26
        # (and output the result implicitly)

```
> 8 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~56~~ 49 bytes

```
a=>a.ToUpper().Distinct().Count(x=>x>64&x<91)/26f

```

Try it online!

*-6 bytes thanks to innat3*
> 7 votes

# Answer
# K (oK), ~~19~~ 15 bytes

**Solution:**

```
1%26%+/26>?97!_

```

Try it online!

**Explanation:**

Convert input to lowercase, modulo 97 ("a-z" is 97-122 in ASCII, modulo 97 gives 0-25), take unique, sum up results that are lower than 26, and convert to the percentage of 26.

```
1%26%+/26>?97!_ / the solution
              _ / lowercase
           97!  / modulo (!) 97
          ?     / distinct
       26>      / is 26 greater than this?
     +/         / sum (+) over (/)
  26%           / 26 divided by ...
1%              / 1 divided by ...

```

**Notes:**

* **-1 bytes** thanks to ngn, `1-%[;26]` =\> `1-1%26%`
* **-3 bytes** inspired by ngn `#(!26)^` =\> `+/26>?`
> 7 votes

# Answer
# APL (Dyalog Extended), 10 bytesSBCS

Anonymous tacit prefix function. Returns decimal fraction.

```
26÷⍨∘≢⎕A∩⌈

```

Try it online!

uppercase

`⎕A∩` intersection with the uppercase **A**lphabet

tally length

then

`26÷⍨` divide by twenty-six
> 6 votes

# Answer
## Bash and Gnu utils (81 78 68 60 42 bytes)

```
bc -l<<<`grep -io [a-z]|sort -fu|wc -l`/26

```

-8 bytes thanks to @wastl

-18 bytes thanks to Nahuel using some tricks I didn't know:

* `sort -f` and `grep -i` ignore case
* `sort -u` is a replacement for `| uniq`
> 6 votes

# Answer
# Perl 6, ~~27~~ 24 bytes

*-3 bytes thanks to nwellnhof*

```
*.uc.comb(/<:L>/).Set/26

```

Try it online!
> 6 votes

# Answer
# , 47 bytes

```
function(x)mean(65:90%in%utf8ToInt(toupper(x)))

```

Try it online!

Converts to upper case then to ASCII code-points, and checks for values 65:90 corresponding to A:Z.
> 6 votes

# Answer
# PowerShell, 55 52 bytes

```
($args|% *per|% t*y|sort|gu|?{$_-in65..90}).count/26

```

Try it online!

First attempt, still trying random ideas

EDIT: @Veskah pointed out ToUpper saves a byte due to the number range, also removed extra `()` and a space

Expansion:
`($args|% ToUpper|% ToCharArray|sort|get-unique|where{$_-in 65..90}).count/26`

Changes string to all loweruppercase, expands to an array, sorts the elements and selects the unique letters (gu needs sorted input), keep only characters of ascii value 97 to 122 (a to z) 65 to 90 (A to Z), count the total and divide by 26 for the decimal output
> 6 votes

# Answer
# Java 8, ~~62~~ 59 bytes

```
s->s.map(c->c&95).distinct().filter(c->c%91>64).count()/26.

```

-3 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
s->                     // Method with IntStream as parameter and double return-type
  s.map(c->c&95)        //  Convert all letters to uppercase
   .distinct()          //  Uniquify it
   .filter(c->c%91>64)  //  Only leave letters (unicode value range [65,90])
   .count()             //  Count the amount of unique letters left
    /26.                //  Divide it by 26.0

```
> 4 votes

# Answer
# Retina 0.8.2, 45 bytes

```
T`Llp`ll_
+`(.)(.*\1)
$2
.
100$*
^
13$*
.{26}

```

Try it online! Link includes test cases. Explanation:

```
T`Llp`ll_

```

Lowercase letters and delete punctuation.

```
+`(.)(.*\1)
$2

```

Deduplicate.

```
.
100$*

```

Multiply by 100.

```
^
13$*

```

Add 13.

```
.{26}

```

Integer divide by 26 and convert to decimal.
> 4 votes

# Answer
# APL (Dyalog Extended), 8 bytes

```
⌹∘≤⍨⎕A∊⌈

```

Try it online!

loosely based on Adám's answer

uppercase

`⎕A∊` boolean (0 or 1) vector of length 26 indicating which letters of the English **A**lphabet are in the string

`⌹∘≤⍨` arithmetic mean, i.e. matrix division of the argument and an all-1 vector of the same length
> 4 votes

# Answer
# K (oK), 19 bytes

```
1%26%26-#(!26)^97!_

```

Try it online!

# , 30 bytes

```
26%~26-u:@(97+i.26)#@-.tolower

```

Try it online!
> 3 votes

# Answer
# Retina, ~~57~~ ~~46~~ 35 bytes

```
.
$L
[^a-z]

D`.
.
100*
^
13*
_{26}

```

-11 bytes taking inspiration from *@Neil*'s trick of adding unary 13 before dividing.
Another -11 bytes thanks to *@Neil* directly.
Rounds (correctly) to a whole integer.

Try it online.

**~~57~~ ~~46~~ 40 bytes version which works with decimal output:**

```
.
$L
[^a-z]

D`.
.
1000*
C`_{26}
-1`\B
.

```

Same -11 bytes as well as an additional -6 bytes thanks to *@Neil*.

Outputs with one ***truncated*** decimal after the comma ( i.e. \\$0.1538\\$ (\\$\frac{4}{26}\\$) is output as `15.3` instead of `15.4`). This is done by calculating \\$\lfloor{\frac{1000 × \text{unique\_letters}}{26}\rfloor}\\$ and then inserting the decimal dot manually.

Try it online.

**Explanation:**

Convert all letters to lowercase:

```
.
$L

```

Remove all non-letters:

```
[^a-z]

```

Uniquify all letters:

```
D`.

```

Replace every unique letter with 1000 underscores:

```
.
1000*

```

Count the amount of times 26 adjacent underscores fit into it:

```
C`_{26}

```

Insert a dot at the correct place:

```
-1`\B
.

```
> 3 votes

# Answer
# Charcoal, 11 bytes

```
Ｉ∕ＬΦβ№↧θι²⁶

```

Try it online! Link is to verbose version of code. Output is as a decimal (or `1` for pangrams). Explanation:

```
  Ｌ         Length of
    β       Lowercase alphabet
   Φ        Filtered on
     №      Count of
        ι   Current letter in
      ↧     Lowercased
       θ    Input
 ∕          Divided by
         ²⁶ Literal 26
Ｉ           Cast to string
            Implicitly printed

```
> 3 votes

# Answer
## Batch, 197 bytes

```
@set/ps=
@set s=%s:"=%
@set n=13
@for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set t="%%s:%%c=%%"&call:c
@cmd/cset/an/26
@exit/b
:c
@if not "%s%"==%t% set/an+=100

```

Takes input on STDIN and outputs a rounded percentage. Explanation:

```
@set/ps=

```

Input the string.

```
@set s=%s:"=%

```

Strip quotes, because they're a headache to deal with in Batch.

```
@set n=13

```

Start with half a letter for rounding purposes.

```
@for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set t="%%s:%%c=%%"&call:c

```

Delete each letter in turn from the string. Invoke the subroutine to check whether anything changed, because of the way Batch parses variables.

```
@cmd/cset/an/26

```

Calculate the result as a percentage.

```
@exit/b
:c

```

Start of subroutine.

```
@if not "%s%"=="%t%" set/an+=100

```

If deleting a letter changed the string then increment the letter count.
> 3 votes

# Answer
# Pepe, ~~155~~ 138 bytes

```
rEeEeeeeeEREeEeEEeEeREERrEEEEErEEEeReeReRrEeeEeeeeerEEEEREEeRERrErEErerREEEEEeREEeeRrEreerererEEEEeeerERrEeeeREEEERREeeeEEeEerRrEEEEeereEE

```

Try it online! Output is in decimal form.

**Explanation:**

```
rEeEeeeeeE REeEeEEeEe # Push 65 -> (r), 90 -> (R)
REE # Create loop labeled 90 // creates [65,66,...,89,90]
  RrEEEEE # Increment (R flag: preserve the number) in (r)
  rEEEe # ...then move the pointer to the last
Ree # Do this while (r) != 90

Re # Pop 90 -> (R)
RrEeeEeeeee rEEEE # Push 32 and go to first item -> (r)
REEe # Push input -> (R)
RE RrE # Push 0 on both stacks, (r) prepend 0
rEE # Create loop labeled 0 // makes input minus 32, so the
    # lowercase can be accepted, since of rEEEEeee (below)
  re # Pop 0 -> (r)
  rREEEEEe REEee # Push item of (R) minus 32, then go to next item
  RrE # Push 0 -> (R)
ree # Do while (R) != 0

rere # Pop 0 & 32 -> (r)
rEEEEeee # Remove items from (r) that don't occur in (R)
         # Remove everything from (r) except the unique letters
rE # Push 0 -> (r)
RrEeee # Push reverse pointer pos -> (r)
REEEE # Move pointer to first position -> (R)
RREeeeEEeEe # Push 26 -> (R)
rRrEEEEee reEE # Divide it and output it

```
> 3 votes

# Answer
# Julia 1.0, 34 bytes

```
s->sum('a':'z'.∈lowercase(s))/26

```

Uses the vectorized version of the ∈ operator, checking containment in the string for all characters in the range from a to z. Then sums over the resulting BitArray and divides by total number of possible letters.

Try it online!
> 3 votes

# Answer
# Jelly, 8 bytes

```
ŒuØAe€Æm

```

Try it online!

### Explanation

```
Œu       | Convert to upper case
  ØAe€   | Check whether each capital letter is present, returning a list of 26 0s and 1s
      Æm | Mean

```
> 2 votes

# Answer
# C, 96 bytes

```
float f(char*s){int i=66,l[256]={};for(;*s;)l[1+*s++&~32]=1;for(;i<92;*l+=l[i++]);return*l/26.;}

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-MList::Util=uniq -p`, 24 bytes

```
$_=uniq(lc=~/[a-z]/g)/26

```

Try it online!
> 2 votes

# Answer
# Stax, 9 bytes

```
░║üy$}╙+C

```

Run and debug it
> 2 votes

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

```
s=>~-s.match(/$|([a-z])(?!.*\1)/ig).length/26

```

Try it online!

---

# JavaScript (Node.js), 47 bytes

```
s=>(s.match(/([a-z])(?!.*\1)/ig)||[]).length/26

```

Try it online!
> 2 votes

# Answer
# Swift 5.9, ~~105~~ ~~100~~ 89 bytes

```
let p={Float((65...90).filter(($0+"").uppercased().map(\.asciiValue).contains).count)/26}

```

Using `Float` instead of `Double` saved a byte.
> 2 votes

# Answer
# Japt, 9 bytes

```
;CoU Ê/26

```

Try it

```
;CoU Ê/26     :Implicit input of string U
;C            :Lowercase alphabet
  oU          :Remove the characters not included in U, case insensitive
     Ê        :Length
      /26     :Divide by 26

```
> 1 votes

# Answer
# Python 2, 57 bytes

```
lambda i:len(set(o for o in i.lower()if o.isalpha()))/26.

```

Try it online!

A bit longer than the Python 3 answer from ArBo but posted as a different approach in Python 2 anyway.
> 1 votes

# Answer
# Ruby `-n`, ~~38~~ 34 bytes

-4 bytes from @historcrat!

```
p (?A..?Z).count{|c|~/#{c}/i}/26.0

```

Try it online!
> 1 votes

# Answer
# C, 95 bytes

```
f(char*s){int a[256]={},z;while(*s)a[*s++|32]=1;for(z=97;z<'z';*a+=a[z++]);return(*a*100)/26;}

```

(note: rounds down)

### Alternate decimal-returning version (95 bytes):

```
float f(char*s){int a[256]={},z;while(*s&&a[*s++|32]=1);for(z=97;z<'z';*a+=a[z++]);return*a/26.;}

```

This borrows some from @Steadybox' answer.
> 1 votes

# Answer
# K4, ~~14~~ 13 bytes

**Solution:**

```
avg .Q.a in _

```

**Explanation:**

Rather ~~stolen from~~ *inspired by* Luis Mendo's Octave solution...

```
avg .Q.a in _ / the solution
            _ / lowercase the input
         in   / 'in' function
    .Q.a      / "abcdefghijklmnopqrstuvwxyz"
avg           / average (mean)

```
> 1 votes

# Answer
# Python 3, ~~51~~ 49 bytes

*51 -\> 49 bytes, thanks to alexz02*

```
lambda s:len({*filter(str.isalpha,s.lower())})/26

```

Try it online!
> 1 votes

# Answer
# Stax 1.1.4 online interpreter, 8 bytes, noncompeting

```
äQæ╟r◘Oñ

```

Run and debug it at staxlang.xyz!

### Unpacked (9 bytes) and explanation:

```
Va%26!/vN
Va           Push the lowercase alphabet
  %          Length...?! Shouldn't this always be 26?
   26!       Push 26.0
      /      Divide
       vN    Subtract from one (decrement and negate)

```

That shouldn't work. Looking at it, you would expect an output of 0 always. Heck, it doesn't even take input! There's a bug in the online interpreter, however, which I have exploited for this answer.

Now, I've marked this answer noncompeting for a reason. As far as I can tell, this exploit requires some human interaction to set up. Here's what you gotta do:

* Put your input in the input field
* Unpack
* Insert `v` at the start of the code and `|b` immediately after `Va`
* Run
* Remove the characters you added to the code
* Repack

Now you have an 8-byte program that will give the correct output each time you run it! At least until you change the input field or reload the page.

### What in the seven hells is going on:

```
Va%26!/vN
Va           Push the lowercase alphabet, EXCLUDING characters that existed in the input field in either case any time the vVa|b version was run
  %26!/vN    Everything else works as expected

```

That little bug handles case checking and filtering for free, at the expense of leaving me with the wrong set of letters (wasting two bytes on the `vN`). I think this can be improved rather easily, but I'm at work right now.
> 1 votes

# Answer
# Haskell, 52 bytes

```
f s=sum[1|n<-[0..25],or[elem([c..]!!n)s|c<-"aA"]]/26

```

Try it online!

Avoids case conversion (which base Haskell lacks) and ASCII-code conversions (which are lengthy) in favor of writing `[c..`\] to enumerate characters. For example, `['A'..]` is a very long list that starts with `ABCDEFGHI...`.
> 1 votes

# Answer
# Ohm v2, 7 bytes

```
ÁαA}εÆm

```

Try it online!
> 1 votes

# Answer
# Pyth, 9 bytes

```
cl@rw0G26

```

Try it online!

```
c      26 # Float division by 26 (alternative: replace 26 by lG)
 l        #   Length of
  @       #     intersection of
   r 0    #       lowercase
    w     #         input
      G   #       and the lowercase alphabet

```
> 1 votes

# Answer
# jq -R, 36 + 3 = 39 bytes

```
1/length*([scan("[a-zA-Z]")]|length)

```

The `-R` flag is required, otherwise stdin needs to be a quoted string.
> 1 votes

# Answer
# Emacs Lisp, 91 bytes

```
(lambda(a)(load"cl")(/(count-if(lambda(x)(< ?` x ?z))(remove-duplicates(downcase a)))26.0))

```

Try it online!
> 1 votes

# Answer
# Go, ~~210~~ 196 bytes

```
import(."strings";U"unicode")
func f(s string)float64{s=Map(func(r rune)rune{if!U.IsLetter(r){r=-1};return r},ToLower(s))
m:=make(map[rune]int)
for _,r:=range s{m[r]++}
return float64(len(m))/26.}

```

Attempt This Online!

Returns a float in `[0,1]`.
> 1 votes

# Answer
# C (gcc), 72 bytes

```
i;j;f(char*s){for(i=j=0;i++<26;)j+=index(s,i+64)!=index(s,i+96);j/=.26;}

```

Try it online!

-9B from c--

# x86 opcode, 35 bytes

```
00000180: 575e 31ff ac2c 4172 030f abc7 0441 75f4  W^1..,Ar.....Au.
00000190: c1e7 06f3 0fb8 c750 df04 2458 6a1a de34  .......P..$Xj..4
000001a0: 2458 c3

```

Try it online!
> 1 votes

# Answer
# Vyxal 3, 6 bytes

```
ʀuȦL₂÷

```

Try it Online!

length of unique lowercase letters divided by 26
> 1 votes

# Answer
# Uiua SBCS, 9 bytes

```
÷26⧻◴▽±.⌵

```

Try it!

```
÷26⧻◴▽±.⌵
        ⌵  # uppercase
       .   # duplicate
      ±    # mask of cases (-1 for lower, 1 for upper, 0 for neither)
     ▽     # keep (only the letters)
    ◴      # remove duplicates
   ⧻       # length
÷26        # divided by 26

```
> 1 votes

# Answer
# JavaScript (ES6), ~~61~~ ~~54~~ 51 bytes

```
s=>new Set(s.toLowerCase().match(/[a-z]/g)).size/26

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 39 bytes

```
Length[Alphabet[]⋂ToLowerCase@#]/26.&

```

Try it online!
> 0 votes

# Answer
# MATLAB, 53 bytes

Anonymous function taking a string:

```
@(a)length(unique(upper(a(isstrprop(a,'alpha')))))/26

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), ~~71~~ ~~70~~ 59 bytes

```
Count[Union@ToCharacterCode@ToUpperCase@#,x_/;64<x<91]/26.&

```

Try it online!

Thanks to attinat for suggesting `Union` to replace `DeleteDuplicates`.
> 0 votes

# Answer
# , ~~30~~, 29 bytes

```
ÓÁ
òóãˆ“±òAÝ/26.0|Óá
C="

```

Try it online!
> 0 votes

# Answer
# EXCEL, 55 bytes

Cell `A1` as input. Place in any cell by doing `Ctrl`+`Shift`+`Enter` . +2 bytes if `{}` is included in the count.

```
=SUM(--ISNUMBER(FIND(CHAR(ROW(A65:A91)),UPPER(A1))))/26

```
> 0 votes

# Answer
# Oracle, 199 bytes

```
CREATE FUNCTION f(s LONG)RETURN FLOAT IS
r FLOAT;BEGIN
SELECT COUNT(DISTINCT c)/26 INTO r
FROM(SELECT LOWER(SUBSTR(s,LEVEL,1))c
FROM dual
CONNECT BY LEVEL<=LENGTH(s))WHERE
c>'`'AND'{'>c;RETURN r;END;

```

More readable version:

```
CREATE FUNCTION f(s LONG) RETURN FLOAT IS
    r FLOAT;
  BEGIN
    SELECT COUNT(DISTINCT c) / 26 INTO r
    FROM (
      SELECT
        LOWER(SUBSTR(s, LEVEL, 1)) AS c
      FROM dual
      CONNECT BY LEVEL <= LENGTH(s)
    )
    WHERE c > '`' AND '{' > c;
    RETURN r;
  END;

```

Try it on SQL Fiddle!
> 0 votes

# Answer
# Haskell, 86 Bytes

Still golfable, probably.

```
import Data.Char
import Data.List
((/26).toEnum.length.nub.filter isLower.(toLower<$>))

```

Is there any better way to convert an Int to a Float?
> 0 votes

# Answer
# C# .NET, 158 bytes

```
public class P{public static void Main(string[]z){var i=0;for(int q=65;q<91;q++)if(z[0].ToUpper().IndexOf((char)(q))>-1)i++;System.Console.Write(100D/26*i);}}

```

Try Online
> 0 votes

# Answer
# MathGolf, 8 bytes

```
▄æl!\╧]▓

```

Try it online!

Based on the 05AB1E solution, so be sure to upvote that. I noticed a bug in the "contains" operator, which if resolved would remove the need of the swap.

## Explanation

```
▄          lowercase alphabet as string
 æ         start block of length 4
  l!       push input lowercased
    \      swap top elements
     ╧     pop a, b, a.contains(b)
           loop ends here
      ]    end array / wrap stack in array
       ▓   get average of list

```
> 0 votes

# Answer
# Factor \+ `spelling`, 44 bytes

```
[ >lower ALPHABET within cardinality 26 /f ]

```

Try it online!

* `>lower` Convert the input to lowercase.
* `ALPHABET` Place the lowercase alphabet on the data stack.
* `within` Take from the input only those elements that are in the alphabet.
* `cardinality` Count how many elements are in the resulting set.
* `26 /f` Divide by 26 and force the result to be a float.
> 0 votes

# Answer
# AWK, 72 bytes

```
gsub("[^a-zA-Z]",z)+gsub(z," "){for(;$++a;)b+=!c[tolower($a)]++}$0=b/.26

```

Try it online!

The first bit in this code is a test that's always truthy, so the associated code block will always run no matter what the input string contains. The purpose of the `gsub` calls is to remove all the non-alphabetic characters and then to split the input string into space separated characters. That re-evaluates the positional parameters, making the input a list of individual `a-zA-Z` characters.

```
gsub("[^a-zA-Z]",z)+gsub(z," "){                               }

```

The codeblock can then iterate over each positional parameters to process all the alphabetic characters in the input string.

```
                                for(;$++a;)

```

The body of the loop is one AWK statement that does all the real work. It counts the number of times each unique (lowercase) character is seen. And anytime the current counter `c[...char...]` is `0` it increments the tally of unique characters.

```
                                           b+=!c[tolower($a)]++

```

Once all the characters have been scanned, the final answer is the tally divided by the number of characters in the alphabet divided by 100. Assigning that value to `$0` wipes out all the other positional parameters and prints the percentage by default.

```
                                                                $0=b/.26

```
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
LẠ€Ƈm

```

Try it online!

## Thunno 2, 7 bytes

```
LỊUl26/

```

Try it online!

#### Explanations

```
LẠ€Ƈm  # Implicit input
L      # Lowercase
 Ạ     # Lowercase alphabet
  €    # Single function map:
   Ƈ   #  Contains
    m  # Mean
       # Implicit output

```

```
LỊUl26/  # Implicit input
L        # Lowercase
 Ị       # Only alphabetic
  U      # Uniquify
   l     # Length
    26/  # Divide by 26
         # Implicit output

```
> 0 votes

# Answer
# x86-64 machine code, 47 bytes

Standard x64 System V ABI, signature `long double get_acr(char* str)`. The string is modified by the function, so it cannot be read-only.

```
57 5e 31 c9 ac ff c1 80 66 ff df 84 c0 75 f5 6a 1a df 04 24 5a d9 ee 6a 41 58 57 51 f2 ae 75 04 d9 e8 de c1 59 5f ff c0 ff ca 75 ee de f1 c3

```

Try it online!

## Explanation

```
; long double get_acr(char* str)
; follows x64 SysV ABI
; input RDI: null-delimited writable string (gets modified)
; output ST0: percentage in range [0, 1]
get_acr:
    ; Get string length in rcx and convert characters to uppercase
    push rdi
    pop rsi ; get str reference in rsi
    xor ecx, ecx ; len = 0

__get_acr_convlp:
    lodsb ; get byte into rsi

    ; non-zero char: increment length and handle conversion
    ; if it is zero, we increment, do (effectively) no conversions, and store
    ; back. this +1 in ecx doesn't matter though, since it's okay if we search
    ; for letters in the zero byte later on.
    inc ecx

    ; convert by removing bit for 32 to force lowercase letters uppercase
    ; in other words, and al by ~32 (0b1101 1111, 0xdf).
    and byte [rsi-1], 0xdf

    ; loop back up if al != 0
    test al, al
    jnz __get_acr_convlp

    ; init counter rdx: do 26 times
    ; also get 26 into st1 for division later
    push 26
    fild word [rsp]
    pop rdx

    fldz ; sum starts at 0.0

    ; We only have uppercase letters now to look for
    ; Initial letter: 'A'
    push 65
    pop rax

__get_acr_loop:
    push rdi ; save rdi
    push rcx ; save rcx

    ; rcx times: search for al
    repne scasb ; go until rcx = 0 or found al (zf = 1)

    ; add 1 if zf, do nothing otherwise
    jnz __get_acr_dno

    fld1
    faddp

__get_acr_dno:
    pop rcx ; restore rcx
    pop rdi ; restore rdi

    inc eax ; next letter

    dec edx
    jnz __get_acr_loop ; loop back to top edx times

    ; Divide st0 by st1 and pop to get the fraction to return
    fdivrp st1, st0

    ret

```
> 0 votes

# Answer
# Racket – 115 bytes

```
(~r(*(/(set-count(apply set(filter char-alphabetic?(string->list(string-upcase(read-line))))))26)100)#:precision 2)

```

Try it online!

---

## Explanation

First, we read user input and transform it into upper case. We then turn the string into a list of characters and remove any characters that aren't alphabetic. Once done, we transform the list into a set. A Set is a data structure that can only contain unique values. That's cool because it allows us to simply count the number of elements in the set and calculate the percentage of unique letters that are used. Once all is done, we return the result as a decimal string with the precision of 2.

```
(~r (* (/ (set-count (apply set
                            (filter char-alphabetic?
                                    (string->list (string-upcase (read-line))))))
           26)
       100)
    #:precision 2)

```

Some cool things to note that I just found out is that Racket uses fractions by default to calculate large arbitrary precision. If you were to remove `~r` you'd see a fraction that looks like `x/y`.
> 0 votes

# Answer
# C (gcc), 72 bytes

*Outputs via exit code*

```
r;a[];main(c){return~c?main(getchar(r+=a[c&=95]++<c/65-c/91)):r/.26+.5;}

```

Try it online!

## Commented

```
r;                // int r is zero-initialized
a[];              // same for int array a[]; it has size 1 (we'll pretend it's 96)
main(c){          // function main returns int and takes an int `c`
 return
  ~c?             // if c != -1:
   main(          //  call main() recursively with
    getchar(      //   next character from stdin or EOF(-1) (ignores argument)
     r+=          //    add the following to r:
      a[c&=95]++  //     uppercase `c`, increment the value at it's index in a[]
       <c/65-c/91 //     if (old value of a[c]) < (c/'A' - c/'[') add 1, else 0
    )             //   end call to getchar()
   )              //  end call to main()
  :               // else (we're at the end):
   r/.26+.5;      //  return the accumulated result as a % of 26, rounded
}                 // end main() function

```

## Explanation

Alphabetic characters are in the ranges \\$1000001\_2..1011010\_2\\$ (uppercase) and \\$1100001\_2..1111010\_2\\$ (lowercase), and \\$95\_{10} = 1011111\_2\\$, so `c &= 95` makes characters uppercase and changes symbols in some way we don't care as they will not land in the same range.

For \\$0 \le c \le 95\\$ the equation \\$\frac{c}{65} - \frac{c}{91}\\$ returns 1 if \\$65 \le c \le 90\\$ (c is uppercase) and 0 otherwise.

So `a[c &= 95]++ < c/65 - c/91` checks that `isapha(c)` and that this is the first time we see `c` in uppercase or lowercase (by incrementing the value we make sure subsequent occurrences of `c` will not match the expression).
> 0 votes

# Answer
# Scala 3, 50 bytes

```
_.filter(_.isLetter).toLowerCase.distinct.size/26f

```

Attempt This Online!
> 0 votes

---
Tags: code-golf
---


title: Summing the Digits of a Number

text:
# Question
Title: Summing the Digits of a Number
## Challenge

* Given a non-negative integer, find the sum of its digits.

### Rules

* Your program must take a non-negative integer as input.
* Your program should output the sum of the digits of the input integer.
* Your program should be able to handle inputs up to 10^100.

### Examples

* If the input is 123, the output should be 6 (1 + 2 + 3).
* If the input is 888, the output should be 24 (8 + 8 + 8).
* If the input is 1024, the output should be 7 (1 + 0 + 2 + 4).
* If the input is 3141592653589793238462643383279502884197169399375105820974944592, the output should be 315.

### Format

* Your program should take input from standard input (stdin) and output the result to standard output (stdout).
* Your program should be runnable in a Unix-like environment.

### Test cases

Input:

```
123

```

Output:

```
6

```

Input:

```
888

```

Output:

```
24

```

Input:

```
1024

```

Output:

```
7

```

Input:

```
3141592653589793238462643383279502884197169399375105820974944592

```

Output:

```
315

```

### Scoring

* This is a code-golf challenge, so the shortest code (in bytes) wins.

# Answer
# Trilangle, 15 bytes

```
'0.<"@(+>i(^-<!

```

Test it on the online interpreter!

---

Roughly equivalent to this C code:

```
#include <stdio.h>

int main() {
    int total = 0;
    int i;
    while ((i = getchar()) != EOF) {
        total += i - '0';
    }
    printf("%d\n", total);
}

```

Control flow is kinda weird so it actually calls `getchar()` a couple times even after EOF is reached.

---

Unfolds to this:

```
    '
   0 .
  < " @
 ( + > i
( ^ - < !

```

With code paths highlighted:

Control flow starts at the north corner heading southwest (on the red path). Instructions are executed as follows:

* `'0`: Push a 0 to the stack
* `<`: Change the direction of control flow

(Walk off the edge of the grid and wrap around)
* `i`: Get a single character from stdin (-1 on EOF) and push it to the stack
* `>`: Branch on the sign of the top of the stack

If the value is positive (any character that isn't EOF), the IP takes the green path:

* `"0`: Push the value of the character '0' (i.e. 48) to the stack
* `-`: Subtract the two values on top of the stack
* `+`: Add the two values on top of the stack
* `<`: Redirect control flow, merging with the red path

Once EOF is read, the IP takes the blue path, printing out the stored value... eventually. As you can see from the image it takes the scenic route.

* `-`: Subtract the two values on top of the stack. There's now only one value, `total - -1` (i.e. `total + 1`).
* `i`: Attempt to read another character from stdin (always sees EOF)
* `<`: Redirect control flow
* `-` Subtract the two values on top of the stack. Again, there's now only one value: `total + 2`.
* `^`: Redirect control flow
* `((`: Decrement the top of the stack twice, undoing the effects of `i-i-`.
* `!`: Print the value on top of the stack as a decimal integer
* `i`: Another attempt to read stdin, though at this point the values on the stack don't matter
* `@`: End program.
> 11 votes

# Answer
# C (gcc), 30 bytes

```
f(int*s){s=*s?*s-48+f(s+1):0;}

```

Try it online!

# C (clang), 31 bytes

```
f(*s){return*s?*s-48+f(s+1):0;}

```

Try it online!

# C89, 35 bytes

```
f(char*s){return*s?*s-48+f(s+1):0;}

```

Try it online!
> 9 votes

# Answer
# Vyxal `s`, 0 bytes

```

```

Try it Online!

That's right. No bytes needed.

Alternatively

## Vyxal, 1 byte

Try it Online!

Just the built-in that works on numbers
> 8 votes

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

```
n=>eval([...n].join`+`)

```

Try it online!

Takes input as a string

## JavaScript (Node.js), 26 bytes

```
n=>eval([...""+n].join`+`)

```

Try it online!

Takes input as a number, doesn't work if the number is too large for JavaScript to stringify naturally
> 7 votes

# Answer
# Python, 24 bytes

```
lambda n:sum(map(int,n))

```

Attempt This Online!

Input as a string.

## Python, 29 bytes

```
lambda n:sum(map(int,str(n)))

```

Attempt This Online!

Input as an integer.
> 7 votes

# Answer
> NOTE: Since many/most of the answers seem to ignore the requirement in the question that the input must be taken from `stdin` and the output must be sent to `stdout`, I suppose it is reasonable if I do so, too. I think that's a silly and arbitrary requirement, because it makes many languages non-competitive. The standard on Code Golf is to allow functions, and to allow functions taking input via arguments and outputting via their return value(s), so this is what I will follow.

# x86-64 Assembly, standard Linux calling convention, 17 bytes

```
64 31 C0 0F B6 0F E3 09 48 FF C7 8D 44 01 D0 EB F2 C3

```

**Try it online!**

This is a minor, iterative improvement on qwr's answer, which is 18 bytes.

It saves 1 byte by using the relatively-obscure `JECXZ` instruction (actually `JRCXZ`, since this is 64-bit mode), which jumps if the value of the `rcx` register is zero.

It also improves on qwr's original (arguably fixes a bug?) in that it supports the case where the input is an empty string, returning a sum of zero. (To be fair, the challenge doesn't specify whether it is required to handle this, so maybe it cannot be termed a "bug", and, in fact, my next attempt will have this same "bug", so I can hardly ding qwr for taking advantage of it, too!)

```
SumDigits:
  31 C0         xor    eax, eax
Loop:
  0F B6 0F      movzx  ecx, BYTE PTR [rdi]
  E3 09         jrcxz  End
  48 FF C7      inc    rdi
  8D 44 01 D0   lea    eax, [rcx + rax - '0']
  EB F2         jmp    Loop
End:
  C3            ret    ; result is in eax

```

# x86-64 Assembly, fully custom calling convention, 14 bytes

```
64 31 C0 31 D2 AC 8D 54 02 D0 38 26 75 F7 C3

```

**Try it online!**

This is a variation on the same theme (it still takes the input as a pointer to the beginning of a NUL-terminated ASCII string), but it pulls out all the stops to really optimize for size:

* It uses the ultra-compact x86 string instructions. In this case, `lods`, which loads a byte into `al` from the address in `rsi`, and also increments `rsi` to point to the next byte, using a single-byte encoding.

+ In order to know whether to increment or decrement the source pointer, the `rsi` instruction implicitly depends on the direction flag (`DF`). Normally, you'd need to explicitly clear that flag with the `cld` instruction, but, in this case, since we're running on a \*nix-like operating system, per the challenge, we can assume it is already clear. (Also, when you're defining a custom calling convention, the state of the flags can be part of that; see below.)
* It uses a custom calling convention so that we can (A) take the input string in the `rsi` register, which is what the `lods` instruction expects, saving us from having to copy it from one register to another, and (B) build the result in a custom register (`edx`), freeing up `eax` to use as a scratch register (because this is what the `lods` instruction uses as an implicit destination operand).
* The `lods` instruction is only loading a single byte, so it only modified the low-order byte of the `eax` register (`al`). But the `lea` instruction that we use to perform multiple arithmetic operations in a single instruction only works on the full 64-bit register, so we need to make sure that the high values are clear. We could do this with an explicit `movzx` after the `lods` instruction, but that would consume a lot of bytes. So, instead, we do it once, outside of the loop, with a single `xor` instruction. This clears the entire `rax` register, which works because we only ever touch the low-order byte (`al`).

+ Another neat trick falls out of this: because we don't touch the high-order byte (`ah`), it's guaranteed to be zero through all iterations of our loop, so we can compare (`cmp`) the source pointer (string) to `ah` instead of comparing it to a literal 0, which saves us one byte in the encoding.

```
SumDigits:
  --          ; cld                           ; can assume DF is always clear on Linux)
  31 C0         xor    eax, eax               ; eax  = 0 (al = 0, ah = 0)
  31 D2         xor    edx, edx               ; edx  = 0 (holds result)
Loop:
  AC            lods                          ; al   = BYTE PTR [rsi]
  8D 54 02 D0   lea    edx, [rdx + rax - '0'] ; edx += (eax - '0')
  38 26         cmp    BYTE PTR [rsi], ah     ; is BYTE PTR [rsi] == ah (which is 0)?
  75 F7         jne    Loop                   ; loop back if not equal (non-zero)
  C3            ret                           ; result is in edx

```

The custom calling convention is a pretty major "cheat" here, but it's not unusual in the "real world" to use a custom calling convention when writing code in assembly. If you're going to call it from C, you need to take steps to match the standard C calling convention, but who says we're calling it from C?! We don't need no stinkin' C! :-)
> 7 votes

# Answer
# MATL, 3 bytes

```
!Us

```

Try it out at MATL Online

**Explanation**

```
      % Implicitly read in first input, a 1 x N string
!     % Flip it so that it is N x 1 character array (one character per row)
U     % Convert each row from a string to a number
s     % Sum the resulting N x 1 numeric array
      % Implicitly display the result

```
> 6 votes

# Answer
# Vyxal 3.0.0-beta.1, 9 bytes

```
'%%O48-/+

```

Try it online! (link is to literate version)

Unlike my v2 answer, there is no sum flag, sum built-in, cast to int or cast to string built in in this version of vyxal (because it's a beta release - what do you expect?).

## Explained

```
'%%O48-/+
'%%        ## Format the input as a string
   O48-    ## get the ordinal value of each character and subtract 48 to get the digit value
       /+  ## fold by addition

```
> 5 votes

# Answer
# 05AB1E, 2 bytes

```
SO

```

Try it online!
> 5 votes

# Answer
# Proton, 14 bytes

```
digits(10)+sum

```

Try it online!

`digits(x, y)` converts `y` into digits in base `x` and `sum` performs sum. Therefore, `digits(10)` is a partial function that becomes `y => digits(10, y)` and `+ sum` chains it with `sum` so an input will be called with `digits(10)(...)` first, and then the result is called with `sum(...)`.

This is 6 bytes shorter than the straightforward `x=>sum(digits(10,x))`.
> 5 votes

# Answer
# Excel, ~~32~~ ~~31~~ 30 bytes

```
=SUM(0+(0&MID(A1,ROW(A:A),1)))

```

Input in cell `A1`.

*Thanks to **user117069** and **EngineerToast** for the two bytes saved*.
> 5 votes

# Answer
# C (gcc), ~~29~~ ~~27~~ 25 bytes

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

```

Try it online!

*-2 bytes thanks to Giuseppe*

*-2 bytes thanks to c--*

Takes input as `int`.

C's `int` isn't large enough for the last test case.

~~The bracket around the ternary is truly awful. Wish I could remove that.~~ Thanks c-- again.

# C (gcc), ~~38~~ 36 bytes (no recursion).

```
a;f(i){for(a=0;i;i/=10)a+=i%10;a=a;}

```

Try it online!

*-2 bytes thanks to Giuseppe*

Takes input as `int`.

C's `int` isn't large enough for the last test case.

# C (gcc), 56 bytes (no recursion) (outgolfed by c-- using recursion).

```
a,n;f(char*s){for(a=0,n=strlen(s);n--;++s)a+=*s-48;a=a;}

```

Takes input as string

Try it online!
> 5 votes

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

```
S

```

Try it online!

Builtin
> 4 votes

# Answer
# Pari/GP, 9 bytes

```
sumdigits

```

Try it online!
> 4 votes

# Answer
# Typescript Type System + `hotscript`, ~~92~~ 87 bytes

```
import{Pipe,S,T}from"hotscript"
type _<U>=Pipe<U,[S.Split<"">,T.Map<S.ToNumber>,T.Sum]>

```

I just found out about this library that basically turns the Typescript Type System into a full-on functional programming language and it's amazing

Saved 5 bytes by taking input as a string instead of a number

TS Playground Link

```
import{Pipe,S,T}from"hotscript"
type _<U>=           // define hotscript lambda with string argument U
Pipe<U,[             // pipe U to:
  S.Split<"">,       //   split on "" (= character list)
  T.Map<S.ToNumber>, //   map each letter to number
  T.Sum              //   sum
]>                   // end pipe

```
> 4 votes

# Answer
# Retina 0.8.2, 6 bytes

```
.
$*
1

```

Try it online! Link includes test cases. Explanation:

```
.
$*

```

Convert each digit to unary.

```
1

```

Convert the sum to decimal.
> 4 votes

# Answer
# Julia, 12 10 bytes

Tacit Julia strikes again!

```
sum∘digits

```

Explanation:

```
digits: take an integer and return a vector of its digits in base 10 (default)
∘: function composition
sum: sum a collection

```

Try it online!

-2 thanks to MarcMush
> 4 votes

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

```
dS

```

Attempt This Online!

```
d    digits of input
 S   calculate sum

```
> 3 votes

# Answer
# Perl 5 -p, 19 bytes

```
s/./$s+=$&/ge;$_=$s

```

Try it online!
> 3 votes

# Answer
# x86-64 Linux assembly, 18 bytes

Lazy C translation. Follows calling convention of System V AMD64 ABI: input null-terminated string in rdi, output in rax.

```
sum_digits:
        xor     eax, eax            ; sum = 0
L:
        movsx   edx, BYTE [rdi]     ; c = *str
        inc     rdi                 ; ++str
        lea     eax, [rax-48+rdx]   ; sum += c - '0'
        cmp     BYTE [rdi], 0
        jne     L                   ; while (*str)
        ret

```

Objdump:

```
0000000000401110 <sum_digits>:
  401110:   31 c0                   xor    eax,eax

0000000000401112 <L>:
  401112:   0f be 17                movsx  edx,BYTE PTR [rdi]
  401115:   48 ff c7                inc    rdi
  401118:   8d 44 10 d0             lea    eax,[rax+rdx*1-0x30]
  40111c:   80 3f 00                cmp    BYTE PTR [rdi],0x0
  40111f:   75 f1                   jne    401112 <L>
  401121:   c3                      ret

```
> 3 votes

# Answer
# Ruby, 17 bytes

```
->x{x.digits.sum}

```

This defines an anonymous function that accepts a single input (a number), breaks it up into an array of digits, then sums this array and returns the result
> 3 votes

# Answer
# Rust, ~~54~~ ~~47~~ 30 bytes

```
|n|n.map(|b|b as u64-48).sum()

```

A function that takes a `std::str::Bytes` and returns a `u64`. For the purpose of this challenge, I consider `std::str::Bytes` to be an iterator of ASCII-characters, which meets our general criteria for a string.

Previous versions:

```
|mut n|{let mut s=0;while n>0{s+=n%10;n/=10;}s}

```

```
|n|n.to_string().bytes().map(|d|u64::from(d)-48).sum()

```
> 3 votes

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

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

```

Try it online!

---

# JavaScript (Node.js), 21 bytes

```
f=n=>n&&n*9%9-f(n/~9)

```

Try it online!

It is shorter, but with floating point errors...
> 3 votes

# Answer
# Raku, ~~19~~ 16 bytes

```
say [+] get.comb

```

Try it online!

`get()`: gets a single line from stdin (parens not required)

~~\`.univals()\`: maps a string of numerical unicode chars to a list of their values. I'm just using it in place of \`.split("")\`, which would be 2 bytes longer.~~

`.comb`: splits out to list of characters (thanks @Mark Reed)

`[+]`: reduces the list by addition.

`say`: writes to stdout
> 3 votes

# Answer
# Befunge-98 (PyFunge), 9 7 6 bytes

```
~c%+#q

```

Try it online!

Having read through the Default I/O thread, it seems my "fun extra" answer is actually valid as a submission. Note that since the output in this version is an exit code, POSIX-compatible systems (including TIO; please let me know if there's a better site for this) will only care about the least significant byte and as such display the result mod 256 (as per the Funge-98 spec).

## Explanation

`~`: Read next character.

`c%`: Push 12, then take input character mod 12. This gives the number represented. Suggested by Jo King (previous iteration subtracted 48 from the number with `'0-`).

`+`: Add that to the current total (initially implicitly 0).

`#q`: Do nothing if control flow is LTR, quit and return top of stack as exit code if RTL.

Due to wrapping, this is a loop. At EOF, `~` reflects, thus executing the last portion RTL.

## Previous version

```
~'0-+2j@.

```

Try it online!

### Explanation

As above, but replace `#q` with:

`2j@.`: Jumps over the exit and print if control flow is LTR, prints top of stack as an integer then exits if RTL (push 2, jump, exit, print).
> 3 votes

# Answer
# APL, 5 bytes

```
+/⍎¨⍞

```

Explanation:

* reads standard input as a character vector
* `⍎¨` converts each digit to its numeric value
* `+/` computes the sum

Try it online!
> 3 votes

# Answer
## Pascal, 114 bytes

This is a full `program` according to ISO standard 7185 “Standard Pascal”. The built-in data type `integer` comprises (at least) all integral values in the range `−maxInt..maxInt`. The value of `maxInt` is *implementation-defined*. In order to successfully test values up to and including one googol you will need a processor (this refers to the specific combination of machine, compiler, OS, etc.) defining `maxInt` ≥ 10100.

```
program p(input,output);var x,y:integer;begin y:=0;read(x);repeat y:=y+x mod 10;x:=x div 10 until x=0;write(y)end.

```

Ungolfed:

```
program digitSum(input, output);
    var
        x, digitSum: integer;
    begin
        digitSum := 0;
        read(x);

        repeat
        begin
            digitSum := digitSum + x mod 10;
            x := x div 10;
        end
        until x = 0;

        write(digitSum);
    end.

```

Because in Pascal `mod` is defined to always yield a non-negative result, `digitSum` works incorrectly for negative inputs. Injecting an `x := abs(x);` prior the loop will resolve this issue.

---

Another method is of course to *process characters*. In Pascal it is guaranteed that the characters `'0'` through `'9'` are in ascending order and consecutive, thus `ord('9') − ord('0')` is guaranteed to yield the `integer` value `9`.

```
program p(input,output);var x:integer;begin x:=0;while not EOF do begin x:=x+ord(input^)-ord('0');get(input)end;write(x)end.

```

Input must not be followed by a newline, or replace the `EOF` by `EOLn`. This `program` is ≥ 124 bytes
> 3 votes

# Answer
# bc, 35 bytes

```
for(;i<length(a);i++)b+=a/10^i%10;b

```

Try it online!

Using the default `scale=0` i.e. no decimals, divide by `1,10,100,...`  successively (`a/10^i`), and `%10` to add only the last digit to `b`. When the `for` loop finishes, print the sum. `;b`
> 3 votes

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

```
+/10\

```

Try it online!
> 3 votes

# Answer
# Javascript, 42 bytes

This new and improved version supports BigInt, as well as numbers and strings. It uses tsh's idea, but it first changes the type and uses the ES10 BigInt. (It also happens to be the shortest I could come up with!)

```
a=n=>eval("x=BigInt(n);x&&x%10n+a(x/10n)")
```

I also tried playing around and created these functions:

```
// BigInt/String/Number
b=n=>eval("l=0;(n+[]).split('').forEach(t=>l+=+t);l")
// String only
c=n=>eval("l=0;n.split('').forEach(t=>l+=+t);l")
// BigInt only
d=n=>n&&n%10n+d(n/10n)
// String/Number
e=n=>+n&&+n%10+e(+n/10|0)
```
> 3 votes

# Answer
# PowerShell, 39 bytes

```
param([string]$i)($i|% t*y)-join"+"|iex

```

Try it online!
> 3 votes

# Answer
# Leaf-Lang, 95 bytes

`macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print`

## Explaination

Leaf Lang is a lang I made in my free time in college. It is a stack-based programming language. It can be hard to understand, so I wrote a step-by-step golf of my solution.

### The readable solution

```
"" input splitString # split input into array of strings
0 : sum              # sum = 0
"" = 0 =             # loop condition
while
        pop pop pop pop      # clean stack of condition
        toNumber sum + : sum # sum = sum + toNumber
        "" = 0 =             # loop condition
stop

pop pop pop pop # clean stack of condition
pop             # clean stack of stop condition

sum # add sum to stack
print

```

### Compressed readable solution, 109 bytes

`""input splitString 0:sum""=0=while pop pop pop pop toNumber sum+:sum""=0=stop pop pop pop pop pop sum print`

### Macro optimization #1, 98 bytes

`macro p pop end""input splitString 0:s""=0=while p p p p toNumber s+:s""=0=stop p p p p p s print`

This uses a macro to shorten the long chains of `pop` calls.

### Macro optimization #2, 96 bytes

`macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p pop s print`

### The final golf code, 95 bytes

`macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print`

The final code abuses my parser to push a `1` to the stack then call the `p` macro to essentially make a single `pop` call.
> 3 votes

# Answer
# Zsh, 31 bytes

```
for i (${(s::)1})((n+=i));<<<$n

```

Try it online!
> 3 votes

# Answer
# Perl 5 `-F -E`, 18 bytes

```
$s+=$_ for@F;say$s

```

Try it online!
> 3 votes

# Answer
# Japt `-x`, 1 byte

```
ì

```

Try it

`ì` gets the digits of the number, the `-x` flag sums the resulting array
> 2 votes

# Answer
# Arturo, 15 bytes

```
$=>[∑digits&]

```

Try it

Even though the question says input and output must be via standard IO, the author of the question said functions are allowed in the comments. So this is a function.
> 2 votes

# Answer
# Charcoal, 3 bytes

```
ＩΣＮ

```

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

```
  Ｎ Input number
 Σ  Sum of digits
Ｉ   Cast to string
    Implicitly print

```
> 2 votes

# Answer
# Standard ML, 43 bytes

```
(foldl op+ 0)o map(fn x=>ord x-48)o explode

```

Lack of sum function strikes again
> 2 votes

# Answer
# Jelly, 2 bytes

```
DS

```

Try it online!

```
D    digits
 S   sum

```
> 2 votes

# Answer
# Pip, 3 bytes

```
$+a

```

Attempt This Online!

```
$+    sum of
      (the digits of)
  a   the input

```
> 2 votes

# Answer
# Hebigo, 25 bytes

```
print:sum:map: int input:

```

(It compiles to the following Python.)

```
print(
  sum(
    map(
      int,
      input())))

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
Total@IntegerDigits

```

Try it online!

```
Total@IntegerDigits@3141592653589793238462643383279502884197169399375105820974944592

```

315
> 2 votes

# Answer
# PowerShell Core, 31 bytes

```
%{$s=0;$_|% *ay|%{$s+="$_"};$s}

```

Input comes from the pipeline

Try it online!

```
%{$s=0;$_|% *ay|%{$s+="$_"};$s}
%{                            } # % is an alias for the cmdlet ForEach-Object; input (the string containing the number) comes from the pipeline and will be in $_
  $s=0;                         # initialize the final sum
       $_|% *ay                 # takes the input string and passes it to "ForEach-Object -MemberName ToCharArray": turns the string into an array of characters. This is shorter than a cast using [char[]]$_
               |%{$s+="$_"};    # pass the single characters to yet another ForEach-Object which sums up the total. The current character in $_ must be turned into a single-char string by wrapping it in double quotes;
                                # without that, PS would add up the character's byte code since the left operand (the sum) is an integer.
                            $s  # output the sum

```
> 2 votes

# Answer
# MathGolf, 1 byte

```
Σ

```

Try it online.

**Explanation:**

```
Σ  # Sum the digits of the (implicit) input-integer
   # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# Brain-Flak, 150 bytes

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

```

Not sure if this counts, because it exceeds TIO's 60s time limit for the `3141592653589793238462643383279502884197169399375105820974944592` test case, as its' time complexity is linear. Theoretically, given enough time, it should output the right answer. This answer is extremely similar in format to my answer here.

```
{                                                                               #  loop while top of left stack is not 0
(({})<><((()()()()()){})>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}{})<>    #  add the result of modulo 10 of the top value of the left stack to the top value on the right stack
({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)          #  integer division by 10 on left stack
}                                                                               #  end loop
<>                                                                              #  switch to right stack
                                                                                #  implicit output of active (right) stack

```

Try it online!
> 2 votes

# Answer
# Brachylog, 2 bytes

```
ẹ+

```

Try it online!

### Explanation

is a pretty disgusting built-in for a declarative logic language, but it’s useful. A "better" alternative would be `∋ᶠ` (find all elements) but it’s longer.

```
ẹ     Split into a list of elements
 +    Sum

```
> 2 votes

# Answer
# APL, 9 bytes (?)

```
sd←+/⊥⍣¯1

```

Some characters take probably more than 1 byte, but I am not sure how many...
> 2 votes

# Answer
# Groovy, 37 bytes

```
def c={("$it"as List).sum{it as int}}

```

Try it online!
> 2 votes

# Answer
# KamilaLisp v0.2, 15 (APL SBCS)

```
$(⌿.← +)∘:⊙⍫∘⍫∧

```

Equivalent to `$(foldl1 +)@:parse-number@str:explode`.
> 2 votes

# Answer
# Scala, 23 bytes

Try it online!

```
x=>x.map(_.asDigit).sum

```
> 2 votes

# Answer
KAP, 7 characters, 11 bytes:

```
+/@0-⍨⍕

```

Try it online.

It appears that one needs bigint support to properly answer this question. If strings are allowed then the last character can be removed from the answer.
> 2 votes

# Answer
# Lua, 40 bytes

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

```

Try it online!
> 2 votes

# Answer
# Nibbles, 2.5 bytes

```
+`@10

```

Attempt This Online!

## Explained

```
+`@10
+      # Sum of
 `@    # input converted to
   10  # base 10 (basically, list of digits)

```
> 2 votes

# Answer
# Rockstar, ~~75~~ ~~65~~ 56 bytes

```
listen to N
cut N
X's 0
while N
let X be+roll N-0

say X

```

Try it here (Code will need to be pasted in)

```
listen to N     :Read input string into variable N
cut N           :Split to an array
X's 0           :Initialise X as 0
while N         :While N is not empty
let X be+       :  Increment X by
  roll N        :    Pop the first element from N
  -0            :    Subtract an 0 to cast it to an integer
                :End while loop
say X           :Output X

```
> 2 votes

# Answer
# Shasta v0.0.11, 27 bytes

```
{(eval(join(split$"")"+"))}

```

`{...}` Function of argument $

`(eval ...)` Evaluate as JavaScript

`(join ... "+")` Join on "+"

`(split $ "")` Characters of the input string

Alternative 27 bytes:

```
{(sum(map(split$"")number)}

```

The sum of mapping each character of the input string to number.

Online interpreter will be set up very soon; for now, you can test this by following instructions from the README on GitHub.
> 2 votes

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

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

```

Attempt This Online!

* `>dec` Convert the input to a string
* `48 v-n` Subtract 48 from each code point
* `Σ` Sum
> 1 votes

# Answer
# Ly, 3 bytes

```
S&+

```

Try it online!

Breaks STDIN into digits and pushes onto the stack, then uses `&+` to sum them. Prints the stack as a number be default when the code exits.
> 1 votes

# Answer
# GolfScript, 11 bytes

```
`1/{~}%{+}*

```

Try it online!

A function which takes a single integer as input. Link includes test cases.

# Explanation

```
`1/{~}%{+}* # whole function
`           # convert the input into a string
  /         # split into groups of size
 1          # 1
   { }%     # for each value in the split groups...
    ~       # eval it
       {+}* # sum this `eval`ed array

```
> 1 votes

# Answer
# Pyth, 4 bytes

```
ssMz

```

Try it online!

Alternatively there's sjQT or just ssM if we're allowed to have quotes around the input.
> 1 votes

# Answer
# , 13 bytes

```
[: +/ 48 -~ a. I. ]

```
> 1 votes

# Answer
I saw this and just had to give it a go with Java. I mean, I'm *not* going to win, but it's in good fun, right? Using loops, assuming that we can have multiple inputs, including 0:

```
class D{public static void main(String[]a){int s=0;for(String t:a)for(char c:t.toCharArray())s+=c-48;System.out.println(s);}}

```

That gives 125 bytes, but if we assume some assumptions, we can surely get it lower. If we assume one and only input, we don't have to loop, so we can shorten it down further. But if we also stream, we get:

```
class D{public static void main(String[]a){System.out.println(a[0].chars().map(i->i-48).sum());}}

```

Which clocks in at 97 bytes.

That's not too bad for Java.
> 1 votes

# Answer
# Google Sheets, 44 bytes

```
=QUERY(,"select "&REGEXREPLACE(A1,"\B","+"))

```
> 1 votes

# Answer
# vemf, 6 bytes

```
ª-:48+

```

Input is a number literal.

try it online, uses `:314159` as example

## Explanation

```
ª      ' represent as a codepage string
 -:48  ' subtract 48 from each codepoint
       ' (so the codepoints are all now 0-9)
     + ' sum list

```
> 1 votes

# Answer
# Java 8 (OpenJDK 8), 31 bytes

Very classic answer in Java

```
s->s.chars().map(e->e-48).sum()

```

Try it online!
> 1 votes

# Answer
# Python, 42 Bytes

```
lambda x:sum(int(y) for y in list(str(x)))

```

Try this code online
> 1 votes

# Answer
# Python 3, 33 (35!) 30 bytes

-5 thanks to c--. No strings

```
f=lambda n:n and n%10+f(n//10)

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 18 bytes

```
s=>s.Sum(a=>a-48);

```

Try it online!
> 1 votes

# Answer
# Bash & coreutils, 21 bytes

```
fold -1|paste -sd+|bc

```

Try it online!
> 1 votes

# Answer
# Swift, 51 bytes

```
let s={String($0+0).reduce(0){Int("\($1)")!+$0}}

```
> 1 votes

# Answer
# Java, 27 bytes

```
for(s=0;n>0;s+=n%10,n/=10);

```

Input as Integer (n)
> 1 votes

# Answer
# Thunno 2 `S`, 0 bytes

Attempt This Online!

No bytes, that's right.

## Thunno 2, 1 byte

```
S

```

Attempt This Online!

Alternatively, have a built-in.
> 0 votes

# Answer
# Perl 5 `-MList::Util=sum -pF`, 8 bytes

```
$_=sum@F

```

Try it online!
> 0 votes

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


title: Parse RNA into codons

text:
# Question
Title: Parse RNA into codons
## Introduction

RNA is the less famous cousin of DNA. Its main purpose is to control the production of proteins in cells through a process called translation. In this challenge, your task is to implement a part of this process where the RNA is split into *codons*.

This challenge is thematically related, but concentrates on another part of the translation process.

## Codons

We will think of RNA as a long string over the alphabet of base pairs, `AUCG`. In translation, RNA is split into non-overlapping chunks of three base pairs, called codons. The process begins at a *start codon*, `AUG`, and ends at a *stop codon*, one of `UAA`, `UAG` or `UGA`. Each codon (except the stop codons) corresponds to an amino acid, and the resulting string of amino acids forms the protein.

## Input

Your input is a non-empty string of RNA.

## Output

Your output is the list of codons in which the RNA is split, in any reasonable format. In this simplified model, the process begins at the **leftmost** start codon `AUG`, which is included in the output. It ends when a stop codon is encountered, or when we run out of RNA. If the input contains no start codon, the output shall be an empty list.

## Examples

Consider the input sequence

```
ACAUGGAUGGACUGUAACCCCAUGC

```

The parsing begins at the leftmost occurrence of `AUG`, at index 2. It continues as follows:

```
AC AUG GAU GGA CUG UAA CCCCAUGC
   *   ^   ^   ^   +

```

The codon marked with `*` is the start codon, and those marked with `^` are also part of the output. The stop codon is marked with `+`. The correct output is

```
AUG,GAU,GGA,CUG

```

For the shorter input

```
ACAUGGAUGGACUGU

```

the process goes

```
AC AUG GAU GGA CUG U
   *   ^   ^   ^

```

This time, a stop codon is not encountered, so the process stops when we run out of base pairs. The output is the same as above.

## Rules and scoring

You can write a full program of a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

```
GGUACGGAUU ->
GGCGAAAUCGAUGCC -> AUG
ACAUGGAUGGACUGU -> AUG,GAU,GGA,CUG
AUGACGUGAUGCUUGA -> AUG,ACG
UGGUUAGAAUAAUGAGCUAG -> AUG,AGC
ACAUGGAUGGACUGUAACCCCAUGC -> AUG,GAU,GGA,CUG
CUAAGAUGGCAUGAGUAAUGAAUGGAG -> AUG,GCA
AAUGGUUUAAUAAAUGUGAUAUGAUGAUA -> AUG,GUU
UGUCACCAUGUAAGGCAUGCCCAAAAUCAG -> AUG
UAUAGAUGGUGAUGAUGCCAUGAGAUGCAUGUUAAU -> AUG,GUG,AUG,AUG,CCA
AUGCUUAUGAAUGGCAUGUACUAAUAGACUCACUUAAGCGGUGAUGAA -> AUG,CUU,AUG,AAU,GGC,AUG,UAC
UGAUAGAUGUAUGGAUGGGAUGCUCAUAGCUAUAAAUGUUAAAGUUAGUCUAAUGAUGAGUAGCCGAUGGCCUAUGAUGCUGAC -> AUG,UAU,GGA,UGG,GAU,GCU,CAU,AGC,UAU,AAA,UGU

```

# Answer
## Retina, ~~39~~ ~~38~~ ~~32~~ 30 bytes

```
M!`AUG|\B\G...
U(AA|AG|GA)\D*

```

The trailing linefeed is significant.

Output as a linefeed-separated list.

Try it online.

### Explanation

```
M!`AUG|\B\G...

```

This is match stage which turns the input into a linefeed-separated list of all matches (due to the `!`). The regex itself matches every codon starting from the first `AUG`. We achieve this with two separate options. `AUG` matches unconditionally, so that it can start the list of matches. The second match can be any codon (`...` matches any three characters), but the `\G` is a special anchor which ensures that this can only match right after another match. The only problem is that `\G` also matches at the beginning of the string, which we don't want. Since the input consists only of word characters, we use `\B` (any position that is not a word boundary) to ensure that this match is not used at the beginning of the input.

```
U(AA|AG|GA)\D*

```

This finds the first stop codon, matched as `U(AA|AG|GA)` as well as everything after it and removes it from the string. Since the first stage split the codons into separate lines, we know that this match is properly aligned with the start codon. We use `\D` (non-digits) to match any character, since `.` wouldn't go past the linefeeds, and the input won't contain digits.
> 11 votes

# Answer
## Haskell, ~~115~~ 112 bytes

```
import Data.Lists
fst.break(\e->elem e["UAA","UAG","UGA"]||length e<3).chunksOf 3.snd.spanList((/="AUG").take 3)

```

Usage example:

```
*Main> ( fst.break(\e->elem e["UAA","UAG","UGA"]||length e<3).chunksOf 3.snd.spanList((/="AUG").take 3) ) "AUGCUUAUGAAUGGCAUGUACUAAUAGACUCACUUAAGCGGUGAUGAA"
["AUG","CUU","AUG","AAU","GGC","AUG","UAC"]

```

How it works:

```
                spanList((/="AUG").take 3)  -- split input at the first "AUG"
             snd                            -- take 2nd part ("AUG" + rest)
     chunksOf 3                             -- split into 3 element lists
fst.break(\e->                              -- take elements from this list
           elem e["UAA","UAG","UGA"]||      -- as long as we don't see end codons
           length e<3)                      -- or run out of full codons

```
> 5 votes

# Answer
# Vyxal 3, 25 bytes

```
"ᶠx„ẋİ⁻/3Ŀ:ƛ'u"\ᵇ„o+c]Ṙƒh

```

Try it Online!

There's my ~~26~~ 25 byter

old explanation:

```
"ᶠx„ẋİ⁻/3Ŀ:ƛ'u"\ᵇ„o+=a]Ṙƒh
"ᶠx„ẋ                       # The first index of "aug"
     İ                      # Slice from here to the end
      ⁻                     # Split into parts of length 3
       /3Ŀ:                 # Keep only those whose length is 3 and duplicate
           ƛ        =a]     # for each codon, does it equal any of...
                  o         # overlapping pairs of....
              "\ᵇ„          # The string "aaga" --> ["aa", "ag", "ga"]
            'u              # with a "u" prepended to each ["uaa", "uag", "uga"]
                       Ṙƒh  # partition before truthy indices, take the first item.

```

Created with the help of Luminespire.
> 2 votes

# Answer
# Perl 5 `-n`, 40 bytes

```
map/UAA|UAG|UGA/?last:say,/AUG|\B\G.../g

```

Try it online!
> 2 votes

# Answer
# Python 2, 185 bytes

```
i=input()
o=[]
if i.find('AUG')>=0:i=map(''.join,zip(*[iter(i[i.find('AUG'):])]*3))
else:print "";exit()
for j in i:
 if j not in['UGA','UAA','UAG']:o+=[j]
 else:break
print ','.join(o)

```

**Explanation** Set `i` to input. Split it from 'AUG' to the end. Split into strings of three. Check if stop codon, and cut.

Try it here
> 1 votes

# Answer
### JavaScript ~~88~~ ~~82~~ ~~70~~ 69 chars

```
s=>/AUG(...)+?(?=(U(AA|AG|GA)|$))/.exec(s)[0].match(/.../g).join(",")

```

Usage Example:

```
(s=>/AUG(...)+?(?=(U(AA|AG|GA)|$))/.exec(s)[0].match(/.../g).join(","))("ACAUGGAUGGACUGUAACCCCAUGC")

```
> 1 votes

# Answer
# Ruby, ~~97~~ ~~95~~ ~~78~~ ~~75~~ 62 bytes

```
->(r){r.scan(/AUG|\B\G.../).join(?,).sub(/,U(AA|AG|GA).*/,'')}

```

I don't golf much, so I'm sure it can be improved.

Edit: ~~Stole~~ Borrowed Martin Büttner's excellent `\B\G` trick
> 1 votes

# Answer
# MATL, 57 bytes

```
j'AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))'XXtn?1X)tnt3\-:)3[]e!

```

This uses current version (9.3.1) of the language/compiler.

Input and output are through stdin and stdout. The output is separated by linebreaks.

### Example

```
>> matl
 > j'AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))'XXtn?1X)tnt3\-:)3[]e!
 >
> ACAUGGAUGGACUGUAACCCCAUGC
AUG
GAU
GGA
CUG

```

*EDIT (June 12, 2016): to adapt to changes in the language, `[]` should be removed. The link below includes that modification*

**Try it online!**

### Explanation

The code is based on the regular expression

```
AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))

```

This matches substrings starting with `AUG`, containing groups of three characters (`...`) and ending in either `UAA`, `UAG`, or `UGA`; or ending at the end of the string, and in this case there may be one last incomplete group (`.?.?$`). *Lookahead* (`(?=...)`) is used so that the stop codons are not part of the match. The matching is *lazy* (`*?`) in order to finish at the first stop codon found, if any.

```
j                                     % input string
'AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))'   % regex
XX                                    % apply it. Push cell array of matched substrings
tn?                                   % if non-empty
1X)                                   % get first substring
tnt3\-:)                              % make length the largest possible multiple of 3
3[]e!                                 % reshape into rows of 3 columns
                                      % implicit endif
                                      % implicit display

```
> 1 votes

# Answer
# Scala 2, ~~170~~ 156 bytes

A port of @nimi's Haskell answer in Scala.

Saved 14 bytes thanks to @pacman256

---

Golfed version. Attempt This Online!

```
s=>{val q=s.indexOf("AUG");if(q>=0){val c=s.drop(q).grouped(3).toSeq;c.takeWhile(c=>c.size==3&& !Seq("UAA","UAG","UGA").contains(c))}else Seq.empty[String]}

```

Ungolfed version. Attempt This Online!

```
object RNASequenceProcessor {

  def main(args: Array[String]): Unit = {
    val rnaSequence = "AUGCUUAUGAAUGGCAUGUACUAAUAGACUCACUUAAGCGGUGAUGAA"
    val codingRegion = findCodingRegion(rnaSequence)
    println("["++codingRegion.mkString(",")++"]")
  }

  def findCodingRegion(sequence: String): Seq[String] = {
    // Find the start of the coding region (first occurrence of "AUG")
    val startOfCoding = sequence.indexOf("AUG")
    if (startOfCoding != -1) {
      // Extract the sequence from "AUG" onward
      val codingSequence = sequence.drop(startOfCoding)

      // Split the sequence into codons (chunks of 3 nucleotides)
      val codons = codingSequence.grouped(3).toSeq

      // Take codons until a stop codon is encountered or the codon length is less than 3
      codons.takeWhile(codon => codon.length == 3 && !Seq("UAA", "UAG", "UGA").contains(codon))
    } else {
      Seq.empty[String] // Return an empty sequence if "AUG" is not found
    }
  }
}

```
> 0 votes

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

```
s=>[/AUG(...)*?(?=UA[AG]|UGA|.?.?$)|$/.exec(s)[0].match(/.../g)]+''

```

Try it online!
> 0 votes

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


title: Sum up snail number neighbours

text:
# Question
Title: Sum up snail number neighbours
**Input**: You are given two numbers `n` and `m`.

**Create the snail**: Given an `n >= 3`, fill an `n` * `n` grid with the numbers from `1` to `n * n`, starting at the top left, going clockwise to the middle like this (for `n` = 5):

```
 1  2  3  4  5
16 17 18 19  6
15 24 25 20  7
14 23 22 21  8
13 12 11 10  9

```

**Calculate the sum of the neightbours of `m`**: for `4*n – 4 < m <= n*n`, calculate the sum of the eight neighbour numbers in the snail. In the 5 * 5 example, for `m`= 17, this would be:

```
1+2+3+16+18+15+24+25 = 104

```

**Output**: Only the sum

**Test cases**:

```
4,14 --> 64
5,17 --> 104
5,25 --> 164
6,24 --> 112
6,30 --> 176
6,32 --> 200
6,33 --> 234

```

**Win** by finding the shortest code for your language of choice!

# Answer
# MATL, 19 bytes

```
UQG1YL-t3Y6Z+wi=*Xz

```

Try it at MATL online!

### How it works

```
UQ     % Implicit input: n. Square, add 1
G      % Push n again
1YL    % Generate spiral with side length n, from 1 to to n^2 outwards
-      % Subtract, element-wise. The spiral is now from 1 to n^2 inwards
t      % Duplicate
3Y6    % Push predefined literal: [1 1 1; 1 0 1; 1 1 1]
Z+     % 2D convolution, preserving size. This computes the sums
w      % Swap. This moves the spiral to the top of the stack
i=     % Input: m. Compare for equality, element-wise
*      % Multiply, element-wise. This keeps the wanted sum, and makes the rest 0
Xz     % Nonzeros. This keeps the only non-zero value. Implicit display

```
> 4 votes

# Answer
# 05AB1E, 31/32 bytes

```
¯I·FāUøí¬g+Xš}2Fø€ü3}€`ʒ˜4èQ}˜O

```

Inputs in the order \\$n,m\\$.

31 bytes - sum including \\$m\\$: Try it online or verify all test cases.
32 bytes - sum excluding \\$m\\$: Try it online or verify all test cases. (Contains an additional trailing `α`.)

**Explanation:**

Step 1: Create the spiral matrix for the given \\$n\\$, taken from this answer of mine:

```
¯             # Start with an empty list []
 I·           # Push the first input n and double it
   F          # Pop and loop that many times:
    ā         #  Push a list in the range [1,length] (without popping the matrix)
     U        #  Pop and store this list in variable `X`
      øí      #  Rotate the matrix 90 degrees clockwise:
      ø       #   Zip/transpose; swapping rows/columns
       í      #   Reverse each row
        ¬     #  Push the first row (without popping the matrix)
         g    #  Pop and push its length
          +   #  Add that to each value in the matrix
           Xš #  Prepend list `X` as first row
   }          # Close the loop

```

Step 2: Create overlapping 3x3 blocks of this matrix:

```
2F            # Loop 2 times:
  ø           #  Zip/transpose; swapping rows/columns
   €          #  Map over each inner list:
    ü3        #   Create overlapping triplets
 }            # Close the loop

```

Step 3: Only keep the 3x3 block with \\$m\\$ in the center:

```
€`            # Flatten the matrix of 3x3 blocks one level down to a list of 3x3 blocks
  ʒ           # Filter this list by:
   ˜          #  Flatten the 3x3 block to a list of 9 values
    4è        #  Pop and leave the 0-based 4th item (the center)
      Q       #  Check whether it equals the second (implicit) input m
  }           # Close the filter

```

Step 4: Sum the found 3x3 block, and output the result:

```
˜             # Flatten the single wrapped 3x3 block to a list
 O            # Sum it together
  α           # (optionally) Take the absolute difference with the second (implicit)
              # input m to subtract m from this sum
              # (after which this is output implicitly as result)

```
> 3 votes

# Answer
# , 116 bytes

```
\(n,k){m=t(1)
while(F<n)m=rbind(1:n,(F=nrow(m))+t(m[F:1,]))
sum(m[t(t(expand.grid(-1:1,-1:1))+c(which(m==k,T)))])-k}

```

Attempt This Online!

Uses some code from the spiral challenge.
> 3 votes

# Answer
# , ~~55~~ 54 bytes

```
([-~1#.]#&,~[:+/(>,{;~i:1)|.=)+:@<:_&(]#\,#+|:@|.),.@1

```

Try it online!

Uses Bubbler's clever APL/Jelly method from an old problem for constructing the involute itself.

Consider input `17 f 5`:

* `+:@<:_&(]#\,#+|:@|.),.@1` Construct the involute iteratively using Bubbler's method (see link above for explanation):

```
1  2  3  4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

```
* `=` Where does the left input equal that?

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

```
* `[:+/(>,{;~i:1)|.` Rotate that in the 8 neighbor directions, and sum the planes:

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

```
* `1#.]#&,~` Filter using that mask and sum:

```
121

```
* `[-~` Subtract the left input (17):

```
104

```
> 3 votes

# Answer
# Charcoal, 60/62 bytes

```
Ｆ⊗Ｎ≔⁺⟦Ｅυ⊕λ⟧Ｅ∧υ⌊υ⁺ＬυＥ⮌υ§μλυＮθ≔⊟Φυ№ιθηＩΣＥΦυ‹↔⁻κ⌕υη²ΣΦι‹↔⁻μ⌕ηθ²

```

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

```
Ｆ⊗Ｎ≔⁺⟦Ｅυ⊕λ⟧Ｅ∧υ⌊υ⁺ＬυＥ⮌υ§μλυ

```

Input `n` and generate the spiral using the method from my answer to Print a NxN integer involute except 1-indexed.

```
Ｎθ≔⊟Φυ№ιθη

```

Input `m` and find the row containing `m` in the spiral.

```
ＩΣＥΦυ‹↔⁻κ⌕υη²ΣΦι‹↔⁻μ⌕ηθ²

```

Extract the neighbours of `m` and output the sum.

Note that the `5, 17` test case includes the `17` itself in the total; if this is not wanted then it can be subtracted at a cost of 2 bytes:

```
Ｆ⊗Ｎ≔⁺⟦Ｅυ⊕λ⟧Ｅ∧υ⌊υ⁺ＬυＥ⮌υ§μλυＮθ≔⊟Φυ№ιθηＩ⁻ΣＥΦυ‹↔⁻κ⌕υη²ΣΦι‹↔⁻μ⌕ηθ²θ

```

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

# Answer
# JavaScript (ES6), 174 bytes

Derived from this answer by tsh to this other challenge.

Expects `(n)(m)`.

```
n=>m=>(g=(s,[l]=t=s[0])=>l>1?g([0,...t].map((_,i)=>s.map((r,x)=>(v=r[i-1]||--l)-m?v:(X=x,Y=i,v)).reverse())):s)([[n*n]]).map((r,y)=>r.map(v=>m-=v*=--x*x+y*y<3,x=n-X,y-=Y))|-m

```

Try it online!
> 2 votes

# Answer
# Google Sheets, 423 bytes

Assuming \\$n\\$ is in A1 and \\$m\\$ is in A2.

```
=SUMPRODUCT(LET(n,A1,s,SEQUENCE(n,n),t,TOCOL(SPLIT(REDUCE(s,s,LAMBDA(x,_,LET(r,INDEX(x,1),a,FILTER(x,r),HSTACK(JOIN(",",r),SORT(TRANSPOSE(QUERY(a,"offset 1")),SEQUENCE(COLUMNS(a)),))))),","),3),p,XLOOKUP(s,{t;INDEX(t,n*n-1)+IF(ISODD(n),1,-1)},TOCOL(s)),x,TEXTJOIN(,,IF(p=A2,SEQUENCE(n)&","&SEQUENCE(1,n),)),i,SPLIT(x,","),r,INDEX(i,1),k,INDEX(i,2),p*MAKEARRAY(n,n,LAMBDA(i,j,ISBETWEEN(i,r-1,r+1)*ISBETWEEN(j,k-1,k+1)))))-A2

```

Ungolfed

<pre><code>// Create the spiral

=LET(n,A1,s,SEQUENCE(n,n),
     t,TOCOL(
         SPLIT(REDUCE(s,s,LAMBDA(x,_,
           LET(r,INDEX(x,1),a,FILTER(x,r),
               HSTACK(JOIN(",",r),
               SORT(TRANSPOSE(QUERY(a,"offset 1")),SEQUENCE(COLUMNS(a)),))))),
           ","),3),
     p,XLOOKUP(s,{t;INDEX(t,n*n-1)+IF(ISODD(n),1,-1)},TOCOL(s)),

// Find the coordinates of m

     x,TEXTJOIN(,,IF(p=A2,SEQUENCE(n)&","&SEQUENCE(1,n),)),

// Assign them to (r,k)

     i,SPLIT(x,","),r,INDEX(i,1),k,INDEX(i,2),

// Create a nxn array composed of 1s in the 3x3 array around (r,k) and 0s everywhere else and multiply it by the spiral

     p*MAKEARRAY(n,n,LAMBDA(i,j,ISBETWEEN(i,r-1,r+1)*ISBETWEEN(j,k-1,k+1))))

// Array enabling sum on the above result to which we subtract m

SUMPRODUCT(all_of_the_above)-A2
```
</code></pre>
> 2 votes

# Answer
# Uiua <sup>SBCS</sup>, 47 bytes

```
-:/+♭⍜↻(↙3_3)-1♭⊚⌕⊙.:+1⍥(⊂⇡⟜(≡⇌⍉+)⧻.):¤[]-1+.⊙.

```

Try it!
> 1 votes

# Answer
# APL+WIN, 106 bytes

Prompts for n followed by m:

```
a←1 1⍴1⋄i←1⋄⍎∊(¯1+n←⎕)⍴⊂'a←(⍳i+1)⍪⌽⍉(i+1)+(⍳i)⍪⌽⍉a+i⋄i←i+1⋄'⋄+/((,a)[(k-n),(k+n),(k←((,a)⍳m)+¯1 0 1)])~m←⎕

```

Try it online! Thanks to Dyalog Classic
> 1 votes

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

```
n=>h=(v,i,j=n,g=(x=i,y=j,w=n,h=w)=>y?w+g(y-1,w+~x,h-1,w):x+1)=>j--?h(v,i,j)+(1/i?(v.i-i)**2+(v.j-j)**2<3?g():g()==v&&h({i,j})-v:h(v,j)):0

```

Try it online!

`g()` gets the number at position `(x,y)`
> 0 votes

# Answer
# AWK, 216 212 193 bytes

```
func f(){r=$2-(g[x,y]=++c)?r:-g[m=x,n=y]}{for(x=y=0;i++<$1;y++)f();for(y--;s++<$1;){for(i=s;i++<$1;)f(x+=t=s%2?1:-1);for(i=s;i++<$1;)f(y-=t)}for(i=m-2;++i<m+2;)for(j=n-1;j<n+2;)r+=g[i,j++]}$0=r

```

Try it online!

* -4 bytes, used ternary operator (`exp?a:b`) instead of `if` statement and replaced `==` with `-` expression.
* -19 bytes, replaced ternary operation with function.
> 0 votes

# Answer
**, 169 Bytes**

**Golfed:**

```
b:1 0 -1 0;d:0;c:0 0;s:n#(,)n#0;a:{c+{x d}'[(0,b;b)]};{.[`s;c;:;x];if[x=m;l::c];if[0<>.[s;n:a[]];d::mod[d+1;4];n:a[]];c::n}'[1+til n*n];sum[(s/')[(cross/){x+3#b}'[l]]]-m

```

**Ungolfed:**

```
snail: n#enlist n#0;   // create an n x n array (the "snail") where each cell has value 0; it's populated properly below
direction: 0;          // 0=right, 1=down, 2=left, 3=up
current_cell: 0 0;     // the row/column of the current cell to populate in the n x n array
m_cell: -1 -1;         // the row/column of the cell in the n x n array whose value is m

// given a 2-item list returns the value of the snail cell at the row & column; returns null (0N) if there is no such row or column
read_cell: { .[snail; x] };

// returns the row + index (2-item list) of the cell after "current_cell" that should be populated given the current value of "direction"
get_next_cell: { (current_cell[0] + (0 1 0 -1)[direction]; current_cell[1] + (1 0 -1 0)[direction]) };

// loop through integers in range [1..n x n] to populate the snail
{
    // set value of current_cell in the snail to the current integer in the loop
    snail:: .[snail; current_cell; :; x];

    // record m_cell if the current integer in the loop is "m
    if[x=m; m_cell:: current_cell];

    // calculate the next cell
    next_cell: get_next_cell[];

    // if the calculated next cell has a non-zero value, either:
    //      * the value is 0N, meaning we've gone past the bounds of the n x n array or
    //      * the value is a positive integer, meaning the cell has already been populated
    // in which case we change direction and re-calculate the next cell
    if[read_cell[next_cell] <> 0;
        direction:: (direction + 1) mod 4;
        next_cell: get_next_cell[];
        ];

    current_cell:: next_cell;
    } each 1+til n*n;

// "return" the difference between (a) the sum of all 9 cells in the 3x3 square centered on m_cell and (b) m
sum[read_cell each .[cross]{x + -1 0 1} each m_cell] - m

```
> 0 votes

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


title: Code-Golf: Permutations

text:
# Question
Title: Code-Golf: Permutations
Write a function that takes as input a set of integers (can be a list, array or any other container with distinct numbers), and outputs the list of all its permutations.

**Python (95 chars)**:

```
p=lambda s:s and sum(map(lambda e:map(lambda p:[e]+p,p(filter(lambda x:x!=e,s))),s),[]) or [[]]
```

It'd be nice to be beaten in the same language, but implementations in other languages are more than welcome!

# Answer
## Python - 76 chars

Longer than gnibbler's, but implements things from scratch.

```
p=lambda x:x and[[a]+b for a in x for b in p([c for c in x if c!=a])]or[[]]

```
> 11 votes

# Answer
# Python, 52

Input is a set. Output is a list of lists.

```
f=lambda a:[p+[x]for x in a for p in f(a-{x})]or[[]]

```

This is shorter than the answer that does all the work with a builtin.
> 17 votes

# Answer
## J, 11 characters

```
(i.@!@#A.[)

```

Usage:

```
   (i.@!@#A.[) 1 3 5
1 3 5
1 5 3
3 1 5
3 5 1
5 1 3
5 3 1

```

Explanation:

`i.@!@#` uses three verbs to return a list from 0 to (!n)-1 where n is the number of items in the given list.

`[` returns the list itself. In the example shown that gives `0 1 2 3 4 5 A. 1 3 5`.

`A.` returns one possible permutation of the second list for each item in the first list (kind of - the proper explanation is given here).
> 10 votes

# Answer
## Python - 55 chars

```
from itertools import*
p=lambda x:list(permutations(x))

```
> 8 votes

# Answer
## Haskell, 44 43

```
p[]=[[]]
p l=[e:r|e<-l,r<-p$filter(/=e)l]

```

Essentially the same as ugoren's solution, but Haskell is better at list comprehensions!

---

Of course, it can also do

## 30

```
import Data.List
p=permutations

```

---

More efficient approach, that doesn't require an equality comparison:

## 92

```
import Data.List
p[]=[[]]
p l=(\(l,(e:r))->map(e:)$p(l++r))=<<(init$zip(inits l)(tails l))

```

As a consequece, this one also works when there are duplicate elements in the list.
> 8 votes

# Answer
# C, ~~270~~ ~~243~~ 239 characters

```
#define S t=*a;*a=a[i];a[i]=t;
#define R o=p(n,r-1,a+1,o,r-2,0)
int*p(n,r,a,o,i,t)int*a,*o;{if(!r)for(;n;--n)*o++=*--a;else{R;for(;i;--i){S R;S}}return o;}
P(n,a)int*a;{int N=1,i=n;for(;i;N*=i--);return p(n,n,a,malloc(N*n*8),n-1,0)-N*n;}

```

The function P(n,a) returns a pointer to the n! permutations of a, packed one after another in one giant array.
> 4 votes

# Answer
# Prolog (SWI), 33 bytes

```
X-Y:-bagof(A,permutation(X,A),Y).

```

Try it online!

-2 from steffan
> 4 votes

# Answer
## in Q (48)

```
g:{$[x=1;y;raze .z.s[x-1;y]{x,/:y except x}\:y]}

```

Sample usage:

```
q)g[3;1 2 3]
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

```
> 3 votes

# Answer
# Ruby - 23 chars

```
f=->x{p *x.permutation}

```

for example `f[[1,2,3]]` outputs this.

but using `[].permutation` feels like cheating, so:

# Ruby - 59 chars

```
f=->a{a.size<2?[a]:a.flat_map{|x|f[(a-x=[x])].map{|y|x+y}}}

```

tested with

```
100.times.all?{arr=(1..99).to_a.sample(rand(5)); arr.permutation.to_a==f[arr]}
=> true

```
> 2 votes

# Answer
### Scala 30:

```
def p(s:Seq[_])=s.permutations

```

### Scala 195, quick'n'dirty, without *permutations* from library:

```
def c(x:Int,t:List[_]):List[_]={val l=t.size
val o=x%l
if(l>1){val r=c(x/l,t.tail)
r.take(o):::(t.head::r.drop(o))}else
t}
def p(y:List[_])=(0 to(1 to y.size).product).foreach(z=>println(c(z,y)))

val y=List(0,1,2,3)
p(y)

```

### Scala 293, full grown, type safe iterator:

```
class P[A](val l:Seq[A])extends Iterator[Seq[A]]{
var c=0
val s=(1 to l.size).product
def g(c:Int,t:List[A]):List[A]={
val n=t.size
val o=c%n
if(n>1){val r=g(c/n,t.tail)
r.take(o):::(t.head::r.drop(o))
}else
t}
def hasNext=c!=s
def next={c+=1
g(c-1,l.toList)}
}
for(e<-new P("golf"))println(e)

```
> 2 votes

# Answer
**Python - 58 chars**

Slightly shorter than ugoren's, by taking a set as input:

```
p=lambda x:x and[[y]+l for y in x for l in p(x-{y})]or[[]]

```
> 2 votes

# Answer
# K, 30 bytes

```
{x@v@&((#x;1)~^=:)'v:!(#x)##x}

```

No builtins!
> 2 votes

# Answer
## JS - ~~154~~ 146 chars

`function f(x){var a=[],m;(m=x.length)>1?f(x.slice(1)).map(function(y){for(l=m;l--;a.push(y.slice(0,l).concat(x[0],y.slice(l))));}):a=[x];return a}`

Test : `f([1,2,3,4,5]).map(function(a){return a.join('')}).join('\n')` returns this.
> 1 votes

# Answer
## R

Since we are talking about permutations let me show at least one solution in R:

```
library(gtools);v=c(3,4,5);permutations(length(v),length(v),v)

```
> 1 votes

# Answer
## Perl 188

No library routines, no recursion

```
sub p{$l=(@_=sort split'',shift)-1;while(print@_){$k=$j=$l;--$k while($_[$k-1]cmp$_[$k])>=0;$k||last;--$j while($_[$k-1]cmp$_[$j])>=0;@_[$j,$k-1]=@_[$k-1,$j];@_[$k..$l]=reverse@_[$k..$l]}}

```
> 1 votes

# Answer
## Python - 50 chars

```
import itertools
list(itertools.permutations("123"))

```
> 1 votes

# Answer
# Pyth, 4 bytes

```
L.pb

```

Yeah, Pyth was created after this challenge was posted and all. This is still really cool. :D

Live demo.

Reading from stdin is a byte shorter:

```
.pQ

```
> 1 votes

# Answer
# JavaScript ~~143~~ ~~136~~ ~~134~~ 123

```
function p(s,a="",c="",i,z=[]){a+=c,i=s.length
!i?z.push(a):0
for(;i--;s.splice(i,0,c))p(s,a,c=s.splice(i,1),0,z);return z}

var perms = p([1,2,3]);

document.getElementById('output').innerHTML = perms.join("\n");
```

```
<pre id="output"></pre>
```
> 1 votes

# Answer
# 05AB1E - 2 1 bytes

`œ`

The input must be an array/list.

Explanation:

```
œ //Takes all the permutations of the elements in the top of the stack (the input is a list, so it would work)

```

Saved a byte thanks to Erik the Outgolfer
> 1 votes

# Answer
# Brachylog, 2 bytes

```
pᵘ

```

Try it online!

```
 ᵘ    Find every unique
p     permutation of the input.

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
ṖU

```

Try it Online!

```
Ṗ  # All permutations of input
 U # Filtered by unique

```
> 1 votes

# Answer
# JavaScript (ES6), ~~91~~ 78 bytes

*-5 thanks to @Neil*

```
f=a=>a.length<2?[a]:a.flatMap((x,i)=>f(a.filter((_,j)=>i-j)).map(t=>[x,...t]))

```

Pretty normal recursive approach, and my first time using `copyWithin` :p

Okay, `copyWithin` modifies the array, so that doesn't work. Used a different approach, which now saves more bytes.
> 1 votes

# Answer
# Curry, ~~41~~ 26 bytes

*15 bytes saved by alephalpha*

*Tested in PAKCS*

```
p[]=[]
p(x++a:y)=a:p(x++y)

```

Try it online!

Uses non-determinism to output all the permutations. This same code is used in my answer here for which I originally wrote it.
> 1 votes

# Answer
# Knight, 180 bytes

```
;=i=jF;W=pP E++"=x"=i+1i" p";=s"";W>i-=j+1jT=s+++++++s";=y"j"F W>i-=y"j"+1y"j"T"E+s';=z=bF;W>i-=z+1zT;=aF W>i-=a+1aT|?z a=b|b?E+"y"zE+"y"a|b;=rF;=s"";W>z=r+1r=s++sE+"x"E+"y"r" "Os'

```

Try it online!

This was a *pain*. Nested evals and stuff. Since recursion doesn't really work, I had to literally compose a string of nested while loops, and then eval it. Extremely inefficient, \\$O(n^{n+1})\\$ where \\$n\\$ is the length of the input. My browser started to freeze up with \\$n=6\\$.

-2 bytes thanks to Aiden Chow.
> 1 votes

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

```
{x@?<'+!a#a:#x}

```

Try it online!
> 1 votes

# Answer
# Perl 5, 66 bytes

```
sub{$"=",";grep{my%t;@t{@$_}++;@_==%t}map{[/\d+/g]}glob"{@_}-"x@_}

```

Try it online!

Relies on the problem definition of *distinct* integers. Also horribly wasteful--it creates n\**n candidates only to discard the ones that duplicate members within them.
> 1 votes

# Answer
# Python, 53 bytes

```
from itertools import*;lambda x:list(permutations(x))

```
> 0 votes

# Answer
# Axiom, 160 bytes

```
p(a)==(#a=0=>[[]];r:=[[a.1]];r:=delete(r,1);n:=#a;m:=factorial n;m>1.E7=>r;b:=permutations n;for j in 1..m repeat(x:=b.j;r:=concat([a.(x.i)for i in 1..n],r));r)

```

ungolfed

```
--Permutation of a
pmt(a)==
     #a=0=>[[]]
     r:=[[a.1]]; r:=delete(r,1) -- r has the type List List typeof(a)
     n:=#a
     m:=factorial n
     m>1.E7=>r
     b:=permutations(n)         --one built in for permutation indices
     for j in 1..m repeat
        x:=b.j
        r:=concat([a.(x.i) for i in 1..n],r)
     r

```

All this call one library function that give permutation on index (only integers as permutation as permutations on \[1\], permutations on \[1,2\], permutations on\[1,2,3\] etc).So it is enough get these set of indices and build the lists; One has to note that this seems to be compiled good for every List of type X

```
(4) -> p([1,2,3])
   Compiling function p with type List PositiveInteger -> List List
      PositiveInteger
   (4)  [[1,2,3],[1,3,2],[3,1,2],[2,1,3],[2,3,1],[3,2,1]]
                                          Type: List List PositiveInteger
(5) -> p([x^2,y*x,y^2])
   Compiling function p with type List Polynomial Integer -> List List
      Polynomial Integer
   (5)
      2      2    2  2        2  2            2  2        2  2    2      2
   [[x ,x y,y ],[x ,y ,x y],[y ,x ,x y],[x y,x ,y ],[x y,y ,x ],[y ,x y,x ]]
                                       Type: List List Polynomial Integer
(6) -> p([sin(x),log(y)])
   Compiling function p with type List Expression Integer -> List List
      Expression Integer
   (6)  [[sin(x),log(y)],[log(y),sin(x)]]
                                       Type: List List Expression Integer
(7) -> m:=p("abc")::List List Character
   Compiling function p with type String -> Any
   (7)  [[a,b,c],[a,c,b],[c,a,b],[b,a,c],[b,c,a],[c,b,a]]
                                                Type: List List Character
(8) -> [concat(map(x+->x::String, m.j))  for j in 1..#m]
   (8)  ["abc","acb","cab","bac","bca","cba"]
                                                        Type: List String

```
> 0 votes

# Answer
# Jelly, 2 bytes

```
Œ!

```

Try it online!

Yay for builtins!
> 0 votes

# Answer
# K (oK), 3 bytes

**Solution**

```
prm

```

Try it online!

**Explanation:**

It's a 3 byte **built-in** shortcut to the following **built-in** 47 byte function:

```
{[x]{[x]$[x;,/x ,''o'x ^/:x;,x]}@$[-8>@x;!x;x]}

```

... which can be shortened to 23 bytes if we know we're getting a list of ints as input:

```
{$[x;,/x,''o'x^/:x;,x]} / golfed built in
{                     } / lambda function with implicit input x
 $[ ;             ;  ]  / if[condition;true;false]
   x                    / if x is not null...
             x^/:x      / x except (^) each-right (/:) x; create length-x combinations
           o'           / call self (o) with each of these
       x,''             / x concatenated with each-each of these results (this is kinda magic to me)
     ,/                 / flatten list
                    ,x  / otherwise enlist x (enlisted empty list)

```
> 0 votes

# Answer
# APL(NARS), 39 chars, 78 bytes

```
{1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨q w[a∼⍵]}¨a←⍳k}

```

test:

```
  q←{1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨q w[a∼⍵]}¨a←⍳k}
  q 1 2 3
1 2 3  1 3 2  2 1 3  2 3 1  3 1 2  3 2 1
  q 'abcd'
abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba

```
> 0 votes

# Answer
# Japt, 1 byte

```
á

```

Japt interpreter

This got bumped and didn't have a Japt answer, so I figured I'd go ahead and add one. `á` when applied to an array and without any arguments is the builtin for "get all permutations". The `-R` flag used in the interpreter link only modifies how the result is printed.
> 0 votes

---
Tags: code-golf, combinatorics, permutations
---