title: Spoonerise words

text:
# Question
Title: Spoonerise words
Given two words, spoonerise them by switching their initial consonant clusters. Fewest bytes wins.

```
plaster man -> master plan
blushing crow -> crushing blow
litigating more -> mitigating lore
strong wrangler -> wrong strangler
def ghi -> ghef di
few years -> yew fears

```

The consonants appearing before the first vowel (`aeiou`) are switched.

**Input:** Two lowercase strings that start with different consonants and each contain a vowel `aeiou`.

**Output:** The two spoonerised strings, in the right order.

For input and/or output, the two strings may also be in a list or the like, or as a single string with separator.

```
    var QUESTION_ID=69385,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/69385/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
    body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

**Leaderboard:**
```

---

This is a near-dupe of this old question, but I'm hoping to write a spec that is clearer and more stable so that the old one can be closed as a dupe.

# Answer
> 51 votes
# Vim, 18 keystrokes

```
/[aeiou]<CR>dbwvnhp0P

```

The crucial trick is that pasting over something in Visual mode actually puts the old contents of the visual selection in the paste buffer.

# Answer
> 21 votes
# brainfuck, ~~238~~ 207 bytes

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

```

Requires `,` to return 0 on EOF, 8-bit wrapping cells and the ability to move left from cell 0. In my experience, these are the most common default settings.

I'm pretty happy with this one. My first try was 314 bytes and this is certainly an improvement. :)

It works by storing every byte from input in two cells; one with the actual value of the byte and the other with the output of the following code when given (the value of the byte - 97):

```
[
    ----
    [
        ----
        [
            ------
            [
                ------>>
            ]
        ]
    ]
]

```

If the character is a consonant, it comes out of that with a non-zero value. If it's a vowel, it becomes 0. From there it's just a matter of finding where the second word starts and printing everything in order.

The 238 byte version of this program found the space character after collecting all the input. It was a headache because doing so involved creating a cell that contained 0 right where I was trying to loop over it. The way I solved that had the effect of subtracting 30 from every character in the first word and 32 from every character after it. A fairly large portion of the code was dedicated to handling that nonsense.

Now, 32 is subtracted from *every character* in the input loop, which is shorter and has a similar side effect that's easier to deal with. As a bonus, doing it this way allowed me to create my own space character in a shorter way: Instead of subtracting 139 from 171 (171 is what you get when you run a space through the vowel detector above), the loop that adds 32 to every character goes out of its way to also add 32 to the 171 cell. This costs four bytes there, but means I can subtract 171 from it later (instead of subtracting 139) for a net total of 3 bytes saved.

With comments:

```
For every input character
,[

  Make a copy
  [<+<+>>-]

  Subtract 32 from one
  ++++[<-------->-]

  Subtract 97 from the other
  -[<<-->>-----]<<+++++

  If nonzero:
  [

    Subtract 4
    ----

    If nonzero:
    [

      Subtract 4
      ----

      If nonzero:
      [

        Subtract 6
        ------

        If nonzero:
        [

          Subtract 6
          ------>>

        ]

      ]

    ]

  ]

>[>>]>,]

Add 32 to every character and the 171 that the space left behind
<<++++++++[<[++++<<]<++++<[++++<<]>>[>>]>>[>>]<-]

Go to the space
<[<<]

Subtract 171 from (32 plus 171)
-[<+>---]

~~~~~~~~~~~~~~~

Ready to print!

~~~~~~~~~~~~~~~

Print letters from the second word until the value to the left is zero
>[>.>]

Go to the beginning of the first word
<[<<]<<[<<]

Look at cells to the left of letters in the first word until reaching a zero
>[>>]

Print the rest of the letters in the first word
>[.>>]

Print a space
<.

Go to the beginning of the first word
<[<<]

Print letters from the first word until the value to the left is zero
>[>.>]

Go to the beginning of the second word
>[>>]

Look at cells to the left of letters in the second word until reaching a zero
>[>>]

Print the rest of the letters in the second word
>[.>>]

```

# Answer
> 18 votes
## vim, 23

```
/[aeiou]<cr>"xd0wndb0Pw"xP

```

I wonder if vim is actually competitive in this challenge. Probably not with the golfing languages, but perhaps with Ruby/Python/Perl/etc.

```
/[aeiou]<cr>  Find the first vowel
"xd0          "Delete" (cut), to register "x, everything from here to BOL
w             Go to next word
n             Find next vowel
db            "Delete back" - delete from here to the beginning of the word
0             Go to BOL
P             Paste what we just "deleted" (cut) behind the cursor
w             Next word
"xP           Paste backwards from register "x

```

# Answer
> 17 votes
# Python, ~~68~~ ~~63~~ 60 bytes

```
import re
lambda s:re.sub('([^aeiou]+|.+ )'*3,r'\3\2\1',s,1)

```

Try it online on Ideone.

### How it works

The pattern string is repeated thrice (`*3`), resulting in the pattern

```
([^aeiou]+|.+ )([^aeiou]+|.+ )([^aeiou]+|.+ )

```

All instances will either match a non-empty string of non-vowels, or a non-empty string followed by a single space character.

The first instance will match the consonants at the beginning of the first word. Since `+` is greedy, it will attempt to match as many as possible, i.e., all up to the first vowel.

Because of this, the second instance will start at a vowel, so it will match the remainder of the first word, up to and including the space that separates the words.

Similarly to the first instance, the third will match all consonants at the beginning of the second word, resulting in a successful match for the entire pattern.

The raw string `\3\2\1` (`r` prevents Python from replacing `\3` etc. with control characters) reverses the order of the matches of the parenthesized patterns, i.e., it replaces them with the consonants at the beginning of the *second* word, then all characters from the first vowel of the first word up to the space, and finally the consonants at the beginning of the first word.

The final argument to `sub` (`1`) makes it return immediately after the first successful replacement, to avoid nonsensical replacements in the remainder of the second word. This is required since the pattern can match any string of three or more consecutive consonants.

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

```
s=>s.replace(r=/\b[^aeiou ]+/g,(_,i)=>s.match(r)[+!i])

```

## Explanation

```
s=>
  s.replace(
    r=/\b[^aeiou ]+/g,     // r = regex to match consonants
    (_,i)=>s.match(r)[+!i] // replace consonants with the consonants from the other word
  )

```

## Test

```
var solution = s=>s.replace(r=/\b[^aeiou ]+/g,(_,i)=>s.match(r)[+!i])
```

```
<input type="text" id="input" value="plaster man" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 11 votes
# Python 3, ~~108~~ ~~101~~ 99 bytes

**(No use of regex)**

This function expects input via 2 arguments, e.g. `f('blushing','crow')`. Returns the new words in a tuple.

```
S=lambda s,p="":s[0]in"aeiou"and(p,s)or S(s[1:],p+s[0])
def f(x,y):a,b=S(x);c,d=S(y);return c+b,a+d

```

There are a lot of regex solutions, so I wanted to write something that didn't use Python's re library.

## How it works

The only complicated part is the lambda expression `S` (the abbreviation means "**S**plit before the first vowel"). It recursively "iterates" over the given word, moving one character at a time from the beginning of `s` (which starts with the whole word) to the end of `p` (which starts empty). At the first vowel encountered it returns `(p,s)`, i.e. (prefix, suffix). Notice that that is the wrong order compared to the parameters!

I thought it made more sense for the returned order to be prefix, then suffix (because generally a prefix goes before a suffix). This order might make the `a,b=S(x)` code slightly easier to read.

But I had no choice of order in the lambda's parameters, so I couldn't define `p` before `s`. The first parameter, `s`, *had* to take the entire word because `p` had a default value, and default parameters go last. Doing that, I didn't need to call the function `S` with an empty string twice, and a few bytes could be saved. However, perhaps it was simply a bad decision to return prefix/suffix in the opposite order as it was used within the lambda expression.

As for the choice of lambda expression over function, it takes more bytes to say `def S(s,p=""):return` than `S=lambda s,p="":`. I can make that choice because Python has short-circuit evaluation, and the ternary operator. However, I cannot adequately explain how I used short-circuits; it's hard to reason about.

---

This is my first answer. I hope I did this correctly, and that there's value to posting a solution that cannot win.

**Edits:** *Thank-you commenters: Reduced the byte count a bit, twice, and removed unnecessary info. Attempted to improve writing. Hopefully made no mistakes.*

# Answer
> 9 votes
# C#6, 115 bytes

```
string S(string a)=>System.Text.RegularExpressions.Regex.Replace(a,"([^aeiou]*)(.*) ([^aeiou]*)(.*)","$3$2 $1$4");

```

It's just a pain the namespace for regex is so long.

# Answer
> 9 votes
# CJam, ~~27~~ ~~24~~ 22 bytes

```
2{l_{"aeiou"&}#/(N\}*o

```

I/O is one word per line. Try it online!

### How it works

```
2{                 }*   Do the following twice:
  l                       Read a line from STDIN.
   _                      Push a copy.
    {"aeiou"&}#           Find the index of the first character that has a non-
                          empty intersection with the string "aeiou".
               /          Split the string into chunks of that size.
                (         Shift out the first chunk, i.e., all leading consonants.
                 N\       Swap the shifted out chunk with a linefeed.
                     o  Print the topmost stack item.

```

# Answer
> 9 votes
# Perl, 33 bytes

```
s/([^aeiou]+)(.+ )((?1))/\3\2\1/

```

The above code is **32 bytes** long and requires the `-p` switch (**+1 byte**).

The substitution is very similar to the one @DigitalTrauma's Retina answer, but this answer takes advantage of PCRE's recursive subpatterns.

Try it online on Ideone.

# Answer
> 8 votes
# JavaScript ES6, ~~93~~ ~~58~~ 52 bytes

Saved 6 bytes thanks to ETHProductions!

```
x=>x.replace(/([^aeiou]+)(.+ )([^aeiou]+)/,"$3$2$1")

```

## Test it! (ES6 only)

```
F=x=>x.replace(/([^aeiou]+)(.+ )([^aeiou]+)/,"$3$2$1");

console.log=_=>u.innerHTML+=_;

console.log(`plaster man -> master plan
blushing crow -> crushing blow
litigating more -> mitigating lore
strong wrangler -> wrong strangler
def ghi -> ghef di`.split`\n`.map(e=>(e=e.split` -> `,`${e[0]} => ${e[1]} ||> `+(F(e[0])==e[1]))).join`<br>`);
```

```
html { font-family: Consolas, monospace; }
```

```
<div id=u></div>
```

# Answer
> 8 votes
# Retina, 34

```
([^aeiou]+)(.+ )([^aeiou]+)
$3$2$1

```

Try it online.

# Answer
> 7 votes
# C, ~~255~~ ~~201~~ 199 bytes

I don't see a lot of C answers around here, so enjoy; Also, first time golfing, suggestions and critique are welcome.

```
#define S(w,p)p=strpbrk(w,"aeiou")-w
#define c ;strcpy(r
#define l c+strlen(v[1])+b+1
main(int q,char**v){char r[64],S(v[1],a),S(v[2],b)c,v[2])c+b,v[1]+a);strcat(r," ")l-a,v[1])l,v[2]+b);puts(r);}

```

If main() is not required we can save 24 bytes, getting to 179 bytes

```
#define S(w,p)p=strpbrk(w,"aeiou")-w
#define c ;strcpy(r
#define l c+strlen(x)+b+1
s(char*x,char*y){char r[64],S(x,a),S(y,b)c,y)c+b, x+a);strcat(r," ")l-a,x)l,y+b);puts(r);}

```

Ungolfed:

```
void spoonerise(char* w1, char* w2)
{
    char rt[64];

    int p1 = strpbrk(w1, "aeiou")-w1;
    int p2 = strpbrk(w2, "aeiou")-w2;

    strcpy(rt, w2);
    strcpy(rt+p2, w1+p1);

    strcat(rt, " ");

    strcpy(rt+strlen(w1)+p2+1-p1, w1);
    strcpy(rt+strlen(w1)+p2+1, w2+p2);

    puts(rt);
}

```

EDIT: Thanks to feersum's suggestion I saved 54 bytes. =D

# Answer
> 6 votes
# sed, 38 characters

```
s/([^aeiou]+)(.+ )([^aeiou]+)/\3\2\1/

```

Using extended regular expression from the Retina solution.

The above is 37 characters long and requires the `-r` switch (+1 character).

Example:

```
$ cat input | tee /dev/tty | sed -r 's/([^aeiou]+)(.+ )([^aeiou]+)/\3\2\1/'
plaster man
blushing crow
litigating more
strong wrangler
def ghi
master plan
crushing blow
mitigating lore
wrong strangler
ghef di

```

# Answer
> 5 votes
# Python 2, ~~364~~ ~~352~~ ~~269~~ 251 bytes

**EDIT:** Thanks so much to @Cyoce for helping me golf 83 bytes!

Please help me golf this! Anyway, at least I am the first Python answerer. And I hope I can beat Java, if there ever is a Java answer!

```
i=input()
f=l=''
A='aeiou'
for j in A:
 I=i[0];J=I.find(j)
 if ~J:
  if f:
   if f>I[0][:J]:f=I[:J];break
  else:f=I[:J]
for j in A:
 Y=i[1];J=Y.find(j)
 if ~J:
  if l:
   if l>Y[:J]:l=Y[:J];break
  else:l=Y[:J]
print I.replace(f,l,1),Y.replace(l,f,1)

```

Try it here

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

Fortunately, I added a vowel class to Japt's regex features a few days ago. Unfortunately, I didn't add a non-vowel class or a way around the double backslashes in regex strings.

```
#¿s4 £Uf"[^\\v]+|.+
?" gX

```

The `¿` should be the raw char U+0093. Input is a multi-line string, one word/line. Try it online!

**EDIT:** I've now added the non-vowel class `\V` and a way around `\\` (with `%`), so this code now works for **21 bytes**: (Try it online)

```
#¿s4 £Uf"%V+|.+
?" gX

```

### How it works

```
                     // Implicit: U = input string
#¿s4                 // Convert the char code (147) into a base-4 string "2103".
     £               // Map each char X in this string to:
      Uf"[^\\v]+|.+  //  Match each group in U of non-vowels or non-newlines,
?"                   //  with an optional trailing newline.
   gX                //  Get the item at position X in the resulting array.
                     // Implicit: output last expression

```

### Old version (26 bytes):

```
UrA="\\b[^\\v ]+"@UfA gÂ!Y

```

Try it online!

### How it works

```
UrA="\\b[^\\v ]+"@UfA gÂ!Y  // Implicit: U = input string
  A="\\b[^\\v ]+"           // Set variable A to this regex string, which matches
                            // a word boundary followed by one or more non-vowels.
UrA              @          // Take U and replace each match X of A and its index Y with:
                  UfA       //  Take U.match(A).
                      gÂ!Y  //  Get the item at index ~~!Y (converts 0 to 1, anything else to 0).
                            // Implicit: output last expression

```

# Answer
> 4 votes
# Python 3, 100 (or 99) bytes

```
import re
def f(*g):a,b=[re.split("[aeiou]",r)[0] for r in g];return b+g[0][len(a):],a+g[1][len(b):]

```

Played with a few versions but can't seem to get it below. Can get it down 99 bytes by using `def f(g)` instead so it takes a list of strings rather than two seperate strings, but I prefer the two arg roue.

The alternative is equal length:

```
import re
s=re.split
def f(x,y):v="[aeiou]";a,b=s(v,x)[0],s(v,y)[0];return b+x[len(a):],a+y[len(b):]

```

I tried replace, like @TanMath uses, but I couldn't get it any shorter. Also, TanMath can get his answer shorter by a byte by also using `"[aeiou]"` instead of `"[aeiou]+"` because we only need to match the single instances. Finally, the implementation of `input()` seems to have changed between py2 and py3 - it automatically evaluates stdin as a string.

# Answer
> 3 votes
# C#6, 165 bytes

```
string S(string a,string b){int i=V(a),j=V(b);return b.Remove(j)+a.Substring(i)+" "+a.Remove(i)+b.Substring(j);}int V(string s)=>s.IndexOfAny("aeiou".ToCharArray());

```

Expanded:

```
string S(string a,string b){
    int i=V(a),
        j=V(b);
    return b.Remove(j)+a.Substring(i)+" "+a.Remove(i)+b.Substring(j);
}
int V(string s)=>s.IndexOfAny("aeiou".ToCharArray());

```

# Answer
> 3 votes
# JavaScript (ES6), ~~120~~ ~~107~~ ~~102~~ ~~101~~ ~~99~~ 92 bytes

* Thanks downgoat!

This takes into account if the parameters were an object like this, and backward:
`var a = {x: "man", y:"plaster"]}`

```
a.b=(e=>e.slice(e.search`[aeiou]`));with(a){c=b(x),d=b(y),x=x.replace(c,d);y=y.replace(d,c)}

```

# Answer
> 3 votes
# Python, ~~129~~ ~~108~~ ~~105~~ 109 bytes

This program takes in a list of words like this `["master","plan"]`

**EDIT**: Thanks @Volatility

**EDIT:** Now using re.split

```
import re
a=re.split
c='[aeiou]+'
i,j=input()
f=a(c,i)[0]
l=a(c,j)[0]
print i.replace(f,l,1),j.replace(l,f,1)

```

This answer uses regex as most of them do.

Try it here

# Answer
> 3 votes
# , 24 chars / 42 bytes

```
ïē/⟮(⁅ᶌ]+)⟯(.+ )Ⅰ/,`⑶⑵⑴`

```

`Try it here (Firefox only).`

If you need help comprehending this, this translates to ES6 as

```
input.replace(/([^aeiou]+)(.+ )([^aeiou]+)/g,'$3$2$1')

```

# Answer
> 3 votes
# PowerShell, 52 bytes

```
"$args "-replace('(.*?)([aeiou]\S+) '*2),'$3$2 $1$4'

e.g.
PS C:\scripts\> .\Spoonerise.ps1 'blushing crow'
crushing blow

```

It's a regex replace with four capture groups; with:

* String multiplication to expand:
    + `('(.*?)([aeiou]\S+) '*2)` to `'(.*?)([aeiou]\S+) (.*?)([aeiou]\S+) '`
* The `"$args "` forces the args array into a string, and adds a trailing space so the trailing space in the regex won't break it.

# Answer
> 3 votes
# Java 8, 343 Bytes

Here you have your first Java-Answer. Not that experienced with golfing, so every suggestion is appreciated!

```
java.util.function.Function;public class C{public static void main(String[] a){Function<String, Integer>f=s->{for(int i=0;i<s.length();++i)if("aeiou".contains(s.substring(i,i+1)))return i;return 0;};int i1=f.apply(a[0]),i2=f.apply(a[1]);System.out.println(a[1].substring(0,i2)+a[0].substring(i1)+" "+a[0].substring(0,i1)+a[1].substring(i2));}}

```

Ungolfed:

```
public class SpooneriseWords {
    public static void main(String[] args)
    {
        Function<String, Integer> f = s -> {
            for(int i = 0; i < s.length(); ++i)
                if("aeiou".contains(s.substring(i, i + 1)))
                    return i;
            return 0;
        };

        int i1 = f.apply(args[0]);
        int i2 = f.apply(args[1]);
        System.out.println(args[1].substring(0, i2) + args[0].substring(i1));
        System.out.println(args[0].substring(0, i1) + args[1].substring(i2));
    }
}

```

# Answer
> 3 votes
## Octave, 96 bytes

Thanks to Octave's inline assignments and 'index-anywhere' functionality, this entire thing is just the definition of a single, anonymous function. Basically, we reconstruct the spoonerized string while storing the cut-off points in `a` and `b`. I'm especially happy with the inline `f` function, which finds the cut-off point, and prevented me from having to use the whole '`find(ismember(a,b),1)`' thing twice. Also, **no regex :)**.

```
@(p,q)[q(1:(a=(f=@(m)find(ismember(m,'aeoui'),1))(q))-1),p(b=f(q):end),32,p(1:b-1),q(a:end)];

```

# Answer
> 3 votes
# Python (no regexes), 85 bytes

```
t=lambda s:s[1]in'aeiou'or-~t(s[1:])
lambda a,b:(b[:t(b)]+a[t(a):],a[:t(a)]+b[t(b):])

```

Sample run:

```
>>> t=lambda s:s[1]in'aeiou'or-~t(s[1:])
>>> lambda a,b:(b[:t(b)]+a[t(a):],a[:t(a)]+b[t(b):])
<function <lambda> at 0x7f495e534398>
>>> _('plaster', 'man')
('master', 'plan')

```

`t` is a recursive function that computes the index of the earliest vowel after the first character in its argument `s`. If the second character `s[1]` is a vowel, it evaluates to `True`, which has `int` value `1`. Otherwise it makes a recursive call with the first character removed, and adds 1 to the resulting index using `-~` (two’s complement of one’s complement). Finally, the results of `t` are used as indices for string slicing to compute the spoonerism.

# Answer
> 2 votes
# Pyth, ~~30~~ 28 bytes

Takes input and gives output as a list of the two words.

```
ACm,Kh:d"[aeiou]"3.-dKQ+V_GH

```

Try it online.

# Answer
> 2 votes
# TeaScript, 27 bytes

```
xg/(\w+)(.+ )(\w+)/,"$3$2$1

```

`\w` is actually `[^aeiou]`.

# Answer
> 2 votes
# PowerShell, 61 bytes

```
"$args"-replace'([^aeiou]+)(.*)\s([^aeiou]+)(.*)','$3$2 $1$4'

```

Uses regex to swap the first non-vowel characters of each word

# Answer
> 2 votes
# Elixir, ~~143~~ 117 Bytes

```
s=fn w->String.split_at(w,elem(hd(Regex.run(~r/[aeiou]/,w,return: :index)),0))end
{v,w}=s.(a)
{x,y}=s.(b)
[x<>w,v<>y]

```

Split up the two strings (a, b) on the first vowel and construct new strings to return.

EDIT: Got a few bytes off by using pattern matching instead of clunky `elem` calls to get the values out of the tuples.

# Answer
> 2 votes
# Java, 147 Bytes

I'm assuming just a function is fine too.

```
String s(String[]i){String r="[aeiou]",f=i[0].split(r)[0],s=i[1].split(r)[0];return s+i[0].substring(f.length())+" "+f+i[1].substring(s.length());}

```

`split(regex)` unfortunately consumes the delimiter, which means that I have to use `substring` to get the suffixes.

# Answer
> 2 votes
## Brainfuck, 141 bytes

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

```

Formatted:

```
,
[
  [
    [<+> >+<-]
    ----[>-----<--]>+
    [
      not u
      ++++++
      [
        not o
        ++++++
        [
          not i
          ++++
          [
            not e
            ++++
            [
              not a
              ,>
            ]
          ]
        ]
      ]
    ]
    <
  ]
  <[>+<-]>>>+
  [
    ,
    [
      [<+> >+<-]
      ++++[>--------<-]
    ]
    >
  ]
  >,
]
<<<<
[
  [<]<[<]
  >[.,+>]
  +<
]
>[-[+.,]>]

```

Expects the two words separated by a space, with or without a trailing newline.

Try it online.

This takes the input and stores it on the tape with three zero cells added: one before the first vowel of each word, and one after the space between the two words. For example, `plaster man` becomes:

`pl\x00aster \x00m\x00an`

The three fragments `m`, `aster`, and `pl` are then printed by looping backwards through the tape while creating dummy `\x01` cells, and the final `an` is printed by going forwards and ignoring the dummy cells.

# Answer
> 2 votes
# Husk, <sup>~~24 19~~</sup> 17 bytes

```
mΣTΓo:↔Tmoġ€¨aeıu

```

Try it online!

-5 bytes from Dominic Van Essen.

-2 bytes using Γ.

## Explanation

```
mΣTΓo:↔  Tmoġ€¨aeıu
          mo             map each string to the following:
            ġ            group by
             €¨aeıu      vowel groups
         T               transpose
   Γo:                   prepend
      ↔                  the first row reversed
                         to the rest of the array
  T                      transpose back
mΣ                       concatenate into words

```

# Answer
> 1 votes
# GNU Awk 4.0, 48 characters

```
split($0,a,/\<[^aeiou]+/,s)&&$0=s[2]a[2]s[1]a[3]

```

Sample run:

```
bash-4.3$ for s in 'plaster man' 'blushing crow' 'litigating more' 'strong wrangler' 'def ghi'; do
>     echo -n "$s -> "
>     awk 'split($0,a,/\<[^aeiou]+/,s)&&$0=s[2]a[2]s[1]a[3]' <<< "$s"
> done
plaster man -> master plan
blushing crow -> crushing blow
litigating more -> mitigating lore
strong wrangler -> wrong strangler
def ghi -> ghef di

```

# Answer
> 1 votes
# Lua, 80 bytes

```
function f(a)return a:gsub('([^aeiou]*)(.*)%s([^aeiou]*)(.*)','%3%2 %1%4'),''end

```

You can test it here.

Ungolfed:

```
function f( a )
    return a:gsub(
        '([^aeiou]*)(.*)%s([^aeiou]*)(.*)', -- Get non-vowels, anything else, space, repeat
        '%3%2 %1%4' -- Re-arrange captures
    ),'' -- Get rid of number of gsubs (1)
end

```

You need to print the output, of course, which would add some more bytes.

# Answer
> 1 votes
# 05AB1E (legacy), 20 bytes

```
ε.œ2ùʒнDžMмQ}θ}ø`R+R

```

I/O as a pair of strings.

Try it online or verify all test cases.

**Explanation:**

```
ε            # Map both strings in the (implicit) input-list to:
 .œ          #  Get all partitions of the current string
   2ù        #  Only keep the partitions of size 2
             #   i.e. "plaster" → [["p","laster"],["pl","aster"],["pla","ster"],
             #    ["plas","ter"],["plaste","r"]]
     ʒ       #  Filter these partitions by:
      н      #   Pop and push the first substring
       D     #   Duplicate it
        žMм  #   Remove all vowels
           Q #   And check whether it's still equal to the duplicated substring
     }θ      #  After the filter: pop and push the last 2-part partition
             #   i.e. [["p","laster"],["pl","aster"]] → ["pl","aster"]
}ø           # After the map: zip/transpose the list of 2-part partitions
             #  i.e. [["pl","aster"],["m","an"]] → [["pl","m"],["aster","an"]]
  `          # Then push both pairs separated to the stack
   R         # Reverse the second pair
             #  → ["an","aster"]
    +        # Append the substrings at the same indices
             # (which is why we use the legacy version built in Python,
             # where `+` can be used to append strings vectorized)
             #  → ["plan","master"]
     R       # And then reverse the resulting pair
             #  → ["master","plan"]
             # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# Zsh, 79 bytes

Non-regex solution, using param expansion

```
m=${(SB)1#[aeiou]}-1;n=${(SB)2#[aeiou]}-1
<<<${2:0:$n}${1:$m}\ ${1:0:$m}${2:$n}

```

Try it Online!

~~original, 121 bytes~~

# Answer
> 1 votes
# Julia, ~~51~~ 55 bytes

I was happy to find a 78-byte solution, then I saw this answer by Dennis. So, here it is in Julia.

Edit: fixed multiple match

```
w->replace(w,Regex('^'*"([^aeiou]+|.+ )"^3)=>s"\3\2\1")

```

Try it online!

(My 78-byte, non-regex solution:)

```
f(w,v=findfirst.(in("aeuio"),w))=[w[3-i][1:v[3-i]-1]*w[i][v[i]:end] for i=1:2]

```

Try it online!

# Answer
> 0 votes
# **Python 162**

```
p,q=raw_input().split()
a=b=-1
c=d=0
v='aeiou'
while a<0:
 if p[c]in v:
  a=c
 c+=1
while b<0:
 if q[d]in v:
  b=d
 d+=1
print " ".join((q[:b]+p[a:],p[:a]+q[b:]))

```

# Answer
> 0 votes
# Matlab 169

```
q=strsplit(input('','s'),' ');n=Inf(1,2);for e=1:2;for w='aeiou';n(e)=min([n(e),find(q{e}==w)]);end;end;[q{2}(1:n(2)-1),q{1}(n(1):end),' ',q{1}(1:n(1)-1),q{2}(n(2):end)]

```

Seeks for vowels in loops and finds the first in each word. Then swaps letters

Test:

```
litigating more
ans =
mitigating lore

def ghi
ans =
ghef di

```

# Answer
> 0 votes
## Haskell, 55 bytes

```
f w|[(a,b),(c,d)]<-break(`elem`"aieou")<$>w=[c++b,a++d]

```

An adaptation of this answer. Input and output is a list of two strings.

Each input is broken into two pieces at the appearance of the first vowel. Then, having assigned names to the four pieces in a guard, they are recombined and outputed.

# Answer
> 0 votes
# PHP 405 325

Minified:

```
<?php
function c($i){$c=[];$l=0;while(!in_array(substr($i,$l,1),['a','e','i','o','u'])&&$l<strlen($i)){$c[]=substr($i,$l,1);++$l;}return $c;}list(,$a,$b)=$argv;$z=c($a);$x=c($b);$a=implode('',$x).substr($a,count($z),strlen($a)-count($z));$b=implode('',$z).substr($b,count($x),strlen($b)-count($x));echo $a.' -> '.$b.PHP_EOL;

```

Original code:

```
<?php
function find_first_consonants($str) {
    $consonants = [];
    $loop = 0;
    while(!in_array(substr($str, $loop, 1), [ 'a', 'e', 'i', 'o', 'u' ]) && $loop < strlen($str)) {
        $consonants[] = substr($str, $loop, 1);
        ++$loop;
    }
    return $consonants;
}
list( , $strA, $strB ) = $argv;
$consonantsA = find_first_consonants($strA);
$consonantsB = find_first_consonants($strB);
$newStrA        = implode('', $consonantsB) . substr($strA, count($consonantsA), strlen($strA) - count($consonantsA));
$newStrB        = implode('', $consonantsA) . substr($strB, count($consonantsB), strlen($strB) - count($consonantsB));
echo $newStrA . ' -> ' . $newStrB . PHP_EOL;

```

# Answer
> 0 votes
# Io, 141 bytes

Surprised that this is actually so long.

```
method(r,r :=r map(x,x splitAt("aeiou"asList map(j,x asList indexOf(j))min))flatten reverse;list(r slice(1,3)join,list(r at(3),r at(0))join))

```

Try it online!

# Answer
> 0 votes
# Japt v2.0a0, ~~17~~ 13 bytes

I/O as an array of strings

```
mòÏè\vÃÕvÔÕmq

```

Try it

```
mòÏè\vÃÕvÔÕmq     :Implicit input of array
m                 :Map
 ò                :  Partition before characters that return truthy
  Ï               :  When passed through the following function
   è              :    Count
    \v            :    RegEx /[aeiou]/gi
      Ã           :End partition and map
       Õ          :Transpose
        v         :Modify first element
         Ô        :  Reverse
          Õ       :Transpose
           m      :Map
            q     :  Join

```

# Answer
> 0 votes
# Lexurgy, 75 bytes

```
a:
((!{a,e,i,o,u})+)$1 ([]*)$2 . ((!{a,e,i,o,u})+)$3 ([]*)$4=>$3 $2 . $1 $4

```

Input and output is period-separated (`plaster.man`) due to how Lexurgy handles whitespace.

# Answer
> 0 votes
# sed, 44 bytes

```
s/([^aeiou]+)(.+) ([^aeiou]+)(.+)/\3\2 \1\4/

```

Try it online!

---
Tags: code-golf, string, natural-language
---


title: Approximation of e

text:
# Question
Title: Approximation of e
We all know that the Euler's number, denoted by \\$e\\$, to the power of some variable \\$x\\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum\_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \\$x\\$ equal \\$1\\$, we obtain

$$\sum\_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

## Challenge

Write a program in any language which approximates Euler's number by taking in an input \\$n\\$ and calculates the series to the \\$n\\$th term. Note that the first term has denominator \\$0!\\$, not \\$1!\\$, i.e. \\$n=1\\$ corresponds to \\$\frac{1}{0!}\\$.

## Scoring

Program with least amount of bytes wins.

# Answer
> 13 votes
# Jelly, 5 bytes

```
R’!İS

```

Try it online!

### How it works

```
R’!İS  Main link. Argument: n

R      Yield the range [1, ..., n].
 ’     Map decrement over the list.
  !    Map factorial over the list.
   İ   Map inverse over the list.
    S  Compute the sum.

```

# Answer
> 15 votes
# Wistful-C \- 336 bytes

My first real wistful- program! There is actually a little golfing I did, with using `someday` instead of `wait for` because the first had a shorter length.

```
if only <stdio.h> were included...
if only int f were 1...
if only int N were 0...
wish for "%d",&N upon a star
if only int i were 0...
if only double e were 0...
someday i will be N...
        if only e were e+1./f...
        if only i were i+1...
        if only f were f*i...
*sigh*
wish "%f\n",e upon a star
if wishes were horses...

```

# Answer
> 11 votes
## Pyth, ~~7~~ 6 bytes

```
smc1.!

```

Try it here.

```
 m      map over range 0..input:
    .!  factorial
  c1    1 / ^
s       sum

```

Thanks to FryAmTheEggman for a byte!

# Answer
> 10 votes
# Julia 0.6, ~~28~~ ~~27~~ 21 bytes

```
n->sum(1./gamma(1:n))

```

Try it online!

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

The approach is quite straightforward. We `sum` 1 divided by the gamma function evaluated at each of 1 through *n*. This takes advantage of the property *n*! = Γ(*n*+1).

Saved 1 byte thanks to Dennis and 6 thanks to Glen O!

# Answer
> 10 votes
# TI-84 BASIC, 12 15 14

```
Input N
Σ(A!⁻¹,A,0,N

```

TI is a tokenized language (bytes are counted via tokens, not individual characters).

# Answer
> 6 votes
## Python, 36 bytes

**Python 2:**

```
f=lambda n,i=1:n/i and 1.+f(n,i+1)/i

```

**Python 3:**

```
f=lambda n,i=1:i<=n and 1+f(n,i+1)/i

```

# Answer
> 6 votes
# dc, 43 bytes

```
[d1-d1<f*]sf[dlfx1r/r1-d1<e+]se1?dk1-d1<e+p

```

This is a fairly direct translation of the series. I tried to be cleverer, but that resulted in longer code.

## Explanation

```
[d1-d1<f*]sf

```

A simple factorial function, for n\>0

```
[dlfx1r/r1-d1<e+]se

```

Execute the factorial for n,...,1; invert and sum

```
1?dk1-

```

Prime the stack with 1; accept input and set an appropriate precision

```
d1<e+

```

If input was 0 or 1, we can just pass it on, else compute the partial sum.

```
p

```

Print the result.

## Test results

The first 100 expansions:

```
0
1
2
2.500
2.6666
2.70832
2.716665
2.7180553
2.71825394
2.718278766
2.7182815251
2.71828180110
2.718281826194
2.7182818282857
2.71828182844671
2.718281828458223
2.7182818284589936
2.71828182845904216
2.718281828459045062
2.7182818284590452257
2.71828182845904523484
2.718281828459045235331
2.7182818284590452353584
2.71828182845904523536012
2.718281828459045235360273
2.7182818284590452353602862
2.71828182845904523536028736
2.718281828459045235360287457
2.7182818284590452353602874700
2.71828182845904523536028747123
2.718281828459045235360287471339
2.7182818284590452353602874713514
2.71828182845904523536028747135253
2.718281828459045235360287471352649
2.7182818284590452353602874713526606
2.71828182845904523536028747135266232
2.718281828459045235360287471352662481
2.7182818284590452353602874713526624964
2.71828182845904523536028747135266249759
2.718281828459045235360287471352662497738
2.7182818284590452353602874713526624977552
2.71828182845904523536028747135266249775705
2.718281828459045235360287471352662497757231
2.7182818284590452353602874713526624977572453
2.71828182845904523536028747135266249775724691
2.718281828459045235360287471352662497757247074
2.7182818284590452353602874713526624977572470919
2.71828182845904523536028747135266249775724709352
2.718281828459045235360287471352662497757247093683
2.7182818284590452353602874713526624977572470936984
2.71828182845904523536028747135266249775724709369978
2.718281828459045235360287471352662497757247093699940
2.7182818284590452353602874713526624977572470936999574
2.71828182845904523536028747135266249775724709369995936
2.718281828459045235360287471352662497757247093699959554
2.7182818284590452353602874713526624977572470936999595729
2.71828182845904523536028747135266249775724709369995957475
2.718281828459045235360287471352662497757247093699959574944
2.7182818284590452353602874713526624977572470936999595749646
2.71828182845904523536028747135266249775724709369995957496673
2.718281828459045235360287471352662497757247093699959574966943
2.7182818284590452353602874713526624977572470936999595749669652
2.71828182845904523536028747135266249775724709369995957496696740
2.718281828459045235360287471352662497757247093699959574966967601
2.7182818284590452353602874713526624977572470936999595749669676254
2.71828182845904523536028747135266249775724709369995957496696762747
2.718281828459045235360287471352662497757247093699959574966967627699
2.7182818284590452353602874713526624977572470936999595749669676277220
2.71828182845904523536028747135266249775724709369995957496696762772386
2.718281828459045235360287471352662497757247093699959574966967627724050
2.7182818284590452353602874713526624977572470936999595749669676277240739
2.71828182845904523536028747135266249775724709369995957496696762772407632
2.718281828459045235360287471352662497757247093699959574966967627724076601
2.7182818284590452353602874713526624977572470936999595749669676277240766277
2.71828182845904523536028747135266249775724709369995957496696762772407663006
2.718281828459045235360287471352662497757247093699959574966967627724076630325
2.7182818284590452353602874713526624977572470936999595749669676277240766303508
2.71828182845904523536028747135266249775724709369995957496696762772407663035328
2.718281828459045235360287471352662497757247093699959574966967627724076630353518
2.7182818284590452353602874713526624977572470936999595749669676277240766303535449
2.71828182845904523536028747135266249775724709369995957496696762772407663035354729
2.718281828459045235360287471352662497757247093699959574966967627724076630353547565
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475915
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759429
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594542
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945681
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457111
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571352
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713792
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138185
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382143
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821752
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217826
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178492
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785218
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852481
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525131
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251635
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516607
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166394

```

Using 1000 terms:

```
2.7182818284590452353602874713526624977572470936999595749669676277240\
766303535475945713821785251664274274663919320030599218174135966290435\
729003342952605956307381323286279434907632338298807531952510190115738\
341879307021540891499348841675092447614606680822648001684774118537423\
454424371075390777449920695517027618386062613313845830007520449338265\
602976067371132007093287091274437470472306969772093101416928368190255\
151086574637721112523897844250569536967707854499699679468644549059879\
316368892300987931277361782154249992295763514822082698951936680331825\
288693984964651058209392398294887933203625094431173012381970684161403\
970198376793206832823764648042953118023287825098194558153017567173613\
320698112509961818815930416903515988885193458072738667385894228792284\
998920868058257492796104841984443634632449684875602336248270419786232\
090021609902353043699418491463140934317381436405462531520961836908887\
070167683964243781405927145635490613031072085103837505101157477041718\
986106873969655212671546889570350116

```

# Answer
> 5 votes
# J, 10 bytes

```
[:+/%@!@i.

```

Straight-forward approach.

## Explanation

```
[:+/%@!@i.    Input: n
        i.    Creates the range [0, 1, ..., n-1]
      !@      Maps factorial to each
    %@        Map 1/x to each
[:+/          Take the sum of the values and return it

```

# Answer
> 4 votes
# MATL, ~~11~~ 7 bytes

```
:Ygl_^s

```

*4 bytes saved thanks to @Luis's recommendation to use `gamma` (`Yg`)*

**Try it Online**

**Explanation**

```
        % Implicitly grab input (N)
:       % Create an array from 1...N
Yg      % Compute factorial(x-1) for each element (x) in the array
l_^     % Take the inverse
s       % Sum all elements
        % Implicitly display the result

```

# Answer
> 4 votes
# JavaScript ES6, ~~44 42~~ 40

```
n=>{for(k=s=m=1;m<n;s+=k/=m++);return s}

```

An unnamed function now.

Thanks for saving 2 bytes @AlexA and thanks to @LeakyNun for another 2 bytes!

# Answer
> 4 votes
# CJam, 11

```
r~,:m!Wf#:+

```

or

```
r~{m!W#}%:+

```

Try it online: first version and second version

**Explanation:**

`r~` = read and evaluate
`m!` = factorial
`W#` = raise to the -1 power (`W` = -1)
`:+` = sum of array
First version constructs the \[0…N-1\] array and applies factorial and inverse to all its elements; 2nd version does factorial and inverse for each number then puts them in an array.

# Answer
> 4 votes
# MATL, 6 bytes

```
q_t1Zh

```

This computes the sum using the hypergeometric function 1*F*1(*a*;*b*;*z*):

Works on Octave and on the online compiler, but not on Matlab, due to a difference in how the hypergeometric function is defined (which will be corrected).

**Try it online!**

### Explanation

```
q_    % Take N implicitly. Compute -N+1
t     % Duplicate
1     % Push 1
Zh    % Hypergeometric function 1F1(-N+1;-N+1;1). Implicitly display

```

# Answer
> 4 votes
# C, 249 bytes

```
#include <stdio.h>
#include <stdlib.h>
#define z double
z f(z x){z r=1;z n=1;while(x>0){r*=n;n++;x--;}return r;}int main(int argc, char **argv){z e=0;z p=0;z d=0;p=strtod(argv[1],NULL);while(p>0){e+=1.0d/f(d);printf("%.10f\n",e);p--;d++;}return 0;}

```

Ungolfed:

```
/* approximate e */

#include <stdio.h>
#include <stdlib.h>

double fact(double x){
    double result = 1;
    double num = 1;

    while (x > 0){
        result *= num;
        num++;
        x--;
    }
    return result;
}

int main(int argc, char **argv){
    double e = 0;
    double precision = 0;
    double denom = 0;

    precision = strtod(argv[1], NULL);
    while (precision > 0){
        e += 1.0d / fact(denom);
        printf("%.10f\n", e);
        precision--;
        denom++;
    }
    return 0;
}

```

Takes a number as an argument to determine number of iterations.

# Answer
> 4 votes
# APL (Dyalog Unicode), 5 bytes

```
⍳⊥⊢÷!

```

Try it online!

Using the mixed base trick found in my answer of another challenge. Uses `⎕IO←0`.

### How it works

```
⍳⊥⊢÷!  Right argument: n, the number of terms
  ⊢÷!  v: 1÷(n-1)!
⍳      B: The array of 0 .. n-1
 ⊥     Expand v to length-n array V,
       then mixed base conversion of V in base B

Base | Digit | Value
--------------------
0    | v     | v×(1×2×..×(n-1)) = 1÷0!
1    | v     | v×(2×3×..×(n-1)) = 1÷1!
2    | v     | v×(3×..×(n-1))   = 1÷2!
..   | ..    | ..
n-2  | v     | v×(n-1)          = 1÷(n-2)!
n-1  | v     | v                = 1÷(n-1)!

```

# Answer
> 3 votes
## Pyke, 10 bytes

```
FSBQi^R/)s

```

Try it here!

Or 8 bytes if power=1

```
FSB1R/)s

```

Try it here!

# Answer
> 3 votes
# k (13 bytes)

Subject to overflows for `N>20`

```
{+/%*\1,1+!x}

```

# Answer
> 3 votes
## 05AB1E, 6 bytes

```
$L<!/O

```

**Explained**

```
$           # push 1 and input: N = 5
 L<         # range [0..N-1]: [0,1,2,3,4]
   !        # factorial over range [1,1,2,6,24]
    /       # divide 1/range: [1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664]
     O      # sum: 2.708333333333333

```

Try it online

# Answer
> 3 votes
## Haskell, 37 bytes

```
((scanl(+)0$(1/)<$>scanl(*)1[1..])!!)

```

Not the shortest, but arguably the prettiest.

---

Also courtesy of Laikoni, here is a solution that is **2 bytes** shorter:

```
sum.(`take`((1/)<$>scanl(*)1[1..]))

```

---

```
λ> let f = ((scanl (+) 0 $ (1/) <$> scanl (*) 1 [1..]) !!)

λ> map f [1..5]
[1.0,2.0,2.5,2.6666666666666665,2.708333333333333]

λ> f 10
2.7182815255731922

λ> f 100
2.7182818284590455

λ> log (f 10)
0.9999998885745155

λ> log (f 100)
1.0

```

# Answer
> 3 votes
# Dyalog APL, 6 bytes

```
+/÷!⍳⎕

```

`+/` sum of
`÷` the reciprocals of
`!` the factorials of
the numbers from 0 to
numerical input

Assumes `⎕IO←0`, which is default on many systems.

TryAPL!

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

```
f=(n,i=1)=>n&&1+f(n-1,i+1)/i

```

# Answer
> 3 votes
# Raku, ~~21~~ 19 bytes

```
{1+sum [\/] 1..^$_}

```

Try it online!

*-2 bytes thanks to Jo King*

`[\/]` performs a "triangular reduction" (or "scan") using the division operator over the sequence `1, 2, ..., $_-1` (where `$_` is the argument to the function). So for example `[\/] 1..4` is the sequence `1`, `1/2`, `1/2/3`, `1/2/3/4`, which are the terms required for the `n = 5` case.

# Answer
> 3 votes
# jq, 25 bytes

```
[range(.)+1|1/tgamma]|add

```

Try it online!

jq currently only has IEEE754 double-precision (64-bit) floating point number support, luckily it works in its favour here.

# Answer
> 2 votes
## Actually, 6 bytes

```
r♂!♂ìΣ

```

Try it online!

Explanation:

```
r♂!♂ìΣ
r       range(N) ([0, N-1])
 ♂!     factorial of each element
   ♂ì   reciprocal of each element
     Σ  sum

```

# Answer
> 2 votes
# Brachylog, 18 bytes

```
:1-:0r:ef:$!a:/a+.

```

### Explanation

```
:1-                 Subtract 1 from Input
   :0r              Create the list [0, Input - 1]
      :ef           Find all integers between 0 and Input - 1
         :$!a       Apply factorial to each member of that list
             :/a    Apply inverse to each element of that list
                +.  Unify the output with the sum of the list

```

# Answer
> 2 votes
# Java with Ten Foot Laser Pole, ~~238~~ 236 bytes

```
import sj224.tflp.math.*;interface U{static void main(String[]a){BigRational r=null,s,t;r=s=t=r.ONE;for(int n=new java.util.Scanner(System.in).nextInt()-1;n-->0;){t=t.multiply(r);s=s.add(t.pow(-1));r=r.add(r.ONE);}System.out.print(s);}}

```

Has much better overflow resistance than most of the other answers. For 100 terms, the result is

```
31710869445015912176908843526535027555643447320787267779096898248431156738548305814867560678144006224158425966541000436701189187481211772088720561290395499/11665776930493019085212404857033337561339496033047702683574120486902199999153739451117682997019564785781712240103402969781398151364608000000000000000000000

```

# Answer
> 2 votes
# Maple, 18

```
add(1/i!,i=0..n-1)

```

Usage:

```
> f:=n->add(1/i!,i=0..n-1);
> f(1);
  1
> f(4);
  8/3

```

# Answer
> 2 votes
# C, 69 bytes

```
double f(int n){double s=1,f=1;for(int i=0;i++<n;s+=f)f/=i;return s;}

```

Ideone it!

# Answer
> 2 votes
# Julia 0.6, 28 bytes

```
~k=k<1?1:1/gamma(k+1)+~(k-1)

```

Try it online!

## Explanation

```
~k=                    #Define ~ to be
    k<1                #If k is less than 1
        ?1             #to be one
        :1/gamma(k+1)  #else add the reciprocal factorial to
            +~(k-1)    #the function applied to the predecessor value

```

`gamma(k+1)` is equal to `factorial(k)` for positive integer inputs, and generalizes it for all values other than the nonnegative integers. It saves one byte, so why not use it?

# Answer
> 2 votes
# PowerShell Core, ~~51~~ 43 bytes

```
param($a)++$p..$a-ge1|%{$s+=$p/=$_}
$s+!!$a

```

Try it online!

-6 bytes thanks to *mazzy*! -2 bytes thanks to *Zaelin Goodman*!

# Answer
> 2 votes
# Thunno 2 `S`, 3 bytes

```
LwỊ

```

Try it online!

#### Explanation

```
LwỊ  # Implicit input
L    # Lowered range
 w   # Factorial
  Ị  # Reciprocal
     # Sum
     # Implicit output

```

# Answer
> 1 votes
# MATLAB / Octave, 22 bytes

```
@(x)sum(1./gamma(1:x))

```

Creates an anonymous function named `ans` that can be called using `ans(N)`.

This solution computes `gamma(x)` for each element in the array \[1 ... N\] which is equal to `factorial(x-1)`. We then take the inverse of each element and sum all elements.

**Online Demo**

# Answer
> 1 votes
# Perl 5, 37 bytes

Not a winner, but nice and straightforward:

```
$e=$p=1;$e+=1/($p*=$_)for 1..<>;say$e

```

Outputs for inputs from 0 to 10:

```
1
2
2.5
2.66666666666667
2.70833333333333
2.71666666666667
2.71805555555556
2.71825396825397
2.71827876984127
2.71828152557319
2.71828180114638

```

# Answer
> 1 votes
## R, 17 bytes

```
sum(1/gamma(1:n))

```

Quite straightforward, although numerical precision issues are bound to arise at some point in time.

# Answer
> 1 votes
# WolframAlpha, 12 bytes

```
sum1/k!,0..n

```

# Answer
> 1 votes
## F#, 87 bytes

```
let rec f x=if x<2 then 1 else f(x-1)*x
let e N=Seq.sumBy(fun x->1./float(f x)){0..N-1}

```

Try it online!

A direct implementation of the Maclaurin expansion. Unfortunately over 35 terms the denominator is too small, so the sum becomes infinity.

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

```
n=>{for(a=d=i=1;i<=n;a+=1/d)d/=i++;return a}

```

# Answer
> 1 votes
# Ruby, ~~43~~ 42 bytes

-1 byte by calculating using `Rational` instead of `Float`.

```
->n{(0..n).sum{|i|1/(1..i).reduce(1r,:*)}}

```

Try it online!

# Answer
> 1 votes
# Stax, 5 bytes

```
òo⌠├p

```

Run and debug it

Produces output as a fraction.

# Answer
> 1 votes
# cQuents, 7 bytes

```
;1/f_-$

```

Try it online!

# Explanation

```
;           Series - output sum of first n terms in sequence
            Each term is
 1/                      1 /
   f   )                     factorial (           )
    _-                                         - 1
      $                                  index

```

# Answer
> 1 votes
# Mathematica, 26 bytes

```
Sum[1/n!,{n,0,Input[]}]//N

```

Pretty straight forward: takes the sum of the inverse of n factorial, with n starting from 0 and all the way to the desired number. The `//N` is used to give an approximate value of the fraction yielded by the sum. The code can be checked online , for free, via the wolfram programming labs:

Wolfram Labs

# Answer
> 1 votes
# k4, ~~16~~ 15 bytes

```
{+/%*/'1_',\!x}

```

---

```
{             } / lambda
            !x  / enumerate x; (!4 -> 0 1 2 3)
          ,\    / join scan; joins successive elements and returns intermediate results (,0;0 1;0 1 2;0 1 2 3)
       1_'      / 1 drop each; drops leading 0s (();,1;1 2;1 2 3)
    */'         / multiply over each; 1 1 2 6
   %            / reciprocal; 1 1 0.5 0.1666667
 +/             / sum

```

# Answer
> 1 votes
# Wren, 81 bytes

```
Fn.new{|N|
var e=0
for(i in 1..N)e=e+1/(1..i).reduce{|a,b|a*b}
return e+1
}

```

Try it online!

# Answer
> 1 votes
# Keg `-rr`, ~~18~~ 15 bytes

```
11(¿|:¡1$/"+"1+

```

Try it online!

This took a whole bunch of fiddling to figure out. It works!!

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
L<!zO

```

Try it online!

```
L<!zO  # full program
    O  # sum of...
   z   # 1 divided by...
  !    # factorial of...
       # (implicit) each element in...
L      # [1, 2, 3, ...,
       # ..., implicit input...
L      # ]...
       # (implicit) with each element...
 <     # decremented
       # implicit output

```

# Answer
> 1 votes
# Husk, 5 bytes

```
ṁo\Πŀ

```

Try it online!

Calculates the sum of the series as a rational number: TIO header converts this to 9 decimal digits (with an implicit point after the first digit).

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

```
ʁ¡Ė

```

Try it Online!

Explanation:

```
     # Implicit input
ʁ    # Range [0, N)
 ¡   # Map factorial over all elements
  Ė  # Map inverse over all elements
     # 's' flag: cumulative sum top of stack and output

```

# Answer
> 1 votes
# Arn `-Rmx`, 3 bytes

```
1/f

```

This can hypothetically be infinitely precise with a large input and the use of the `-p`, `-o`, and `--stack` arguments, as Arn makes use of arbitrarily-precise floating point numbers. Compression doesn't save any bytes here.

# Explained

`-R` transforms input from `N` to the range `[0, N)`. `-m` maps the program over the input

```
1/      Reciprocal of
   f   The factorial function in the global scope (takes `_`)

```

`-x` then sums the result

## Arn (less boring), 10 bytes uncompressed

```
+{1/f}\0->

```

Same concept but without the flags. This is probably **7-8 bytes compressed**, but I'm not at my computer right now and so can't check.

# Answer
> 1 votes
# Ruby, 33 bytes

Returns a rational number. If the we can use 0-indexing, `...` can be shortened to `..`.

```
->n{[k=1,*1...n].sum{|j|1r/k*=j}}

```

Try it online!

# Answer
> 1 votes
# asm2bf, 133 bytes

Requires a 16-bit interpreter, at least 64 tape cells, integer i/o. This all is faciliated using `bfi -d` bundled with asm2bf. Fairly slow, overflows at n=6. Takes `n` in r4. Outputs the result due to a meta consensus.

```
?A=popr1/outr1
@z incr3
psh1
dup
@a movr2,r3
movr1,1
@b cltr2,2
cjn%c
mulr1,r2
decr2
jmp%b
@c pshr1
psh1
fad
incr3
cltr3,r4
cjn%a
A
A

```

Example usage:

```
mov r4, 5
jmp %z

```

Deobfuscated:

```
inc r3
push 1
push 1
@mloop
    mov r2, r3
    mov r1, 1
@loop
    clt r2, 2
    cjnz %done
    mul r1, r2
    dec r2
    jmp %loop
@done
    push r1
    push 1
    fadd
    inc r3
    clt r3, r4
    cjnz %mloop
pop r1
out r1
pop r1
out r1

```

Bonus: optimized brainfuck code:

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

```

To change the output, tweak the first block of `+`.

# Answer
> 1 votes
# Java (JDK)

*note that you can get better results faster by increasing the precision of `MathContext`. This would take up one more byte per power of 10 though. This is why I decided to leave it at `9` If you need to include the `import java.math.*;` that would add another 19 bytes.*

## Using BigDecimals: 241 bytes

```
static BigDecimal c(int n){var o=BigDecimal.ONE;var c=o;for(int i=0;i++<n;)o=o.add(c.divide(f(o.valueOf(i)),new MathContext(9)));return o;}static BigDecimal f(BigDecimal n){var o=n.ONE;return n.compareTo(o)<1?o:f(n.subtract(o)).multiply(n);}

```

Try it online!

## Using primitive Number types: 119 bytes

```
static double c(int n){double v=0;for(int i=0;i<n;)v+=1/f(i++);return v;}static double f(int n){return n<2?1:f(n-1)*n;}

```

Try it online!

Explanation:

```
    static double c(int n){
        double v=0;               // value for e
        for(int i=0;i<n;)         // for n-iterations
            v+=1/f(i++);          // add the inverse
                                  // of the factorial
        return v;                 // return value
    }

    static double f(int n){
        return n<2?1:f(n-1)*n;    // recursively calculates the factorial
    }

```

# Answer
> 1 votes
# Nekomata, 4 bytes

```
rFŗ∑

```

Attempt This Online!

```
rFŗ∑
r       Range
 F      Factorial
  ŗ     Reciprocal
   ∑    Sum

```

# Answer
> 1 votes
# x86-64 machine code, 23 bytes

Expects \\$n\\$ in `rcx` and leaves the result of the approximation in `st0`. The FPU stack is assumed to be empty upon subroutine entry, and only has one value—the result—in it on exit.

Clobbers `rcx`, the FPU stack and flags, and `FLAGS`.

```
d9 e8 d9 e8 d9 e8 eb 0a d9 c1 de c3 d9 e8 de c1 dc f9 e2 f4 da e9 c3

```

Try it online!

## Explanation

The algorithm is essentially the same as @Leaky Nun's answer, just ported to x64 assembly.

```
func:
    fld1 ; load sum to st2 (constant 1.0)
    fld1 ; load term to st1 (constant 1.0)
    fld1 ; load termdiv to st0 (constant 1.0)

    ; first term counts in rcx dec/check too
    jmp func_do_chk

func_loop:
    ; sum += term
    fld st1
    faddp st3, st0

    ; termdiv += 1.0
    fld1
    faddp

    ; term /= termdiv
    fdiv st1, st0

    ; loop back up
func_do_chk:
    loop func_loop

    ; dump st0 and st1 to get sum into st0
    fucompp
    ret

```

# Answer
> 1 votes
# Go, ~~85~~ 84 bytes

```
import."math"
func f(n float64)(S float64){for i:=1.;i<=n;i++{S+=1/Gamma(i)}
return}

```

Attempt This Online!

# Answer
> 0 votes
# Factor \+ `math.factorials math.unicode`, 27 bytes

```
[ iota [ n! -1 ^ ] map Σ ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes an integer from the data stack as input and leaves a ratio approximation of `e` on the data stack as output.

* `iota` Create a range from 0 to the input where the input itself is excluded.
* `[ ... ] map` Apply a quotation to each element of a sequence, collecting the results into a new sequence of the same length.
* `n!` Take the factorial.
* `-1 ^` Take the reciprocal. Shorter than `1 swap /` and `recip`.
* `Σ` Sum a sequence.

# Answer
> 0 votes
# Swift, 71 bytes

```
print(Set(0...n).reduce(0){$0+1/Float(Set(1...max(1,$1)).reduce(1,*))})

```

Try it online!

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


title: Lithp Tranthlator

text:
# Question
Title: Lithp Tranthlator
My friend made a lisp translator the other day, that is to say it took a string and converted s=\>th and S=\>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

**Test case**

```
Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth

```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

# Answer
> 40 votes
## Common Lithp, 62

```
(map()(lambda(u)(princ(case u(#\s"th")(#\S"Th")(t u))))(read))

```

First, `(read)` the input (it should be a string). Strings in CL are sequences so we use `map` to iterate on each character. The first argument to `map` represents the type of the result (e.g. I could build a list from a vector). When it is `nil`, a.k.a. `()`, results are discarded. The function that is mapped to the input simply `princ` (print non-readably) each character, except the ones that should be replaced.

# Answer
> 17 votes
# Retina, 9 bytes

```
S
Th
s
th

```

Try it online!

The obvious answer.

# Answer
> 14 votes
# JavaThcript ETh6, 38 bytes

At first I went with the obvious solution

```
a=>a.replace(/s/g,'th').replace(/S/g,'Th')

```

But I golfed it down 4 bytes

```
a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')

```

This makes use of the regex `i` flag, which searches for case-insensitive patterns. The good thing about Javascript is that you can specify an anonymous function to handle (regex) replacing.

Try it here

```
f=
a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')

s.innerHTML = [
    'abScdsefSghsij',
    'Sam and Sally like Sheep',
    'Sally likes sausages',
    'Sally sells seashells'
].map(c=>c + ' => ' + f(c)).join`<br>`
```

```
<pre id=s>
```

# Answer
> 11 votes
### GNU Sed - 17

```
s/S/Th/g;s/s/th/g

```

The obvious answer.

```
$ sed -e "s/S/Th/g;s/s/th/g"

Sam and Sally like Sheep
Tham and Thally like Thheep

Sally likes sausages
Thally liketh thauthageth

Sally sells seashells
Thally thellth theathhellth

```

# Answer
> 10 votes
# Jelly, 13 bytes

```
“Ss”,“Th“th”y

```

Thhowing off Jelly'th thhiny new tranthlate atom. Try it online!

# Answer
> 8 votes
# Python 3 - 40 byteth

First golfing!

```
lambda s:s.translate({115:'th',83:'Th'})

```

It uses the `str` module's translate method which accepts a translation table. The translation table is a simple `dict` with keycode as keys and the `str` in place of it as value.

# Answer
> 6 votes
## 05AB1E, ~~14~~ 12 bytes

```
's„th:'S„Th:

```

The straight forward answer.

Try it online

Saved 2 bytes thanks to @Adnan

# Answer
> 6 votes
# JavaThcript ETh6, 43 byteth

```
s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])

```

## Tetht Thuite:

```
th=s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])

console.log(th('Sam and Sally like Sheep'));
console.log(th('Sally likes sausages'));
console.log(th('Sally sells seashells'));
```

# Answer
> 6 votes
# , 11 byteth

```
Ís/th
ÍS/Th

```

Try it online!

V ith a language I made. It'th not finithed, but it'th really good at regekth.

# Answer
> 5 votes
# C, 50 bytes

```
s(c){c=getchar();c+=c-83&95?0:'h\1';s(printf(&c));}

```

Replace `\1` with an actual `\x01` byte.

jimmy23013 saved a byte, and then I saved two more using his approach! Thanks.

# Answer
> 4 votes
# Java, 71 65 bytes

```
String t(String s){return s.replace("S","Th").replace("s","th");}

```

First attempt at golfing, so why not with Java.

# Answer
> 4 votes
# TI-Basic, 126 bytes

```
Input Str1
inString(Str1,"s
While Ans
sub(Str1,1,Ans-1)+"th"+sub(Str1,Ans+1,length(Str1)-Ans->Str1
inString(Str1,"s
End
inString(Str1,"S
While Ans
sub(Str1,1,Ans-1)+"Th"+sub(Str1,Ans+1,length(Str1)-Ans->Str1
inString(Str1,"S
End
Str1

```

# Answer
> 4 votes
# Java, 101 byteth

```
interface a{static void main(String[]A){System.out.print(A[0].replace("S","Th").replace("s","th"));}}

```

Note that this is a complete program unlike the previous Java answer.

Bonus (has to be fed to the C preprocessor THEE preprothethor first):

```
#define interfaith interface
#define thtatic static
#define Thtring String
#define Thythtem System
#define replaith(x,y) replace(x,y)

interfaith a{thtatic void main(Thtring[]A){Thythtem.out.print(A[0].replaith("S","Th").replaith("s","th"));}}

```

# Answer
> 4 votes
# GNU AWK, 31 bytes

Just using `gsub` function to translate lower or upper S via regex and print it afterwards. Can work with files, or with `stdin` as in this case

```
$ awk '{gsub(/s/,"th");gsub(/S/,"Th")}1' <<< "This is Sparta"
Thith ith Thparta

```

# Answer
> 4 votes
# 35 Byteth of Julia:

```
s->replace(s,r"s"i,s->"$(s[1]+1)h")

```

Try it online! (includes all test cases)

# Answer
> 4 votes
# C (GCC), 62 byteth

-10 bytes thanks to @ceilingcat; forgot to use the function argument as the iterator.

-1 more byte thanks to @l4m2 and his very smart recursion trick.

```
l(char*s){*s&&l(s+!!putchar(*s&31^19?*s:104+!putchar(*s+1)));}

```

Try It Online!

Explanation:

```
l(char*s)
{
    // If at end of string, do nothing.
    *s&&
        // Else, apply this function to the next character in s ...
        l(s+
            // ... but first, print the current character. If the first
            // five bits of *s equal 19 (which they do for 's' and
            // 'S'), print *s+1 (that is, 't' for 's' and 'T' for 'S')
            // before printing character code 104, which is 'h'.
            // If the first five bits aren't 19, just print *s.
            !!putchar(*s&31^19?*s:104+!putchar(*s+1)));}

```

Alternative 62-byte version, made by l4m2:

```
l(char*s){*s&&l(s+!!printf(*s&31^19?"%c":*s%5?"Th":"th",*s));}

```

Try it online!

I'm too lazy to explain that one fully, but it's quite similar to the last one except it uses two nested conditional statements to figure out if it should print the current character, `Th` or `th`. The new `*s%5` check is used to figure out if `*s` is `'S'` or `'s'` (knowing that it's one of those), since the ASCII code of `s` is divisible by 5 but `'S'` is not.

# Answer
> 3 votes
## Python3 - 46 bytes

```
lambda s:s.replace("s","th").replace("S","Th")

```

Dropped 4 bytes with the help of @DenkerAffe!

# Answer
> 3 votes
## CJam, 15 bytes

```
q"sS""thTh"2/er

```

Test it here.

### Explanation

```
q      e# Read input.
"sS"   e# Push string.
"thTh" e# Push string.
2/     e# Split into pairs, i.e. ["th" "Th"].
er     e# Transliteration, replaces 's' with 'th' and 'S' with 'Th'.

```

# Answer
> 3 votes
# Haskell, 36 bytes

```
f 's'="th";f 'S'="Th";f x=[x]
(>>=f)

```

# Answer
> 3 votes
# PHP, 42 Bytes

if run from a file:

```
<?=strtr($argv[1],["s"=>"th","S"=>"Th"]);

```

Run as:

```
~$ php [file] "This is Silly"

```

# Answer
> 3 votes
# Rust, 46 bytes

```
|s:&str|s.replace("s","th").replace("S","Th");

```

Try it online!

# Answer
> 3 votes
# Befunge 98, ~~37~~ 49 bytes

Original version :

```
~:"s"- #v_$"ht",>,
_;#-"S":<;$"hT",^

```

---

Terminating edition, as per consensus :

```
~:a-!#@_:"s"-#v_$"ht",>,
_;#-"S":      <;$"hT",^

```

This leaves a big honking hole in the code grid that I'm not very happy about. I'll look into that when I have the time.
The 49th byte is a space at the end of the second line, included to have a rectangular grid, required to prevent ccbi (and probably other interpreters) from bugging out and printing an infinite line of "Th"s.

# Answer
> 3 votes
# Emacth Lithp, 61 byteth

```
(lambda(s)(replace-regexp-in-string"[Ss]\\(\\w*\\)""th\\1"s))

```

Emacs Lisp tries to be smart when replacing text, but that smartness breaks when the replaced string only takes up one space, i.e. the capital letter S. To prevent this from converting "Sam and Sally" to "THam and THally", the whole word is matched instead. However, this also handles "SAM and Sally" in the way that one would want, i.e. producing "THAM and Thally".

# Answer
> 3 votes
# x86 machine code, 19 bytes

In hex:

```
86ac3c5374043c73750440aab068aa84c075eec3

```

Input: `ESI`: input string, `EDI`: output buffer.

Disassembly:

```
_loop:
0:  ac          lodsb
1:  3c 53       cmp al,'S'
3:  74 04       je _th
5:  3c 73       cmp al,'s'
7:  75 04       jne _nth
_th:
9:  40          inc eax     ;[Ss]->[Tt]
a:  aa          stosb
b:  b0 68       mov al,'h'
_nth:
d:  aa          stosb
e:  84 c0       test al,al
10: 75 ee       jnz _loop
12: c3          ret

```

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

```
ƛ⇩\s=[‛th$•

```

Try it Online!

~~I wath hoping I could find thomething lethth trivial than jutht replacing the letter with the combo but I couldn't.~~ Lookth like I did.

## Explained

```
ƛ⇩\s=[‛th$•
ƛ             # To each character:
 ⇩\s=[        #   if char.lower == "s":
      ‛th$•   #     "th" with the capitalisation of the character

```

# Answer
> 2 votes
## **C# 6.0 - 58 bytes**

```
string f(string s)=>s.Replace("s","th").Replace("S","Th");

```

Takes the input string as an argument to the function.

# Answer
> 2 votes
# Pyth, 14 bytes

```
::z\s"th"\S"Th

```

Test suite

Thanks to @LeakyNun for spotting a typo!

# Answer
> 2 votes
# MATL, 17 bytes

```
115'th'YX83'Th'YX

```

**Try it online!**

### Explanation

```
115    % 's' (ASCII)
'th'   % String 'th'
YX     % Regex replacement
83     % 'S' (ASCII)
'Th'   % String 'Th'
YX     % Regex replacement

```

# Answer
> 2 votes
# Python 3, 53 bytes

```
def l(s):return s.replace("s","th").replace("S","Th")

```

Usage:

```
>> l('Sam and Sally like Sheep')

Tham and Thally like Thheep

```

# Answer
> 2 votes
# GameMaker Language, 74 bytes

```
return string_replace_all(string_replace_all(argument0,'s','th'),'S','Th')

```

# Answer
> 2 votes
## Matlab, 39 byteth

A straitforward approach:

```
@(t)strrep(strrep(t,'s','th'),'S','Th')

```

# Answer
> 2 votes
# s-lang, ~~16~~ ~~15~~ 8 bytes (non-competing)

*Saved one byte because s-lang no longer requires last argument bracket*

*Saved seven bytes because of `!` paramater*

### Try it online!

```
t![s][th

```

s-lang (or, th-lang) is a string manipulation language I am working on for fun. I am still optimizing argument brackets...

## Explantion

* `t` replace function with search argument and replace argument.
* `!` "preserve case" parameter
* `[s]` the first search argument (searches for the character "s")
* `[th` the first replace argument (now this will replace each "s" with a "th"). End bracket is omitted because it is unnecessary.

# Answer
> 2 votes
# Brainfuck, 235 byteth

(Newlines included only for readability)

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

```

Requires 8-bit cells, and 0 on EOF. Try it online! I thought I could golf tt using some "if = s OR = S" wizardry, but it turns out that this just confounds the system.

## Readable

```
,
[
 [>+>+>+<<<-]>>>
 >-[>+<---]>--
 [-<<->>]+<<[>>-<<[-]]>>
 [ if char = "S"
  >-[--->+<]>-.[---->+++++<]>-.<<<-  output Th
 ]
 >>>

 >[-]
 <[>+<[-]]+
 >[<->-]<    logical negation

 [ else
  <<<<<
  -[>++<+++++++++]>+
  [-<<->>]+<<[>>-<<[-]]>>

   [ if char = "s"
    >--------[-->+++<]>.------------.>  output th
   ]

  <

  >[-]
  <[>+<[-]]+
  >[<->-]<    logical negation

  [<<.>] otherwise output and move to zero cell
 ]
 >>>>>>> we're going to move over some so we can use new cells
 , take more input
]

```

# Answer
> 2 votes
# Javathcript, 27 Byteth

```
b=a=>a.replace(/s/gi,'th');

```

Although it is case insensitive it is the smallest JS version so far :)

# Answer
> 2 votes
# Arturo, ~~30~~ 29 byteth

```
$=>[translate&#[S:"Th"s:'th]]

```

Try it

# Answer
> 2 votes
# Lexurgy, 18 byteth

```
s:
{S,s}=>{Th,th}

```

# Answer
> 1 votes
# ~~SpecBAS~~ ThpecBATh - 53 bytes

```
1 INPUT a$: ?REPLACE$(REPLACE$(a$,"S","Th"),"s","th")

```

# Answer
> 1 votes
## Matlab, 38 ~~42~~ bytes

```
@(t)regexprep(t,{'s','S'},{'th','Th'})

```

Shout out to @LuisMendo for the tip about cell arrays!

For `'Miss Sissy'` yields `ans = Mithth Thiththy`.

# Answer
> 1 votes
## Thue, Full program: 27 byteth, function: 13 byteth

```
s::=th
S::=Th

```

~~Thince Thue can read input, a correct input routine will be too long. Tho i potht it ath a "function"~~

EDIT: I have forgotten, Thue read lineth from thtdin, not characterth

Tho, here ith a full program:

```
s::=th
S::=Th
I::=:::
::=
I

```

# Answer
> 1 votes
# PowerThhell, 41 bytes

```
$args.replace('S','Th').replace('s','th')

```

I can't beat this simple approach; there is a string.translate buried in XPath and there are `map` style approaches in the Linq library - but they're wordy. Can't easily do a dictionary lookup per character because PS is case insensitive and thinks 's' and 'S' are duplicate keys.

Best novelty alternative so far:

```
$OFS='Th';''+$args.split('S')-replace's','th'

```

# Answer
> 1 votes
# Perl 5, 18 byteth

The obviouth anthwer; I don't thee anything thhorter. 17 byteth, pluth 1 for `-pe` inthtead of `-e`.

```
s/s/th/g;s/S/Th/g

```

I wathn't thure whether, tho ath to follow the thandard for anthwerth of thith quethtion, I thhould lithpify my code ath well ath my prothe. Jutht in cathe, here'th the lithpy verthion:

```
th/th/th/g;th/Th/Th/g

```

# Answer
> 1 votes
# J, 38 bytes

```
load'strings'
rplc&('s';'th';'S';'Th')

```

In J, `rplc` is the string replace verb in the `strings` addon, and it takes a list of boxes where each pair `[x, y]` represents the string `x` to be replaced with `y`.

## Usage

```
   f =: rplc&('s';'th';'S';'Th')
   f 'Sam and Sally like Sheep'
Tham and Thally like Thheep
   f 'Sally likes sausages'
Thally liketh thauthageth
   f 'Sally sells seashells'
Thally thellth theathhellth

```

# Answer
> 1 votes
# C, 101 bytes

Note this is a complete C program, unlike the previous C answer.

It takes the first command line argument as input. Compile w/ `gcc` and run `./a.out "Sally sells seashells"`

```
#include<stdio.h>
main(int d,char**c){for(d=**++c;d;putchar(d&223^83?d:d+(*0[c]--=104,1)),d=*++*c);}

```

# Answer
> 1 votes
## C, 69 byteth

Reads from `stdin`, writes to `stdout`. Nothing terrific, but somebody had to do it!

```
c;main(){while((c=getchar())>0)printf(c-'s'?c-'S'?"%c":"Th":"th",c);}

```

# Answer
> 1 votes
# J, 47 bytes

Without using the `strings` library.

```
[:;(]`('h',~[:u:1+3&u:)@.([:+/'sS'-:"0]))&.>@;/

```

# Answer
> 1 votes
# Thilicon, 13 byteth

```
i`s|th``S|Th`

```

Pretty simple. `i` to get input, and the rest of it is replacing stuff. Output is implicit.

# Answer
> 1 votes
# Go, 87 bytes

```
import."strings"
func f(s string)string{R:=ReplaceAll
return R(R(s,"s","th"),"S","Th")}

```

Attempt This Online!

# Answer
> 1 votes
# Thunno, \\$ 16 \log\_{256}(96) \approx \\$ 13.17 bytes

```
's"th"AR'S"Th"AR

```

Attempt This Online!

Obviouth anthwer.

#### Explanation

```
's"th"AR'S"Th"AR  # Implicit input
's                # Character 's'
  "th"            # String "th"
      AR          # Replace
        'S        # Character 'S'
          "Th"    # String "Th"
              AR  # Replace
                  # Implicit output

```

# Answer
> 1 votes
# Thunno 2, 11 bytes

```
`Ss"Thth"½Ṇ

```

Try it online!

#### Explanation

```
`Ss"Thth"½Ṇ  # Implicit input
`Ss          # Push "Ss"
   "Thth"    # Push "Thth"
         ½   # Halve it
          Ṇ  # Transliterate
             # Implicit output

```

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

```
"Th"/"S"\"th"/"s"\

```

Try it online!

* `"s"\` split (implicit) input on `"s"`s
* `"th"/` join with `"th"`
* `"S"\` split on `"S"`s
* `"Th"/` join with `"Th"`

# Answer
> 0 votes
## Pyke, 14 byteth

```
\s"th":\S"Th":

```

Try it here!

Thith anthwer ith very thimple and boring.

# Answer
> 0 votes
## TCC - 28 bytes

```
=SO;i;{'s';'th';{'S';'Th';SO

```

Try it online!

Explanation:

```
=SO;i;                       - Load input (i) into SO (string operations)
      {'s';'th';             - Replace 's' with 'th' in SO
                {'S';'Th';   - Replace 'S' with 'Th' in SO
                          SO - Implicit print of SO

```

# Answer
> 0 votes
# Rattle, 50 byteth

```
\&Th&th|Ig0Ig0I^P3[g["S"b1]["s"b2][^"S"[^"s"b]]>]`

```

Try it Online!

# Explanation

```
\&Th&th|                          pass [(user input), "Th", "th"] to program
        I                         place list items in consecutive memory slots, move pointer to next free slot
         g0                       get item 0 (user input)
           I                      place list items in consecutive memory slots, move pointer to next free slot
            g0                    get item 0 (user input)
              I^                  set top of stack to the length of this item
                P3                move the pointer to slot 3

[ ... ]`                          loop n times, where n is the top of the stack

g                                 get the value at the pointer
 ["S"  ]                          if the value is "S",
     b1                           add the item in storage at pointer 1 ("Th") to print buffer
        ["s"  ]                   if the value is "s",
            b2                    add the item in storage at pointer 2 ("th") to print buffer
               [^"S"       ]      if the value is not "S",
                    [^"s" ]       if the value is not "s",
                         b        add the item to the print buffer
                            >     move the pointer right
                                  the buffer is printed implicitly

```

# Rattle, 50 byteth

Here's an alternative approach using ASCII values that turned out to be the same byte count:

```
\&Th&th|Ig0Ig0I^P3[gn[83b1][115b2][^83[^115gb]]>]`

```

Try it Online!

# Answer
> 0 votes
# Raku, 23 bytes

```
*.trans(<s S>=><th Th>)

```

Try it online!

Just calls the built-in string `trans`late function.

# Answer
> 0 votes
# Racketh -- 58 bytes

```
#!racket
(regexp-replaces(read-line)'(["s""th"]["S""Th"]))

```

Try it online!

---

## Explanation

On line one we have the required language expression for Racket.

On line two we pass user input to a function that uses regular expressions to replace certain characters ("s" becomes "th" and "S" becomes "Th").

```
#lang racket
(regexp-replaces (read-line) '(["s" "th"] ["S" "Th"]))

```

# Answer
> 0 votes
# sed 4.2.2, 17 bytes

```
s/s/th/g
s/S/Th/g

```

Try it online!

Pretty thimple. It'th what thed it made for.

# Answer
> 0 votes
# 05AB1E, ~~11~~ 10 byteth

```
„sS„thD™‚‡

```

Originally thuggethted ath a golf for the exithting 05AB1E anthwer, but I decided to potht it ath a theparated anthwer after there wath no rethpondth for halve a year. :)

Try it online.

**Explanation:**

```
„sS         # Push string "sS"
   „th      # Push string "th"
      D     # Duplicate it
       ™    # Titlecase the copy
        ‚   # Pair the two together: ["th","Th"]
         ‡  # Transliterate all "s" to "th" and "S" to "Th" in the (implicit) input
            # (after which the result is output implicitly)

```

PTh: Altho workth in 2thable:
Try it online (Hello. Table for two, pleathe. ;p)

# Answer
> 0 votes
# brainfuck, 183 byteth

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

```

Try it online!

## Explanation

```
[
* https://esolangs.org/wiki/Brainfuck_constants
* https://esolangs.org/wiki/Brainfuck_algorithms
*
* Cell #    Name    Explanation
* 0         tc0     Unused except right at the start for making 83 ('S')
* 1         tc1     Stores 'S'
* 2         tc1p5   Temp cell & used for outputting input char
* 3         tc2     Temp cell & holds input char - 'S'
* 4         tc3     Temp cell & holds input char - 's'
* 5         tc4     Temp cell & input initially starts here
* 6         tc4p5   Temp cell
* 7         tc5     Stores 's'
* 8         tc6     Stores 'h'
*
* Algorithm:
*   initialization
*
*   while (ch = input()) {
*       if ((ch - 's') != 0) {
*           if ((ch - 'S') != 0) {
*               output(ch)
*           } else {
*               output(ch + 1)
*               output('h')
*           }
*       } else {
*           output(ch + 1)
*           output('h')
*       }
*   }
]

-[>+<---]>-- make 83 ('S') on tc1 end tc1

>> make space for tc1p5 and tc4p5

>+[->-[<]>--]>- make 104 ('h') on tc6 end tc6
<<<+[-->++[<]>-]>+ make 115 ('s') on tc5 end tc5

<<,[ tc4 begin input loop

handling:
    'S': output Th
    's': output th
    else: output char

[-<+<+<+>>>] copy tc4 to tc3 tc2 tc1p5 end tc4

>> tc5 s
[<<+<->>>-] move tc5 to tc4 and sub from tc3 end tc5
<<[->>+<<] tc4 move back to tc5 end tc4

+ tc4 is 1
<[
    tc3 is not 's'
    [-] zero tc3
    >-< tc4 to zero

    <<< tc1
    [->>->+<<<] tc1 to sub tc2 and add tc3 end tc1
    >>>[-<<<+>>>] tc3 to tc1 end tc3

    + tc3 one
    <[
        tc2 is not 'S'
        <. output tc1p5

        > tc2
        >-
    ]>
    [<
        tc2 is 'S'
        <+. tc1p5 output 'T'
        >>->>>>. tc6 output 'h' and dec tc3 along the way

        <<< tc4
    ] end tc4

]>
[< tc3 and tc3 is 's'
    <<+. tc1p5 make 't' output
    >>>->>>. tc6 output 'h' and dec tc4 along the way
    << tc4p5
] end tc4p5  tc4 0 tc4p5 0

<<<[-] tc2 zero
<[-] tc1p5 zero

>>> tc4

,] end tc4

```

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


title: Add All Permutations of a Number

text:
# Question
Title: Add All Permutations of a Number
You have to make something that takes in one input from a default I/O method (as an integer), and prints out the sum of all the permutations of that number (not necessarily unique)

For example:

`10` would return `11` because `10` can have 2 permutations (`10` and `01`), and the sum of those two numbers would be `11`

`202` would have 6 permutations (`202`, `220`, `022`, `022`, `202`, `220`), so the sum would be `888`.

The input is positive, and the input can be taken as any type, but your program's output must be a number.

Standard loopholes are not allowed, and as usual, since this is code golf, the shortest answer in bytes wins!

# Answer
# Japt `-x`, 1 byte

Takes input as a string.

```
á

```

Try it

---

## Explanation

```
á     :Get permutations
      :Implicitly reduce by addition and output

```
> 10 votes

# Answer
# CJam, ~~10~~ 6 bytes

```
{m!1b}

```

Try it online!

## Explanation

```
{    }  Anonymous block taking input as string on stack
 m!     Find all permutations
   1b   Implicitly convert each to integer and sum

```
> 7 votes

# Answer
# Python 2, 66 bytes

```
n=s=0
P=1
for c in input():s+=int(c);n+=1;P*=n
print 10**n/9*s*P/n

```

Try it online!

Takes input as a string.

---

# Python 2, 70 bytes

```
f=lambda k,P=1,n=0,s=0:f(k/10,P*-~n,n+1,s+k%10)if k else 10**n/9*s*P/n

```

Try it online!

An arithmetic method. The base case is hard to deal with because the `/n` causes division by zero for the inital value `n=0`.
> 6 votes

# Answer
# 05AB1E, 2 bytes

```
œO

```

Try it online!
> 5 votes

# Answer
# Perl 6, 30 bytes

```
*.comb.permutations>>.join.sum

```

Try it online!

It would be nice if this was just `*.permutations.sum` but Perl 6 doesn't treat strings as lists of characters.

### Explanation

```
*.comb.permutations>>.join.sum
*.comb                           # Convert to list of digits
      .permutations              # Get all permutations of the list
                   >>.join       # Join all lists of digits
                          .sum   # Get the sum of all numbers

```
> 4 votes

# Answer
# Python 2, ~~63~~ 62 bytes

```
f=lambda n,k=1,s=0:n>9and k*f(n/10,k+1,s+n%10)or 10**k/9*(s+n)

```

Try it online!
> 3 votes

# Answer
# , ~~59~~ 57 bytes

```
sum(gamma(n<-nchar(x<-scan()))*x%/%10^(0:n)%%10)*10^n%/%9

```

Try it online!

Mathematical approach suggested by Peter Taylor and decribed by Arnauld. -2 bytes by J. Doe.
> 3 votes

# Answer
# J-uby, 35 bytes

```
:digits|:permutation|:sum+(:join|Z)

```

Try it online!

-3 from Jordan.
> 3 votes

# Answer
# JavaScript (ES6), 53 bytes

Recursive version, inspired by @tsh.

```
f=(n,s=i=0,p='')=>n?(i++||1)*f(n/10|0,s+n%10,p+1):s*p

```

Try it online!

---

# JavaScript (ES6), ~~61~~ 60 bytes

*Saved 1 byte thanks to @l4m2*

```
n=>![...n+(x=s=p='')].map((d,i)=>(p+=1,x=x*i||1,s-=d))-s*p*x

```

Try it online!

### How?

This is based on the formula suggested by Peter Taylor in the sandbox:

$$\left(\sum\_{i=1}^n{a\_i}\right)\frac{10^n-1}{9}(n-1)!$$

where \\$a\_i\\$ is the \\$i\\$th digit of the input number and \\$n\\$ is the total number of digits.

The result of the expression \\$(10^n-1)/9\\$ is a number consisting of the digit \\$1\\$ repeated \\$n\\$ times, which is what is computed in \\$p\\$. The factorial is stored in \\$x\\$ and the opposite of the sum is stored in \\$s\\$.
> 2 votes

# Answer
# , 18 bytes

```
1#.(A.~i.@!@#)&.":

```

Try it online!

## Explanation:

```
                ":  - convert to string
              &.    - do the verbs in () then convert back to number
       i.           - make a list from 0 to
         @!         - factorial
           @#       - of the number of digits in the input
    A.~             - find all permutations, using the list above as permutation index
1#.                 - find the sum by base-1 convertion

```

## Alternative:

Using the formula suggested by Peter Taylor:

# , 30 bytes

```
1#.("."0*9%~!@<:@#*_1+10^#)@":

```

Try it online!
> 2 votes

# Answer
# Haskell, 62 bytes

```
import Data.List
f::Int->Int
f=sum.map read.permutations.show

```

Unfortunately, `f` must be annotated with a type to avoid ambiguity.
> 2 votes

# Answer
# MY, 12 bytes

```
⍞℘⌊Σ88ǵ'ƒ⇥(↵

```

Try it online!

Some of MY's stupid builtin decisions are coming in handy.

```
⍞℘⌊Σ88ǵ'ƒ⇥(↵
⍞             Input
  ℘                's permutations
   ⌊                                as integers.
    Σ                                           Sum of that
     88ǵ'ƒ⇥(                                               to standard base 10 form
             ↵                                                                      output.

```
> 2 votes

# Answer
# Python 2, 76 bytes

```
s=map(int,`input()`);n=len(s);t=sum(s)*int('1'*n)
while~-n:n-=1;t*=n
print t

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~89~~ 71 bytes

```
g(x,s,p,f,i){for(s=x%10,p=f=i=1;x/=10;s+=x%10)p=p*10+1,f*=i++;x=s*p*f;}

```

Try it online!

-18 bytes thanks to @nwellnhof
> 1 votes

# Answer
# Ruby `-nl`, 41 bytes

```
p$_.chars.permutation.sum{|x|x.join.to_i}

```

Try it online!

Full program taking input from stdin.

## Ruby, 45 bytes

```
->n{n.digits.permutation.sum{|x|x.join.to_i}}

```

Try it online!

Function taking input as integer. `digits` can be shortened to `chars` if input is acceptable as string, and `chars` can be completely removed if input is an array of characters.
> 1 votes

# Answer
# Python 2, 76 bytes

```
lambda x:sum(map(int,x))*int('1'*len(x))*reduce(int.__mul__,range(1,len(x)))

```

Try it online!

xnor's answer is shorter, but I thought I'd have a go at a one-liner
> 1 votes

# Answer
# Scala (74 bytes)

```
def%(i:Int)=s"$i".indices.permutations.map(_.map(i+"").mkString.toInt).sum

```

Try it online

Since permutation on digits will drop the repeated digits, we have to permute on indices.
> 1 votes

# Answer
# Jelly, 5 bytes

```
DŒ!ḌS

```

Try it online!
> 1 votes

# Answer
# Charcoal, 12 bytes

```
Ｉ↨χＥθΠＥθ∨μΣθ

```

Try it online! Link is to verbose version of code. Explanation: Based on Peter Taylor's formula. `ΠＥθμ` doesn't quite calculate \\$ (n - 1)! \\$ as Charcoal's indices range from \\$ 0 \\$ to \\$ n - 1 \\$ so  is used to replace the \\$ 0 \\$ with the sum of digits of the input, thus implicitly multiplying the two. The outer mapping then creates an array of the length of the original input with that product as elements which is then passed to base 10 conversion which effectively multiplies the product by the appropriate repunit.

```
    θ           Input
   Ｅ            Map over characters
       θ        Input
      Ｅ         Map over characters
         μ      Current index
        ∨       Logical Or
           θ    Input
          Σ     Digital sum
     Π          Product
  χ             Predefined variable 10
 ↨              Base conversion
Ｉ               Cast to string
                Implicitly print

```
> 1 votes

# Answer
# Pyth, ~~5~~ 4 bytes

```
sv.p

```

Try it online! Takes input as a string.

Explanation:

```
sv.pQ - Full program. Implicit Q added.

    Q - Input
  .p  - All permutations of it
 v    - Evaluate each (list of strings into integers)
s     - Sum the list

```
> 1 votes

# Answer
# APL(NARS), 25 chars, 50 bytes

```
{+/10⊥⍉⍎¨w[110 1‼↑⍴w←⍕⍵]}

```

test:

```
  f←{+/10⊥⍉⍎¨w[110 1‼↑⍴w←⍕⍵]}
  f¨202 1024 505
888 46662 2220

```

110 1‼k would return as built in all the permutations of 1..k .
> 1 votes

# Answer
# Pyt, 4 bytes

```
ǰᒆƖƩ

```

Try it online!

**Explanation:**

```
      Implicit input
ǰ     Join (becomes string)
 ᒆ    All permutations of it
  Ɩ   List of strings to int
   Ʃ  Sum the array

```
> 1 votes

# Answer
# Vyxal `Ṡs`, 3 bytes

```
ṖvI

```

Try it Online!
> 1 votes

# Answer
# Brachylog, 3 bytes

```
pᶠ+

```

Try it online!

### Explanation

```
 ᶠ     Find all:
p          permutations
  +    Sum

```
> 1 votes

# Answer
# Husk, 4 bytes

```
ṁdPd

```

Try it online!

### Explanation

```
ṁdPd
   d  digits of input
  P   get all permutations
ṁ     (flat/concat/sum)-map
 d    interpret as digits

```
> 1 votes

# Answer
# Wolfram Language(Mathematica), 111 bytes

Try it online!

```
Total[FromDigits/@(Permutations[#]/.Thread[#->IntegerDigits@#2])]&[Unique[]&/@Range@Length@IntegerDigits@#, #]&

```

---

Appendix:

Don't allow duplicate(i.e. Multinomial Permutation) \\$\quad \\$ (50 bytes). Try it online!

```
Total[FromDigits/@Permutations[IntegerDigits[#]]]&

```
> 0 votes

# Answer
# Racket -- 93 bytes

```
#!racket
(for/sum([l(permutations(string->list(~a(read))))])(string->number(apply string l)))

```

Try it online!

---

## Explanation

User input is a number. We split the number into its individual digits and then we permutate the list of digits. We loop through all the permutations and rejoin them to form a number. Once we have iterated through the entire list, we return the sum of resulting numbers of the permutations.

```
#lang racket

(for/sum ([lst (permutations (string->list (~a (read))))])
  (string->number (apply string lst)))

```

Let's do an example with input `50`.

1. Split input into separate digits: `'(5 0)`
2. Obtain all permutations of digits: `'((5 0) (0 5))`
3. Convert all permutations back into numbers: `'(50 05)` or `'(50 5)`
4. Once all permutations are numbers, add the numbers together: `(+ 50 5)`
5. Return the sum: `55`
> 0 votes

---
Tags: code-golf
---