title: Find the prime factors

text:
# Question
Title: Find the prime factors
In this task, you have to write a program, that computes the prime factors of a number. The input is a natural number 1 \< n \< 2^32. The output is a list of the prime factors of the number in the following format. Exponents must be omitted if they are 1. Only output prime numbers. (Assuming the input is 131784):

> 131784 = 2^3 * 3 * 17^2 * 19

Using the same amount of whitespace is not required; whitespace may be inserted wherever appropriate. Your program should complete in less then 10 minutes for any input. The program with the shortest amount of characters wins.

# Answer
# SageMath, 31 Bytes

```
N=input()
print N,"=",factor(N)

```

Test case: `83891573479027823458394579234582347590825792034579235923475902312344444` Outputs:

`83891573479027823458394579234582347590825792034579235923475902312344444 = 2^2 * 3^2 * 89395597 * 98966790508447596609239 * 263396636003096040031295425789508274613`
> 12 votes

# Answer
## Ruby 1.9, ~~74~~ 70 characters

```
#!ruby -plrmathn
$_+=?=+$_.to_i.prime_division.map{|a|a[0,a[1]]*?^}*?*

```

Edits:

* (74 -\> 70) Just use the exponent as slice length instead of explicitly checking for `exponent > 1`
> 8 votes

# Answer
## Perl 5.10, 73 ~~88~~

```
perl -pe '$_=`factor $_`;s%( \d+)\K\1+%-1-length($&)/length$1%ge;y, -,*^,;s;\D+;=;'

```

Takes input number from standard input. Will compute factors for multiple inputs if provided.

Counted as a difference to `perl -e`. 5.10 is needed for the `\K` regex metacharacter.
> 7 votes

# Answer
## Python, 140 135 133 chars

```
M=N=input()
s=''
f=1
while f<4**8:
 f+=1;e=0
 while N%f<1:e+=1;N/=f
 if e:s+='*%d'%f+'^%d'%e*(e>1)
print M,'=',(s+'*%d'%N*(N>1))[1:]

```
> 5 votes

# Answer
## J, 72

```
(":*/f),'=',([,'*',])/(":"0~.f),.(('^',":)`(''"0)@.(=&1))"0+/(=/~.)f=.q:161784

```

Typical J. Two characters to do most of the work, sixty characters to present it.

**Edit:** Fixed the character count.
> 5 votes

# Answer
# OCaml, 201 characters

A direct imperative translation of the best Python code:

```
let(%)s d=if!d>1then Printf.printf"%s%d"s!d
let f n=let x,d,e,s=ref n,ref 1,ref 0,ref"="in""%x;while!d<65536do
incr d;e:=0;while!x mod!d=0do x:=!x/ !d;incr e
done;if!e>0then(!s%d;"^"%e;s:="*")done;!s%x

```

For example,

```
# f 4294967292;;
4294967292=2^2*3^2*7*11*31*151*331- : unit = ()

```

(note that I've omitted outputting the final endline.) Just for fun, at 213 characters, a purely functional version, thoroughly obfuscated through liberal use of operators:

```
let(%)s d=if d>1then Printf.printf"%s%d"s d
let f x=let s=ref"="in""%x;let rec(@)x d=if d=65536then!s%x else
let rec(^)x e=if x/d*d<x then x,e else x/d^e+1in
let x,e=x^0in if e>0then(!s%d;"^"%e;s:="*");x@d+1in x@2

```
> 5 votes

# Answer
## J, ~~53~~ 52 characters

This solution takes the `rplc` trick from the solution of randomra but comes up with some original ideas, too.

```
":,'=',(":@{.,'^','*',~":@#)/.~@q:}:@rplc'^1*';'*'"_

```

In non-tacit notation, this function becomes

```
f =: 3 : 0
(": y) , '=' , }: (g/.~ q: y) rplc '^1*' ; '*'
)

```

where `g` is defined as

```
g =: 3 : 0
": {. y) , '^' , (": # y) , '*'
)

```
* `q: y` is the vector of *prime factors* of `y`. For instance, `q: 60` yields `2 2 3 5`.
* `x u/. y` applies `u` to `y` *keyed* by `x`, that is, `u` is applied to vectors of elements of `y` for which the entries in `x` are equal. This is a bit complex to explain, but in the special case `y u/. y` or `u/.~ y`, `u` is applied to each vector of distinct elements in `y`, where each element is repeated for as often as it appears in `y`. For instance, `</.~ 1 2 1 2 3 1 2 2 3` yields

```
┌─────┬───────┬───┐
│1 1 1│2 2 2 2│3 3│
└─────┴───────┴───┘

```
* `# y` is the *tally* of `y`, that is, the number of items in`y`.
* `": y` *formats* `y` as a string.
* `x , y` *appends* `x` and `y`.
* `{. y` is the *head* `y`, that is, its first item.
* Thus, `(": {. y), '^' , (": # y) , '*'` formats a vector of *n* repetitions of a number *k* into a string of the form *k* ^ *n* \*. This phrase in tacit notation is `:@{.,'^','*',~":@#`, which we pass to the adverb `/.` described further above.
* `x rplc y` is the library function *replace characters.* `y` has the form `a ; b` and every instance of string `a` in `x` is replaced by `b`. `x` is ravelled (that is, reshaped such that it has rank 1) before operation takes place, which is used here. This code replaces `^1*` with `*` as to comply with the mandated output format.
* `}: y` is the *curtail* of `y`, that is, all but its last item. This is used to remove the trailing `*`.
> 5 votes

# Answer
# PHP, 112

```
echo$n=$_GET[0],'=';$c=0;for($i=2;;){if($n%$i<1){$c++;$n/=$i;}else{if($c){echo"$i^$c*";}$c=0;if(++$i>$n)break;}}

```

118

```
echo $n=$_GET[0],'=';for($i=2;;){if(!($n%$i)){++$a[$i];$n/=$i;}else{if($a[$i])echo "$i^$a[$i]*";$i++;if($i>$n)break;}}

```
> 4 votes

# Answer
**Python 119 Chars**

```
M=N=input()
i=1
s=""
while N>1:
 i+=1;c=0
 while N%i<1:c+=1;N/=i
 if c:s+=" * %d"%i+['','^%d'%c][c>1]
print M,'=',s[3:]

```
> 3 votes

# Answer
### JavaScript, ~~124~~ ~~122~~ 119

```
for(s='',i=2,o=p=prompt();i<o;i++){for(n=0;!(p%i);n++)p/=i;n?s+=i+(n-1?'^'+n:'')+'*':0}alert(s.substring(0,s.length-1))

```
> 3 votes

# Answer
# Perl, 78

```
use ntheory":all";say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp(shift)

```

It uses the s///r feature of Perl 5.14 to elide the ^1s. 81 characters to run in a loop:

```
perl -Mntheory=:all -nE 'chomp;say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp($_);'

```
> 3 votes

# Answer
## PHP, 236 characters

```
$f[$n=$c=$argv[1]]++;echo"$n=";while($c){$c=0;foreach($f as$k=>$n)for($r=~~($k/2);$r>1;$r--){if($k%$r==0){unset($f[$k]);$f[$r]++;$f[$k/$r]++;$c=1;break;}}}foreach($f as$k=>$n)if(--$n)$f[$k]="$k^".++$n;else$f[$k]=$k;echo implode("*",$f);

```

Output for 131784: 2^3\*3\*17^2\*19

Completes all numbers within a few seconds while testing.

```
4294967296=2^32
Time: 0.000168

```

Input was never specified, so I chose to call it using command line arguments.

```
php factorize.php 4294967296

```
> 2 votes

# Answer
### Scala 374:

```
def f(i:Int,c:Int=2):List[Int]=if(i==c)List(i)else
if(i%c==0)c::f(i/c,c)else f(i,c+1)
val r=f(readInt)
class A(val v:Int,val c:Int,val l:List[(Int,Int)])
def g(a:A,i:Int)=if(a.v==i)new A(a.v,a.c+1,a.l)else new A(i,1,(a.v,a.c)::a.l)
val a=(new A(r.head,1,Nil:List[(Int,Int)])/:(r.tail:+0))((a,i)=>g(a,i))
a.l.map(p=>if(p._2==1)p._1 else p._1+"^"+p._2).mkString("", "*", "")

```

ungolfed:

```
def factorize (i: Int, c: Int = 2) : List [Int] = {
  if (i == c) List (i) else
    if (i % c == 0) c :: f (i/c, c) else
      f (i, c+1)
}
val r = factorize (readInt)
class A (val value: Int, val count: Int, val list: List [(Int, Int)])
def g (a: A, i: Int) =
  if (a.value == i)
    new A (a.value, a.count + 1, a.list) else
    new A (i, 1, (a.value, a.count) :: a.list)
val a = (new A (r.head, 1, Nil: List[(Int,Int)]) /: (r.tail :+ 0)) ((a, i) => g (a, i))
a.l.map (p => if (p._2 == 1) p._1 else
  p._1 + "^" + p._2).mkString ("", "*", "")

```
> 2 votes

# Answer
# J, 74 chars

```
f=.3 :0
(":y),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:y
)

   f 131784
131784=2^3*3*17^2*19

```

64 chars with input in variable `x`:

```
   x=.131784

   (":x),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:x
131784=2^3*3*17^2*19

```
> 2 votes

# Answer
# Java 10, ~~109~~ 108 bytes (lambda function)

```
n->{var r=n+"=";for(int i=1,f;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;return r;}

```

Try it online.

# Java 6+, 181 bytes (full program)

```
class M{public static void main(String[]a){long n=new Long(a[0]),i=1,f;String r=n+"=";for(;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;System.out.print(r);}}

```

Try it online.

-1 byte thanks to *@ceilingcat*.

**Explanation:**

```
n->{                // Method with integer parameter and String return-type
  var r=n+"=";      //  Result-String, starting at the input with an appended "="
  for(int i=1,f;i++<n;
                    //  Loop in the range [2, n]
      r+=           //    After every iteration: append the following to the result-String:
        f<1?        //     If the factor `f` is 0:
         ""         //      Append nothing
        :           //     Else:
         (f<2?      //      If the factor `f` is 1:
           i        //       Append the current prime `i`
          :         //      Else:
           i+"^"+f) //       Append the current prime `i` with it's factor `f`
         +(n>1?     //      And if we're not done yet:
            "*"     //       Also append a "*"
           :        //      Else:
            ""))    //       Append nothing more
    for(f=0;        //   Reset the factor `f` to 0
        n%i<1;      //   Loop as long as `n` is divisible by `i`
      n/=i)         //    Divide `n` by `i`
      f++;          //    Increase the factor `f` by 1
  return r;}        //  Return the result-String

```
> 2 votes

# Answer
# Japt, ~~28~~ ~~27~~ 26 bytes

-1 byte thanks to Shaggy

```
+'=+Uk ü ®ÊÉ?ZÌ+'^+Zl:ZÃq*

```

Try it
> 2 votes

# Answer
# Jelly, 16 bytes

```
³”=³ÆFḟ€1j€”^j”*

```

One of my first Jelly answers, so can definitely be golfed (especially `³”=³`)..

Try it online.

**Explanation:**

```
³                 # Push the first argument
 ”=               # Push string "="
   ³ÆF            # Get the prime factor-exponent pairs of the first argument
      ḟ€1         # Remove all 1s from each pair
         j€”^     # Join each pair by "^"
             j”*  # Join the pair of strings by "*"
                  # (implicitly join the entire 'stack' together)
                  # (which is output implicitly as result)

```
> 2 votes

# Answer
# Powershell, ~~113~~ 97 bytes

Inspired by Joey's answer. It's a slow but short.

```
param($x)(2..$x|%{for(;!($x%$_)){$_
$x/=$_}}|group|%{$_.Name+"^"+$_.Count-replace'\^1$'})-join'*'

```

Explained test script:

```
$f = {

param($x)               # let $x stores a input number > 0
(2..$x|%{               # loop from 2 to initial input number
    for(;!($x%$_)){     # loop while remainder is 0
        $_              # push a current value to a pipe
        $x/=$_          # let $x is $x/$_ (new $x uses in for condition only)
    }
}|group|%{              # group all values
    $_.Name+"^"+$_.Count-replace'\^1$'  # format and remove last ^1
})-join'*'              # make string with *

}

&$f 2
&$f 126
&$f 129
&$f 86240
#&$f 7775460

```

Output:

```
2
2*3^2*7
3*43
2^5*5*7^2*11

```
> 1 votes

# Answer
# 05AB1E, ~~22~~ 20 bytes

```
ÐfsÓ0Køε1K'^ý}'*ý'=ý

```

-2 bytes thanks to *@Emigna*.

Try it online.

**Explanation:**

```
Ð                # Triplicate the (implicit) input-integer
 f               # Pop and push all prime factors (without counting duplicates)
  s              # Swap to take the input again
   Ó             # Get all prime exponents
    0K           # Remove all 0s from the exponents list
      ø          # Zip it with the prime factors, creating pairs
       ε         # Map each pair to:
        1K       #  Remove all 1s from the pair
        '^ý     '#  And then join by "^"
       }'*ý     '# After the map: join the string/integers by "*"
           '=ý  '# And join the stack by "=" (with the input we triplicated at the start)
                 # (after which the result is output implicitly)

```
> 1 votes

# Answer
# APL(NARS), 66 chars, 132 bytes

```
{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}

```

test and comment:

```
  f←{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
  f 131784
131784=2^3 * 3 * 17^2 * 19
  f 2
2=2
  f (2*32)
4294967296=2^32

{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
k←π⍵      find the factors with repetition of ⍵ and assign that array to k example for 12 k is 2 2 3
v←∪       gets from k unique elements and put them in array v
+/¨{k=⍵}¨ for each element of v count how many time it appear in k (it is array exponents)
v,¨       make array of couples from element of v (factors unique) and the array above (exponents unique)
∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨ pretty print the array of couples factor exponent as array chars
3↓                                 but not the first 3 chars
(⍕⍵),'='  but print first the argument and '=' in char format

```

if someone has many time with these primitives, know them very well them, for me it is possible that the code is clearer of comments... so code more clear than comments, comments unuseful...
> 1 votes

# Answer
# QBasic, 156 characters

```
INPUT n#
?n#;"=";
f=2
1c=0
WHILE n#/f=INT(n#/f)
n#=n#/f
c=c+1
WEND
IF c THEN?f;
IF c>1THEN?"^";c;
IF c*(n#>1)THEN?"*";
f=f+1
IF f*f<=n#GOTO 1
IF n#>1THEN?n#

```

When run at Archive.org, this takes about 2½ minutes to finish for an input of 4294967291, the largest prime in the specified range.

### Ungolfed, with some remarks

This is the version I used to get the timing information:

```
CLS
INPUT num#
PRINT num#; "=";
factor = 2

startTime# = TIMER

DO
    count = 0
    WHILE num# / factor = INT(num# / factor)
        num# = num# / factor
        count = count + 1
    WEND
    IF count > 0 THEN PRINT factor;
    IF count > 1 THEN PRINT "^"; count;
    IF count > 0 AND num# > 1 THEN PRINT "*";
    factor = factor + 1
LOOP WHILE factor * factor <= num#

IF n# > 1 THEN PRINT n# ELSE PRINT

time# = TIMER - startTime#
PRINT "Search took"; INT(time# / 60); "minutes and";
PRINT INT(time# mod 60); "seconds"

```

The program uses the standard approach of trial division of each factor between \\$2\\$ and \\$\sqrt n\\$. It prints a `*` after each successful factor if the remaining \\$n\\$ is still greater than 1. If the factor becomes greater than \\$\sqrt n\\$ while \\$n \> 1\\$, then \\$n\\$ is prime and we output it after exiting the loop.

A few extra bytes had to be spent to cope with very large numbers:

QBasic's numbers are either single- or double-precision floating point under the hood, although it casts to integers for certain calculations. Integers greater than \\$2^{24}\\$ are not guaranteed to be accurately represented in single-precision floating point, so we have to use double-precision for \\$n\\$ (thus the double-precision sigil on the variable `num#`). However, since we're only checking factors up to \\$\sqrt n \< 2^{16}\\$, we can use the default single precision for `factor`.

At first, I had `WHILE num# MOD factor = 0` for the inner loop. This worked until I tried numbers close to \\$2^{32}\\$, at which point it said "Overflow." It seems that the `MOD` operator casts its operands to integers--specifically, 32-bit *signed* integers. A value of \\$2^{32}-1\\$ can fit in a 32-bit *unsigned* integer, but not a signed one. So `MOD` wasn't going to work. Neither was my usual golf trick of checking divisibility with `a/b=a\b`, since the int-div operator `\` also casts to integers. Fortunately, I could still use floating point division and then truncate explicitly with the `INT` function (which seemingly does *not* cast to integer--??).

Given the issues with single- vs. double-precision, I assumed that squaring `factor` (single-precision) before comparing it with `num#` (double) wasn't going to work. But surprisingly, it did. My best guess after some experimentation is that if there's a double-precision value anywhere in an expression, QBasic casts *all* of the values to double before computing anything. This contrasts with C, for example, where implicit casting only occurs between the operands of a single operator.
> 1 votes

# Answer
# JavaScript, 107

```
n=prompt()
s=n+'='
c=0
for(i=2;;){if(n%i<1){c++
n/=i}else{if(c)s+=i+'^'+c+'*'
c=0
if(++i>n)break}}
alert(s)

```

120

```
n=prompt()
o={2:0}
for(i=2,c=n;i<=c;)!(c%i)?++o[i]?c/=i:0:o[++i]=0
s=n+'='
for(i in o)s+=o[i]?i+'^'+o[i]+'*':''
alert(s)

```
> 0 votes

# Answer
# PHP, 112 bytes

```
<?=$a=$argn,"=";for($i=2;1<$a;)$a%$i?$i++:$a/=$i+!++$r[$i];foreach($r as$k=>$v)echo$t?"*":!++$t,$v<2?$k:"$k^$v";

```

Try it online!
> 0 votes

# Answer
# PHP, 93 bytes

```
<?=$n=$argn;for($i=2;$n>1;$k&&$p=print($p?"*":"=")."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;

```

I could do 89 bytes with PHP 5.5 (or later), but that postdates the challenge by more than 2 years:

```
<?=$n=$argn;for($i=2;$n>1;$k&&$p=print"=*"[$p]."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;

```

Run as pipe with `-nF` or try them online.
> 0 votes

# Answer
# Japt, 24 bytes

```
+'=+Uk ü ËÎ+DÅÊÎç^+DÊÃq*

```

Try it
> 0 votes

# Answer
# Go, 199 bytes

```
type M=map[int]int
func f(n int)M{m:=make(M)
for x,i:=n,2;i<=n;i++{if func(p int)int{if p<4{return p}else{for i:=2;i*i<=p;i+=2{if p%i==0{return-1}}}
return p}(i)>0{for x%i==0{m[i]++;x/=i}}}
return m}

```

Attempt This Online!

Returns a map where the keys are the bases, and the values are exponents. So `131784 => map[2:3 3:1 17:2 19:1]`
> 0 votes

---
Tags: code-golf, number-theory, primes, restricted-time, factoring
---


title: Finding the Value of Words!

text:
# Question
Title: Finding the Value of Words!
# Introduction

In the land of \[Insert cool name here\], people don't buy things with money, because everyone has a severe allergy to paper. They pay eachother with words! But how is that? Well, they give each letter number values:

```
a=1,b=2,c=3,etc.

```

(With some other special rules that will be described later)

In this challenge, your task will be to calculate the value of sentences.

# Challenge

You will take an input which will be a sentence. You may assume the input has no newlines or trailing spaces. The challenge will be to calculate the value of the sentence, using these rules:

```
a=1,b=2,c=3,etc.

```
* A capital letter is worth 1.5 times it's corresponding lowercase letter

`H=h*1.5`

So, the word

```
cab

```

Would be worth `c+a+b = 3+1+2 = 6`

But the word `Cab` with a capital c would be worth `(c*1.5)+a+b = 4.5+1+2 = 7.5` So if your program input was "Cab" your program would output 7.5

* All non alphabetic characters are worth 1.

This is code golf, so shortest answer in bytes wins. Good luck!

# Answer
> 13 votes
# Python 3, ~~71~~ ~~65~~ 61 bytes

```
lambda z:sum((ord(s)*1.5**(s<'_')-96)**s.isalpha()for s in z)

```

By an extraordinary coincidence, `(ord(s)-64)*1.5` is equal to `ord(s)*1.5-96`, so we only have to write `-96` once. The rest is pretty straight forward.

Edit: Shaved off some bytes using exponentiation shenanigans.

# Answer
> 5 votes
# Python 2, 120 102 bytes

Edit:

```
e=raw_input()
print sum([ord(l)-96for l in e if not l.isupper()]+[1.5*ord(l)-96for l in e if l.isupper()])

```

First submission, not so golfy but one has to start somewhere.

```
def s2(p):
 c=0
 for l in p:
  if l.isupper():
   c+=(ord(l.lower())-96)*1.5
  else:
   c+=ord(l)-96
 return c
print s(raw_input())

```

# Answer
> 5 votes
# Pyth, ~~23~~ 20 bytes

```
sm|*hxGrdZ|}dG1.5 1z

```

Live demo and test cases.

## Explanation

```
 m                 z    For each input character
    hxGrdZ              Get the value of it's lowercase form, or 0 for non-alphabetic characters
   *      |}dG1.5       Multiply it by 1 if it's lowercase, 1.5 if uppercase
  |               1     If it's still zero, it's a non-alphabetic character, so use 1 as its value
s                       Sum of all the values

```

Quite a few creative uses of booleans values as integers here.

## 23-byte version:

```
sm+*hxGJrdZ|}dG1.5!}JGz

```

Live demo and test cases.

# Answer
> 4 votes
# Julia, 63 bytes

```
s->sum(c->isalpha(c)?(64<c<91?1.5:1)*(c-(64<c<91?'@':'`')):1,s)

```

This simply sums an array constructed via a comprehension that loops over the characters in the input string and performs arithmetic on their codepoints.

Ungolfed:

```
function char_score(c::Char)
    (64 < c < 91 ? 1.5 : 1) * (c - (64 < c < 91 ? '@' : '`')) : 1
end

function sentence_value(s::String)
    sum(char_score, s)
end

```

Thanks to Glen O for fixing the approach.

# Answer
> 2 votes
# Stuck, ~~85~~ 43 Bytes

~~Yeah yeah, I know, Python is shorter.. :P~~ I'm using the same logic as Tryth now, for the most part.

```
s_"str.isalpha"fgl;l-|0Gc"_91<1.5;^*96-":++

```

Explanation:

```
s_                                            # Take input & duplicate
  "str.isalpha"fg                             # Filter for only alpha chars, save
                 l;l-|                        # Determine number of symbols in start string
                      0Gc                     # Get saved string, convert to char array
                         "_91<1.5;^*96-":     # Logic to find score for each letter
                                         ++   # Sum the list of nums, add to # of symbols

```

# Answer
> 2 votes
# Python 2, 101 bytes

```
v=0
for x in raw_input():v+=(ord(x.lower())-96)*(1.5 if ord(x)<96 else 1)if x.isalpha()else 1
print v

```

# Answer
> 1 votes
# CJam, 30 bytes

```
q:i91,64fm1.5f*32,5f-+1fe>f=:+

```

How this works (wow, I've never made one of these!):

```
   91,64fm1.5f*32,5f-+1fe>      Construct an array so that a[i] == score for chr(i)
q:i                             Read STDIN and convert to ASCII codes
                          f=    Index each from the array
                            :+  Sum the result

```

# Answer
> 1 votes
# Javascript (ES6), ~~85~~ ~~82~~ ~~80~~ 67 bytes

I love quick & easy challenges like this. :)

```
t=>[...t].map(c=>u+=(v=parseInt(c,36)-9)>0?v*(c>'Z'||1.5):1,u=0)&&u

```

This works by interpreting each char as a base-36 number, multiplying it by 1 or 1.5 if it's greater than 9 (`a-z` or `A-Z`), and giving 1 instead if not. As always, suggestions welcome!

# Answer
> 1 votes
# F#, 168 bytes

Not really golfed yet, but a start:

```
fun(w:string)->w|>Seq.map(fun c->if Char.IsLetter c then (if Char.IsUpper(c) then (float)(Math.Abs(64-(int)c))*1.5 else (float)(Math.Abs(96-(int)c))) else 1.0)|>Seq.sum

```

Here a more readable version:

```
let calc (w : string) =
    w
    |> Seq.map (fun c -> if Char.IsLetter c then (if Char.IsUpper(c) then (float)(Math.Abs(64 - (int)c)) * 1.5 else (float)(Math.Abs (96 - (int)c))) else 1.0)
    |> Seq.sum

```

# Answer
> 1 votes
# MATLAB, 68 bytes

This takes advantage of the fact that characters are automatically casted to integers, and that boolean values can be summed as integers.

```
sum([t(t>96&t<132)-96,(t(t>64&t<91)-64)*1.5,t<65|(t>90&t<97)|t>122])

```

# Answer
> 1 votes
# K, 30

```
+/1^(,/1 1.5*(.Q`a`A)!\:1+!26)

```

.

```
k)+/1^(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
349f

```

How it works:

`.Q`a`A` generates two lists of lowercase and uppercase letters

```
k).Q`a`A
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

```

`!:1+til 26`maps each letter in each list from 1 to 26

```
k)(.Q`a`A)!\:1+!26
"abcdefghijklmnopqrstuvwxyz"!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

```

Multiply the first list by 1, the last by 1.5

```
k)1 1.5*(.Q`a`A)!\:1+!26
"abcdefghijklmnopqrstuvwxyz"!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26f
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"!1.5 3 4.5 6 7.5 9 10.5 12 13.5 15 16.5 18 19.5 21 22.5 24 25.5 27 28.5 30 31.5 33 34.5 36 37.5 39

```

Raze into a single dictionary using `,/`

```
k)(,/1 1.5*(.Q`a`A)!\:1+!26)
a| 1
b| 2
c| 3
d| 4
..

```

Map the characters in the input string to the relevant scores

```
k)(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
24 18 15 7 18 1 13 13 9 14 7 0n 24 21 26 26 12 5 19 0n 0n 0n 4.5 15 4 5 0n 10.5 15 12 6

```

Fill any null values with 1

```
k)1^(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
24 18 15 7 18 1 13 13 9 14 7 1 24 21 26 26 12 5 19 1 1 1 4.5 15 4 5 1 10.5 15 12 6

```

Sum

```
k)+/1^(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
349f

```

# Answer
> 1 votes
# JavaScript, 121 bytes

```
l=process.argv[2].split(""),r=0;for(k in l)c=l[k],o=c.toLowerCase(),r+=(o.charCodeAt(0)-96)*(o===c?1:1.5);console.log(r);

```

call js file with node (node index.js "Cab")

# Answer
> 1 votes
# Perl 5, 77 bytes

```
@_=split//,$ARGV[0];$i+=(ord)*(/[a-z]/||/[A-Z]/*1.5||96/ord)-96for@_;print$i

```

Tested on `v5.20.2`.

# Answer
> 0 votes
# Python 3: 86 85 Bytes

```
t=0
for c in input():k=ord(c)-64;t+=k*1.5if 0<k<27else k-32if 32<k<59else 1
print(t)

```

# Answer
> 0 votes
# C# 81 Bytes

```
decimal a(string i){return i.Sum(c=>c>64&&c<91?(c-64)*1.5m:c>96&&c<123?c-96:1m);}

```

Call with (LinqPad):

```
a("Hello World").Dump();

```

# Answer
> 0 votes
# PHP, 102 bytes

```
foreach(str_split($argv[1])as$c){$v=ord($c)-64;$s+=A<=$c&&$c<=Z?1.5*$v:(a<=$c&&$c<=z?$v-32:1);}echo$s;

```

Usage example:

```
$ php -d error_reporting=0 value.php cab
6
$ php -d error_reporting=0 value.php Cab
7.5
$ php -d error_reporting=0 value.php 'Programming Puzzles & Code Golf'
349

```

Nothing special in the algorithm. Each character from the first program's argument (`$argv[1]`) is checked against `A` and `Z` then `a` and `z` and counted accordingly.

# Answer
> 0 votes
# PowerShell, 108 Bytes

Decently competitive, I'm kinda surprised. Not too shabby for not having a compact Ternary operator.

### Code:

```
$a=[char[]]$args[0];$a|%{$b=$_-64;If($b-in(1..26)){$c+=$b*1.5}ElseIf($b-in(33..58)){$c+=$b-32}Else{$c++}};$c

```

### Explained:

```
$a=[char[]]$args[0]                # Take command-line input, cast as char array
$a|%{                              # For each letter in the array
  $b=$_-64                         # Set $b as the int value of the letter (implicit casting), minus offset
  If($b-in(1..26)){$c+=$b*1.5}     # If it's a capital, multiply by 1.5.
                         # Note that $c implicitly starts at 0 the first time through
  ElseIf($b-in(33..58)){$c+=$b-32} # Not a capital
  Else{$c++}                       # Not a letter
  }
$c                                 # Print out the sum

```

# Answer
> 0 votes
# C, 85 bytes

```
float f(char*s){return(*s-96)*!!islower(*s)+1.5*(*s-64)*!!isupper(*s)+(*++s?f(s):0);}

```

The `!!` before `islower` and `isupper` are necessary, because the boolean values returned by these functions are not guaranteed to be `0` and `1` , true value was `1024` on my system indeed !

# Answer
> 0 votes
# Candy, ~~26~~ 22 bytes

~~(~"a"\<{A#64-2/3\*|A#96-}h)Z~~

Thanks to @Tryth for the factorization trick!

```
(~"a"<{A2/3*|A}#96-h)Z

```

Invokation is with the -I flag, as in `candy -I "Cab" -e $prg`

The code in it's long form is:

```
while     # loop while able to consume characters from stack
  peekA   # A gets stack to
  "a"
  less    # is pop() < "a"
  if
    pushA   # capitalized
    digit2
    div
    digit3
    mult
  else
    pushA   # lower case
  endif
  number
  digit9
  digit6
  sub
  popAddZ   # add pop() to counter register Z
endwhile
pushZ       # push Z onto stack as answer

```

# Answer
> 0 votes
# Prolog (SWI), 101 bytes

**Code:**

```
X*Y:-X>64,X<91,Y is X*1.5-96;X>96,X<123,Y is X-96.
_*1.
p(L):-maplist(*,L,A),sumlist(A,B),write(B).

```

**Explained:**

```
X*Y:-X>64,X<91,       % When X is upper case
     Y is X*1.5-96    %      Y is 1.5 times charvalue starting at 1
     ;X>96,X<123,     % OR when X is lower case
     Y is X-96.       %      Y is charvalue starting at 1
_*1.                  % ELSE Y is 1
p(L):-maplist(*,L,A), % Get list of charvalues for all chars in string
      sumlist(A,B),   % Take sum of list
      write(B).       % Print

```

**Example:**

```
p(`Cab`).
7.5

```

# Answer
> 0 votes
# PHP, 75 bytes

```
while(~$c=$argn[$i++])$r+=ctype_alpha($c)?ord($c)%32*(1+($c<a)/2):1;echo$r;

```

Run as pipe with `-nr` or try it online.

# Answer
> 0 votes
# Ruby, 48 bytes

```
->s{s.bytes.sum{_1>64&&_1<91?(_1-64)*1.5:_1-96}}

```

Attempt This Online!

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


title: Case Permutation

text:
# Question
Title: Case Permutation
Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input.

## Input

A string of printable standard ascii characters. Input should not be assumed to be all lowercase. Input will always be at least one character.

## Output

Every permutation of uppercase and lowercase for the inputted string (no duplicates). This should only change characters with a small and large version (numbers will stay the same). Each permutation must be output as a string or a list of characters; lists of singleton strings are not allowed.

## Examples

```
a1a
['a1a', 'a1A', 'A1a', 'A1A']

abc
['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC']

Hi!
['hi!', 'hI!', 'Hi!', 'HI!']

```

## Scoring

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

As a fun extra see how much additional effort it will take to handle the extended ascii characters, here is an extra test case:

```
ž1a -> ['ž1a', 'ž1A', 'Ž1a', 'Ž1A']

```

(your program does not need to support this)

# Answer
# Pyth, ~~13~~ ~~12~~ 11

```
{msrVQd^U2l

```

1 byte thanks to Leaky Nun!

Another byte thanks to Jakube!

Try it here or run a Test Suite

We create a list of lists True/False values by taking the cartesian product of the list `[0, 1]` with itself a number of times equal to the length of the input string. So each of the sublists has the same length as the input string. Then we apply the `r` function as a vector operation over the input and the list, so we get `r letter value` for each sub element. `r` with second argument zero is to lowercase and with one it is to upper case. This creates duplicates on non-letters, which means we need to remove duplicates from the result.
> 11 votes

# Answer
# Jelly, 6 bytes

```
żŒsŒpQ

```

This is a monadic link (function) that expects a string as left argument and returns a list of strings.

Handles non-ASCII characters. Try it online!

### How it works

```
żŒsŒpQ  Monadic link. Argument: s (string)

 Œs     Swapcase; change the case of all letters in s.
ż       Zipwith; pair each character with itself with changed case.
   Œp   Take the Cartesian product of all pairs.
     Q  Unique; deduplicate the Cartesian product.

```
> 8 votes

# Answer
# Python, ~~74~~ 71 bytes

```
f=lambda s:s and{r[0]+t for r in{s,s.swapcase()}for t in f(s[1:])}or{s}

```

Handles non-ASCII characters. Test it on Ideone.
> 5 votes

# Answer
# Oracle SQL 11.2, 276 bytes

```
WITH v AS(SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))SELECT w FROM(SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w FROM(SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v)START WITH p=1CONNECT BY PRIOR p=p-1)WHERE LENGTH(:1)=LENGTH(w);

```

Un-golfed

```
WITH v AS
( -- Split input into an array of characters
  SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)
)
SELECT w
FROM   ( -- Build every string combination
         SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w
         FROM   ( -- Merge upper and lower arrays, keep same position for each character, it allows to mix cases
                  SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v
                )
         START WITH p=1          -- Start with first character (either lowercase or uppercase)
         CONNECT BY PRIOR p=p-1  -- Add the next character (either lowercase or uppercase)
       )
WHERE LENGTH(:1)=LENGTH(w); -- Keep only full strings

```

Ugly as hell, must be more golfable.
> 5 votes

# Answer
## 05AB1E, 17 bytes

**Code:**

```
vyDš‚N0Êiâvy˜J})Ù

```

**Explained:**

```
vy                     # for each character in input
  Dš‚                  # create a pair of different case, eg: ['ž', 'Ž']
     N0Êiâ             # for all pairs but the first, take cartesian product
                         result will be a list of layered lists eg: [['ž', '1'], 'a']
            vy         # for each such list
              ˜J}      # deep flatten and join as a string eg: ž1a
                 )Ù    # wrap in array and remove duplicates

```

Try it online
> 4 votes

# Answer
# Brachylog, ~~25~~ 22 bytes

```
:ef:1fd.
:2ac.
@u.|@l.

```

This works as well as the lowercase/uppercase predicates of Prolog, therefore it works on non-ASCII letters too:

```
?- run("ž1a",Z).
Z = ["Ž1A", "Ž1a", "ž1A", "ž1a"] .

```

### Explanation

Unlike all other answers as of the moment I'm posting this, this does not use the cartesian product approach at all.

* Main Predicate

```
:ef       Split the Input string into a list of 1-char strings
   :1f    Find all valid outputs of predicate 1 with the previous list
          of outputs as input
      d.  Unify the Output with that list excluding all duplicates

```
* Predicate 1

This is used to apply uppercasing or lowercasing on each char of the input, thus computing one possible permutation. Using findall on this predicate in the main predicate allows to compute all possible permutations (with some duplicates).

```
    :2a       Apply predicate 2 on the each element of the Input
       c.     Unify the Output with the concatenation of the elements of
              the previous list

```
* Predicate 2

This is used to turn a character of the string into either its uppercase or its lowercase version.

```
    @u.       Unify the Output with the uppercase version of the Input
       |      Or
        @l.   Unify the Output with the lowercase version of the input

```
> 4 votes

# Answer
## Haskell, ~~69~~ 58 bytes

```
import Data.Char
mapM(\x->toLower x:[toUpper x|isAlpha x])

```

Try it online!

Edit: @Angs saved 11 bytes. Thanks!
> 4 votes

# Answer
# MATL, 13 bytes

```
tYov!Z}N$Z*Xu

```

**Try it online!**

### Explanation

```
t       % Implicit input string. Duplicate
Yo      % Change case of string
v       % Concatenate as a 2xN char array, where N is input length
!       % Transpose: Nx2 char array. Each row has different case, if letter
Z}      % Split into rows: gives N strings of 2 chars. Each char has different
        % case if it's a letter, or is repeated otherwise
N$      % Specify N inputs for next function
Z*      % Cartesian product of the N strings. Each combination is a row.
        % Repeated chars (i.e. non-letters) give rise to duplicate rows.
Xu      % Remove duplicate rows. Implicit display

```
> 3 votes

# Answer
## JavaScript (Firefox 30-57), ~~92~~ 90 bytes

```
f=([c,...s])=>c?[for(t of f(s))for(d of new Set(c.toUpperCase()+c.toLowerCase()))d+t]:['']

```

Edit: Saved 2 bytes because `new Set` will happily extract the unique characters from a string.
> 3 votes

# Answer
# Perl 6, 37 bytes

```
{[X~] '',|.comb.map:{unique .lc,.uc}}

```

Try it

### Explanation:

```
{
  [X[~]]                     # cross combine using &infix:<~> operator
    '',                      # empty string so that 1 character strings work
    |                        # flatten the following into outer list
      .comb                  # get every character from input string
      .map:                  # and map it with:
        { unique .lc, .uc }
}

```

### Test:

```
#! /usr/bin/env perl6

use v6.c;
use Test;

my &case-permutation = {[X~] '',|.comb.map: {unique .lc,.uc}}

my @tests = (
  'a1a' => <a1a a1A A1a A1A>,
  'abc' => <abc abC aBc aBC Abc AbC ABc ABC>,
  'Hi!' => <hi! hI! Hi! HI!>,
  'ž1a' => <ž1a ž1A Ž1a Ž1A>,
);

plan +@tests;

for @tests -> $_ (:key($input),:value($expected)) {
  is case-permutation($input).sort, $expected.sort, .gist
}

```

```
1..4
ok 1 - a1a => (a1a a1A A1a A1A)
ok 2 - abc => (abc abC aBc aBC Abc AbC ABc ABC)
ok 3 - Hi! => (hi! hI! Hi! HI!)
ok 4 - ž1a => (ž1a ž1A Ž1a Ž1A)

```
> 3 votes

# Answer
# Julia, ~~66~~ 60 bytes

```
!s=s>""?[~s[1:1]t for~=(ucfirst,lcfirst),t=!s[2:end]]∪[]:[s]

```

Try it online!
> 2 votes

# Answer
# Python, 69 bytes

```
import itertools as i;f=lambda s:set(i.product(*zip(s,s.swapcase())))

```
> 2 votes

# Answer
## Actually, 28 bytes

```
;╗l2r∙`"'Ö*£"£M╜@Z"iƒ"£MΣ`M╔

```

Try it online!

This program can handle non-ASCII characters, thanks to the magic of Python 3.

Explanation:

```
;╗l2r∙`"'Ö*£"£M╜@Z"iƒ"£MΣ`M╔
;╗                            save a copy of input to reg0
  l                           length of input
   2r                         [0,1]
     ∙                        Cartesian product with self (length of input) times
      `                  `M   map:
       "'Ö*£"£M                 push `Ö` (swapcase) if 1 else `` for each value in list
               ╜@Z              zip with input
                  "iƒ"£M        swap the case of those values
                        Σ       join string
                           ╔  unique elements

```
> 2 votes

# Answer
## C ~~229~~ 252 bytes

```
i,n,j,k,l;f(char *s){l=strlen(s);for(i=0;i<l;i++)s[i]=tolower(s[i]);int v[l];for(i=0;i<l;i++)v[i]=0;for(i=0;i<pow(2,l);i++){n=i,k=0;for(;n;k++){v[k]=n;n/=2;}for(j=0;j<l;j++){v[j]%=2;if(v[j])s[j]=toupper(s[j]);else s[j]=tolower(s[j]);}printf("%s ",s);}}

```

Ungolfed version:

```
void f(char *s)
{
  int i,num,k,l=strlen(s);
  for(i=0;i<l;i++)
     s[i]=tolower(s[i]);

   int v[l];
   for(i=0;i<l;i++)
     v[i]=0;

   for(i=0;i<pow(2,l);i++)
   {
      num=i,k=0;
      for(;num;k++)
      {
         v[k]=num;
         num/=2;
      }

      for(int j=0;j<l;j++)
      {
        v[j]%=2;

        if(v[j])
         s[j]=toupper(s[j]);
        else
         s[j]=tolower(s[j]);

      }
      printf("%s \n",s);

   }
}

```

Explanation:

* Accept the character string, convert the string to lowercase.
* Declare integer array of length equal to that of the string. Fill it with zeroes.
* Store the numbers from 0 to `2^strlen(s)`in binary form in an `int` array.( For a 3 byte string: 000,001,010...111)
* Depending on if a bit at a position is set or, toggle the case.
* Output the string for every possible combination.

Try it online!
> 2 votes

# Answer
## Hoon, 242 bytes

```
|=
t/tape
=+
l=(reap (pow 2 (lent t)) t)
%+
roll
(gulf 0 (dec (lent l)))
|=
{a/@ b/(set tape)}
=+
%+
turn
(gulf 0 (dec (lent t)))
|=
n/@
=+
t=(snag n t)
=+
k=(trip t)
?:
=(0 (cut 0 n^1 a))
?:
=((cuss k) t)
(cass k)
(cuss k)
t
(~(put in b) -)

```

Ungolfed:

```
|=  t/tape
=+  l=(reap (pow 2 (lent t)) t)
%+  roll  (gulf 0 (dec (lent l)))
|=  {a/@ b/(set tape)}
    =+  %+  turn  (gulf 0 (dec (lent t)))
      |=  n/@
      =+  t=(snag n t)
      =+  k=(trip t)
      ?:  =(0 (cut 0 n^1 a))
        ?:  =((cuss k) t)
              (cass k)
        (cuss k)
      t
    (~(put in b) -)

```

I'm not sure how much smaller this could be, unfortunately.

First, we set `l` equal to a list with 2^(length t) repetitions of `t`. Hoon doesn't have a `fac` function in the stdlib, but 2^n is always bigger than n!, so we simply map over the bigger list and use a `set` (hashmap) to de-duplicate entries.

We then fold over the list \[0..(length l)\], accumulating into a `(set tape)`. We need to do this instead of mapping over `l` directly because we also need to know what number repetition it is (`a`), but can't simply increment an accumulator due to Hoon being a pure language.

We map over \[0..(length t)\] (again so we have the current index), setting `t` to the nth character in the string, checking if the nth bye of `a` and inverting the case (cuss or cass, depending if it changes or not). The return type of this map is a `tape`.

We then put the string into our hashmap, and return the hashmap of all the strings.
> 1 votes

# Answer
# Tcl, 165 ~~181~~ bytes

```
set n -1
while {[incr n]<1<<[llength [set s [split $argv {}]]]} {puts [join [lmap c $s b [split [format %0[llength $s]b $n] {}] {string to[expr $b?{u}:{l}] $c}] ""]}

```

Improvements thanks to **sergiol**. Previous answer:

```
set s [split $argv {}]
set n -1
while {[incr n]<1<<[llength $s]} {set r ""
foreach c $s b [split [format %0[llength $s]b $n] {}] {set r $r[string [expr $b?{tou}:{tol}] $c]}
puts $r}

```

Uses a binary number to choose between upper/lower case when creating the output text.
> 1 votes

# Answer
# C, 216 bytes

```
k,i,j,p,n,m;z(char *c){n=-1;m=0;while(c[++n])if(c[n]>64&c[n]<90)c[n]+=32;else if(c[n]<'a'|c[n]>'z')m++;k=1<<(n-m);for(j=0;j<k;j++){for(i=0;i<n;i++){p=1<<i;putc((j&p)==p?toupper(c[i]):c[i],stdout);}putc(0xa,stdout);}}

```

This is ~~a different approach~~, the **same** approach as the other C answer.

Should I delete this, and put it under the other answer as a comment?

Let me explain with the **Ungolfed version**

```
k,i,j,p,n,m;
z(char * c) {
    int n=-1;       // We start at -1 because of forward incrementation
    int m=0;        // this will count the characters we don't have to manipulate
    while(c[++n])   // go until we reach '\0'
    {
        if(c[n]>='a'&c[n]<='z')c[n]-=32; // If we are lower case, then convert
        else if(c[n]<'A'|c[n]>'Z')m++;   // If we are neigther lower case
                                         // nor upper, then make a note
    }

    // get 2 ^ ("length" - "number of invonvertibles")
    k=1<<(n-m);
    for(j=0;j<k;j++) {      // go through the combinations
        for(i=0;i<n;i++) {  // for each combination go though the characters
            p=1<<i;         // for each character get it's bit position
            putc(
                // if the bit position is set (==1)
                (j&p)==p ?
                   tolower(c[i]) // convert
                   : c[i], // else: don't
                stdout);
        }
        putc(0xa, stdout);  // print a newline
    }
}

```
> 1 votes

# Answer
# Python3, 96 bytes

```
i=input().lower()
for l in{*__import__('itertools').product(*zip(i,i.upper()))}:print(*l,sep='')

```

Late to the party but still had a go. Thanks to DLosc for reminding me of the stuff I missed, giving me golfing tips and saving me a bunch of bytes. :)
> 1 votes

# Answer
## Wolfram Language (Mathematica), 55 bytes

```
""<>#&/@Union@Tuples[{#,ToUpperCase@#}]&@*Characters

```

Try it online!

is the transpose operator (and displays as a superscript **T** in Mathematica).
> 1 votes

# Answer
# Perl 5, 52 + 1 (`-n`) = 53 bytes

```
@k{glob s/./lc("{$&,").uc"$&}"/ger}++;say for keys%k

```

Try it online!
> 1 votes

# Answer
## Perl 5, 30 bytes

```
s/\pl/{\l$&,\u$&}/g;say<"$_ ">

```

Try it online!

Outputs an additional space at the end of the output.
> 1 votes

# Answer
# Attache, 39 bytes

```
&Cross[Sum@V]##Unique@V#SwapCase=>Chars

```

Try it online!

Similar to the perl answer. (I've lost my more interesting alternative, I should be posting those in the next few hours.)
> 1 votes

# Answer
# JavaScript (ES6), 103

Handles non-ASCII characters

```
(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a]

```

**Test**

```
f=(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a]

function test() { O.textContent = f(I.value).join('\n') }

test()
```

```
<input id=I oninput='test()' value='ž1a'>
<pre id=O></pre>
```
> 0 votes

# Answer
# Ruby, 52 bytes

```
->s{a,*b=s.map{[_1,_1.swapcase]}
a.product(*b).uniq}

```

Attempt This Online!
> 0 votes

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


title: Let's build a Staircase

text:
# Question
Title: Let's build a Staircase
We don't have enough (semi-)easy challenges for beginners. More and more of the easy ones are already taken. So I tried to come up with something that might be achievable by beginners, but that isn't a duplicate.

### Input:

A single string separated with your OS new-line (i.e. `\r\n`),
or an array with multiple strings.

### Output - *The Stairs*:

Remove all non-alphabetic and non-numeric symbols. So all that's left is `[A-Za-z0-9]`. And then 'build a stairs'; basically ordering them on length with the smallest at top and widest at the bottom.

### Challenge rules:

1. When two strings are of equal length, we merge them with each other as one big string (the order doesn't matter, so it could be from first to last or last to first, whichever of the two you prefer).
2. The rule above can stack when the merged strings are of equal length again (see test case 2).

### General rules:

* The input is STDIN and contains only ASCII characters. And the output is STDOUT.
* The case of the output must be the same as the input.
* ~~Each submission must be a full program able to compile and run, so not just a method/function.~~ EDIT: I'm rather new, so perhaps it's indeed better to use the default from now on, even though I prefer a full program myself. Sorry for everyone that has already posted a full program. Feel free to edit, and I'll try to not change the post mid-challenge next time.
* This is , so the shortest answer in bytes wins. I probably accept the shortest answer in a year from now.
Don't let code-golf answers discourage you from posting golfed non-codegolf languages like C# and alike! Try to come up with the shortest answer for any programming language.
* Feel free to use newer languages than this question.

---

### Test cases:

***Input 1:***

```
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do

```

***Output 1:***

```
Okthatwilldo
Thisisasampletext
Blablablasomemoretext
Thewoodmaybeofexcellentquality
thatyouwillhavetousetobuildstairs
orprettycrappyalmostfallingapartandfilledwithtermites

```

---

***Input 2:***

```
A
small
one
that
contains
equal
length
strings
for
the
special
rule

```

***Output 2:***

```
A                   Or alternatively:       A
length                                      length
oneforthe                                   theforone
smallequal                                  equalsmall
stringsspecial                              specialstrings
thatrulecontains                            containsrulethat

```

***Steps explained of 2:***

*First order on length:*

```
A
one
for
the
that
rule
small
equal
length
strings
special
contains

```

*First merge:*

```
A
oneforthe
thatrule
smallequal
length
stringsspecial
contains

```

*Second order on length:*

```
A
length
thatrule
contains
oneforthe
smallequal
stringsspecial

```

*Second merge:*

```
A
length
thatrulecontains
oneforthe
smallequal
stringsspecial

```

*Third order on length:*

```
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

```

---

***Input 3:***

```
Test,
test.
This
is
a
test.

```

***Output 3:***

```
a                   Or alternatively:       a
is                                          is
TesttestThistest                            testThistestTest

```

---

***Input 4:***

```
a
bc
d!
123

```

***Output 4:***

```
123     Or alternatively:    123
adbc                         dabc

```

# Answer
> 4 votes
## Husk, 11 bytes

```
ωȯmΣġLÖLmf□

```

Try it online!

Husk is younger than this challenge (which makes no difference officially, but still).

## Explanation

```
ωȯmΣġLÖLmf□  Implicit input (list of strings), say ["a","bc","d!","123"]
        mf□  Keep only alphanumeric chars of each: ["a","bc","d","123"]
ωȯ           Repeat until fixed point is reached:
      ÖL       Sort by length: ["a","d","bc","123"]
    ġL         Group by length: [["a","d"],["bc"],["123"]]
  mΣ           Concatenate each group: ["ad","bc","123"]
             Final result ["123","adbc"], print implicitly separated by newlines.

```

# Answer
> 4 votes
# Python 3, 264 Bytes

I'm not good at code golf so I'm confident this won't be the best Python 3 answer. This uses recursion and an ordered dict with all the words for each length.

```
from collections import*
def f(i):
 d = defaultdict(list)
 for l in i: x = "".join(c for c in l if c.isalnum());d[len(x)].append(x)
 n = (sorted(["".join(d[z]) for z in d.keys()], key=len))
 if n == i:return "\n".join(n)
 return f(n)
print(f(eval(input())))

```

Takes input from stdin as a list, for example, test it with this list:

```
['A', 'small', 'one', 'that', 'contains', 'equal', 'length', 'strings', 'for', 'the', 'special', 'rule']

```

Will output:

```
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

```

# Answer
> 4 votes
# Retina, ~~69~~ 63 bytes

```
[^\w¶]|_

{`\b((.)+)¶((?.)+)\b(?(2)(?!))
$1$3
O$`(.)+
$#1$*

```

Try it online!

# Answer
> 3 votes
# Oracle SQL 11.2, 346 bytes

The lines in the input string are separated by '¤'. That way it is not necessary to create a table to use as the input.

```
This is a sample text,¤that you will have to use to build stairs.¤The wood may be of excellent quality,¤or pretty crappy almost falling apart and filled with termites.¤Bla bla bla - some more text¤Ok, that will do
A¤small¤one¤that¤contains¤equal¤length¤strings¤for¤the¤special¤rule
Test,¤test.¤This¤is¤a¤test.¤

```

Query :

```
WITH v AS(SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))),r(s,i,l)AS(SELECT s,1,1 FROM v UNION ALL SELECT LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s)),ROW_NUMBER()OVER(PARTITION BY LENGTH(s)ORDER BY s),l+1 FROM r WHERE l<LENGTH(:1)AND i=1)SELECT s FROM r WHERE l=LENGTH(:1);

```

Un-golfed

```
WITH v AS
(
  -- Splits on ¤ and keeps only alphanum characters
  SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))
)
-- Recursive view
-- s : string
-- i : index of the string in case of duplicates
-- l : exit condition
,r(s,i,l)AS
(
  -- Start with every element of the input
  SELECT s,1,1 FROM v
  UNION ALL
  SELECT -- Concatenate elements of the same lengths
         LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s))
         -- Index of elements of the same length (listagg with over generates duplicates)
        ,ROW_NUMBER()OVER(PARTITION BY LENGTH(s) ORDER BY s)
        -- exit condition
        ,l+1 FROM r WHERE l<LENGTH(:1) AND i=1
)
-- Keep only the elements from the last iteration (automaticaly sorted on my system)
SELECT s FROM r WHERE l=LENGTH(:1)

```

# Answer
> 3 votes
# , 48 bytes

```
[:(/:#&>)[:(#&>,&.>//.])^:_(#~e.&AlphaNum_j_)&.>

```

Try it online!

## ungolfed

```
[: (/: #&>) [: (#&> ,&.>//. ])^:_ (#~e.&AlphaNum_j_)&.>

```

## explanation

* `(#~e.&AlphaNum_j_)&.>` remove non alphanum
* `(#&> ,&.>//. ])` combine same length items
* `^:_` keep combining until it stops changing
* `(/: #&>)` sort by length

# Answer
> 2 votes
## Haskell, 129 bytes

```
import Data.List
import Data.Char
l=length
print.(foldl(const.map concat.groupBy((.l).(==).l).sortOn l)=<<(filter isAlphaNum<$>))

```

Accepts and prints an array of strings. If the result can be returned from the function (in contrast to printed to stdout), you can omit the `print.` and save 6 bytes.

How it works (note, I use `x` for the input parameter which of course does not appear in the pointfree version above):

```
 (    )=<<(     )          -- (f =<< g) x is f (g x) x, so we fold over x with a
                           -- starting value of:
     filter isAlphaNum<$>x -- keep only alphanumeric chars in every line of x

                           -- during folding, I ignore the the elements of x.
                           -- However folding stops the repeatedly applied function
                           -- after (length x) steps, which is enough for combining
                           -- lines of equal length

 const                     -- ignore elements from x, deal only with start value
                sortOn l   -- sort lines from shortest to longest
      groupBy((.l).(==).l) -- group lines of equal length
    map concat             -- concatenate each group

print                      -- print result after (length x) iterations

```

# Answer
> 2 votes
# Python 3, ~~184~~ 180 bytes

```
def f(x):l=len;m=filter;y=sorted([''.join(m(str.isalnum,i))for i in x],key=l);*z,=m(l,[''.join(i for i in y if-~j==l(i))for j in range(l(y[-1]))]);y==z and+print(*z,sep='\n')or f(z)

```

A function that takes input, by argument, as a list of strings and prints the result to STDOUT. Execution raises an error (due to the use of the + operator before the print statement), but not before the output has been printed.

**How it works**

```
def f(x):                              Function with input of list of strings
l=len;m=filter                         Redefine much-used functions: len gives the length
                                       of an object and filter chooses those items from an
                                       iterable for which a function is true
[''.join(m(str.isalnum,i))for i in x]  Strip to leave only alphanumeric characters...
y=sorted(...,key=l)                    ...and sort by length, into y
''.join(i for i in y if-~j==l(i))      Concatenate equal length strings...
[...for j in range(l(y[-1]))]          ...for all possible string lengths...
*z,=(m(l,...))                         ...and remove empty strings by filtering by length
                                       (the empty string has length 0, and is thus false),
                                       into z
y==z and+print(*z,sep='\n')...         If no change after concatenation, no more equal
                                       length strings exist, so print result to STDOUT...
...or f(z)                             ...else pass new list to function

```

Try it on Ideone

# Answer
> 2 votes
# jq, 78 bytes

Expects "an array with multiple strings."

```
def g:group_by(length);map(scan("\\w+"))|g|until(all(length<2);map(add)|g)[][]

```

Try it online!

# Answer
> 1 votes
# Javascript ~~198~~ ~~188~~ ~~186~~ 179 bytes

This is my second longest golfed javascript program

```
s=>s.replace(/[^\w]|_/g,``,l=0).split(/\s/g).sort(g=(a,b)=>a[m=`length`]-b[m]).reduce((a,b,c)=>a+(a.split(/\s/g)[c-1][m]<b[m]?`
`:` `)+b).replace(/ /g,``).split`
`.sort(g).join`
`

```

Probably can be golfed further

# Answer
> 1 votes
# Pyth, 39 bytes

Back to golfing !

There is the program :

```
~~`=Qm:d"[\W_]"kQKYLmsd.glkolNb;WnKQ=KQ=yQ;jQ`~~
```

```
=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j

```

Test it here !

# Explanations

```
=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j       (Implicit) Assign evaluated imput to Q (In this case, an array)
=Q                                            Reassign a value to Q
  m          Q                                map a function over Q
   :d"[\W_]"k                                 Replace any special character with an empty string
              L           ;                   Declare a function y(b)
                      olNb                      Sort b by length
                  .glk                          Group strings of same length in arrays
               msd                              Concat each inner array
                           WnYQ      ;        While Y != Q (previous array is not equal to current array)
                               =YQ              Assign the current array to Y (Y=Q)
                                  =yQ           Assign y(Q) to Q (Q=yQ). Here, the assigned variable name is implicit
                                      j       Display the resulting array

```

# Answer
> 1 votes
# Pyth, 22 bytes

```
jlDusM.glkG@Ls++GrG1UT

```

Try it here.

Explanation:

```
jlDusM.glkG@Ls++GrG1UT
j                      join on newlines
 lD                     sort by length
   u                     run until duplicate result, return result (argument G, iteration number H)
    sM                    map concatenate elements
      .g                   group elements by function (argument k)
        l                   length
         k                   k
          G                 G
           @L             left map filter on presence (extra argument first)
             s             concatenate elements
              +             concatenate two items
               +             concatenate two items
                G             G (default = lowercase alphabet)
                 r 1          to uppercase
                  G            G
                    U        unary range [0..n)
                     T        T (default = 10)

```

# Answer
> 1 votes
# Jelly, 17 bytes

```
f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY

```

Try it online!

Not sure why `Ẏf¥€ØWṖ¤L€ĠịµÐLY` doesn't work...

Explanation:

```
f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY Full program
             µÐL  Execute the following until we get a result a second time
     ¤              The following as a nilad
  ØW                  [A-Za-z0-9_]
    Ṗ                 Remove last element (_)
f€                  Filter the left argument (current result) with the above nilad
       €            Left map
      L               Length
        Ġ           Group indices of same values, sort values
          ⁸         Left argument
         ị          Index on ^^ and ^
            €       Left map
           Ẏ          Concatenate elements
                Y Join on newlines (full program will display correctly)

```

# Answer
> 1 votes
# Perl 5, 112 bytes

```
@F=<>;while($n-@F){$n=@F;%k=();s/[^a-z0-9]//gi,$k{y///c}.=$_ for@F;@F=values%k}say $k{$_}for sort{$a<=>$b}keys%k

```

Try it online!

# Answer
> 1 votes
# Java 8, 268 bytes

A void lambda accepting a mutable `List<String>` (i.e. implements `add` and `remove`; e.g. `ArrayList`). Output is printed to standard out, delimited by newline, with a trailing newline. Cast to `Consumer<List<String>>`.

```
l->{int i=0,z;while(i<l.size())l.set(i,l.get(i++).replaceAll("\\W| ",""));while(l.size()>0){l.sort((s,t)->s.length()-t.length());String s=l.remove(0);for(i=0,z=s.length();l.size()>0&&l.get(0).length()==z;i++)s+=l.remove(0);if(i<1)System.out.println(s);else l.add(s);}}

```

Try It Online

This ended up being much longer than I expected. As Kevin observed, it's more complicated than it seems at first glance.

## Ungolfed lambda

```
l -> {
    int i = 0, z;
    while (i < l.size())
        l.set(i, l.get(i++).replaceAll("\\W| ", ""));
    while (l.size() > 0) {
        l.sort((s, t) -> s.length() - t.length());
        String s = l.remove(0);
        for (
            i = 0, z = s.length();
            l.size() > 0 && l.get(0).length() == z;
            i++
        )
            s += l.remove(0);
        if (i < 1)
            System.out.println(s);
        else
            l.add(s);
    }
}

```

First, I reduce the input in place to letters and numbers. I then process the inputs in groups by length. I append items to the first in the list until the next length is reached, removing them as I go. If only the first element was used, that will be the only string of that length, so it's printed. Otherwise, the joined string is added to the list for another iteration. I sort the list by length each iteration before use.

I started off with a lovely solution that used a priority queue to keep track of the intermediate strings. Unfortunately, `java.util.PriorityQueue<String>` is quite long (and using the raw type was longer), so it had to go.

# Answer
> 1 votes
# Japt v2.0a1 `-h`, 11 bytes

Input & output as arrays of strings.

```
£=mk\W üÊmq

```

Try it

```
£=mk\L üÊmq
                :Implicit input of string array U
£               :Map
  m             :  Map U
   k            :    Remove
    \W          :    /[^A-Z0-9]/gi
       ü        :  Sort & partition by
        Ê       :    Length
         m      :  Map
          q     :    Join
 =              :  Reassign to U for next iteration
                :Implicit output of last element

```

# Answer
> 1 votes
# JavaScript, 119 bytes

I feel like this should be much shorter ...

Includes 2 leading newlines in the output.

```
f=s=>s==(s.replace(/[^\w\n]|_/g,t=``).split`
`.sort((x,y)=>x[l=`length`]-y[l]).map(x=>t+=s==(s=x[l])?x:`
`+x),t)?t:f(t)

```

Try it online

# Answer
> 1 votes
# Perl 6, 85 bytes

```
{.&([o] {my@a;@a[+.comb]~=$_ for $_;@a.grep(~*)}xx$_).sort(+*.comb)}o*.map:{S:g/\W//}

```

Try it online!

Input and outputs as lists of strings.

# Answer
> 1 votes
# Pyth, 21 bytes

```
jusM.glkG:R"[^\w\d]"k

```

Input is a list of strings. Try it online here, or verify all the test cases here.

```
jusM.glkG:R"[^\w\d]"kQ   Implicit: Q=eval(input()), k=""
                         Trailing Q inferred
          R          Q   For each string in Q...
         : "[^\w\d]"     ... replace non-alphanumerics...
                    k    ... with k (empty string)
 u                       Repeat the following until a fixed point occurs, current as G:
    .g  G                  Group the elements of G...
      lk                   ... by length
                             Groups ordered by the result of the inner function, i.e. length
                             This means that, in the final iteration, this acts as a sort by length
  sM                       Concatenate each group back into a string
j                        Join the resulting list on newlines, implicit print

```

# Answer
> 1 votes
# Ruby, ~~95~~ 93 bytes

```
f=->a{b=a.map{_1.gsub /\W|_/,""}.group_by(&s=:size).map{_2*""}.sort_by &s
b[a.size-1]?a:f[b]}

```

Attempt This Online!

# Answer
> 1 votes
# Vyxal, 12 bytes

```
krv↔⁽LġṠÞṡ)Ẋ

```

Try it Online!

I/O as lists of lines

```
          )Ẋ # Repeat until no change...
  v          # To each...
   ↔         # Keep only characters from...
kr           # Alphanumeric chars
      ġ      # Group by...
    ⁽L       # Length
       Ṡ     # Concatenate each
        Þṡ   # Sort by length

```

# Answer
> 0 votes
# 05AB1E, 16 bytes

```
εžKÃ}»Δ¶¡é.γg}J»

```

Input as a list of strings.

Try it online or verify all test cases.

Could have been 14 bytes with `εžKÃ}Δé.γg}J}»` if `Δ` would work with a list of strings as well..

**Explanation:**

```
ε   }            # Map the (implicit) input-list of strings:
 žjÃ             #  Leave only the letters and digits of each string
                 #   i.e. ["a","bc","d!","123"] → ["a","bc","d","123"]
     »           # Join the list by newlines to a single string
                 #  i.e. ["a","bc","d","123"] → "a\nbc\nd\n123"
      Δ          # Loop until the string no longer changes:
       ¶¡        #  Split by newlines
                 #   i.e. "a\nbc\nd\n123" → ["a","bc","d","123"]
         .γ }    #  Group the strings by:
           g     #   Their length
                 #    i.e. ["a","bc","d","123"] → [["a,"d"],["bc"],["123"]]
             J   #  Join each group-list to a single string
                 #   i.e. [["a,"d"],["bc"],["123"]] → ["ad","bc","123"]
              »  #  Join this list by newlines again
                 #   i.e. ["ad","bc","123"] → "ad\nbc\n123"
                 # (and the result is output implicitly after the loop)
                 #  i.e. "123\nadbc"

```

# Answer
> -1 votes
## Powershell, Windows 10, 63 bytes

So input...

```
$n = @"
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do
"@

```

and code...

```
((($n -Split '\n').Replace(" ","")) -Replace '[\W]','')|Sort *h

```

That covers input/output 1, working on 2 and 3...

---
Tags: code-golf, string, ascii-art
---


title: Every possible pairing

text:
# Question
Title: Every possible pairing
Given an positive even integer \\$ n \\$, output the set of "ways to pair up" the set \\$ \[1, n\] \\$. For example, with \\$ n = 4 \\$, we can pair up the set \\$ \\{1, 2, 3, 4\\} \\$ in these ways:

* \\$ \\{\\{1, 2\\}, \\{3, 4\\}\\} \\$
* \\$ \\{\\{1, 3\\}, \\{2, 4\\}\\} \\$
* \\$ \\{\\{1, 4\\}, \\{2, 3\\}\\} \\$

This can more formally be described as the set of sets of pairs of integers such that those pairs exactly cover the set \\$ \[1, n\] \\$.

Note that because we're dealing with sets here, the order of the pairs is irrelevant. For example, \\$ \\{\\{1, 2\\}, \\{3, 4\\}\\} \\$ is considered the same as \\$ \\{\\{3, 4\\},\\{2, 1\\}\\} \\$.

For the same reason, the order of your output does not matter. However, your output may not contain duplicates.

* If you want, you can choose to operate on the set \\$ \[0, n) \\$ instead of \\$ \[1, n\] \\$
* If you want, you can choose to take the integer \\$ \frac n 2 \\$ as input, instead of \\$ n \\$

This is , so the shortest code in bytes wins.

## Test cases

```
2 -> {{{1, 2}}}
4 -> {{{1, 2}, {3, 4}}, {{1, 3}, {2, 4}}, {{1, 4}, {2, 3}}}
6 -> {{{1, 2}, {3, 4}, {5, 6}}, {{1, 2}, {3, 5}, {4, 6}}, {{1, 2}, {3, 6}, {4, 5}}, {{1, 3}, {2, 4}, {5, 6}}, {{1, 3}, {2, 5}, {4, 6}}, {{1, 3}, {2, 6}, {4, 5}}, {{1, 4}, {2, 3}, {5, 6}}, {{1, 4}, {2, 5}, {3, 6}}, {{1, 4}, {2, 6}, {3, 5}}, {{1, 5}, {2, 3}, {4, 6}}, {{1, 5}, {2, 4}, {3, 6}}, {{1, 5}, {2, 6}, {3, 4}}, {{1, 6}, {2, 3}, {4, 5}}, {{1, 6}, {2, 4}, {3, 5}}, {{1, 6}, {2, 5}, {3, 4}}}
8 -> {{{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {{1, 2}, {3, 4}, {5, 7}, {6, 8}}, {{1, 2}, {3, 4}, {5, 8}, {6, 7}}, {{1, 2}, {3, 5}, {4, 6}, {7, 8}}, {{1, 2}, {3, 5}, {4, 7}, {6, 8}}, {{1, 2}, {3, 5}, {4, 8}, {6, 7}}, {{1, 2}, {3, 6}, {4, 5}, {7, 8}}, {{1, 2}, {3, 6}, {4, 7}, {5, 8}}, {{1, 2}, {3, 6}, {4, 8}, {5, 7}}, {{1, 2}, {3, 7}, {4, 5}, {6, 8}}, {{1, 2}, {3, 7}, {4, 6}, {5, 8}}, {{1, 2}, {3, 7}, {4, 8}, {5, 6}}, {{1, 2}, {3, 8}, {4, 5}, {6, 7}}, {{1, 2}, {3, 8}, {4, 6}, {5, 7}}, {{1, 2}, {3, 8}, {4, 7}, {5, 6}}, {{1, 3}, {2, 4}, {5, 6}, {7, 8}}, {{1, 3}, {2, 4}, {5, 7}, {6, 8}}, {{1, 3}, {2, 4}, {5, 8}, {6, 7}}, {{1, 3}, {2, 5}, {4, 6}, {7, 8}}, {{1, 3}, {2, 5}, {4, 7}, {6, 8}}, {{1, 3}, {2, 5}, {4, 8}, {6, 7}}, {{1, 3}, {2, 6}, {4, 5}, {7, 8}}, {{1, 3}, {2, 6}, {4, 7}, {5, 8}}, {{1, 3}, {2, 6}, {4, 8}, {5, 7}}, {{1, 3}, {2, 7}, {4, 5}, {6, 8}}, {{1, 3}, {2, 7}, {4, 6}, {5, 8}}, {{1, 3}, {2, 7}, {4, 8}, {5, 6}}, {{1, 3}, {2, 8}, {4, 5}, {6, 7}}, {{1, 3}, {2, 8}, {4, 6}, {5, 7}}, {{1, 3}, {2, 8}, {4, 7}, {5, 6}}, {{1, 4}, {2, 3}, {5, 6}, {7, 8}}, {{1, 4}, {2, 3}, {5, 7}, {6, 8}}, {{1, 4}, {2, 3}, {5, 8}, {6, 7}}, {{1, 4}, {2, 5}, {3, 6}, {7, 8}}, {{1, 4}, {2, 5}, {3, 7}, {6, 8}}, {{1, 4}, {2, 5}, {3, 8}, {6, 7}}, {{1, 4}, {2, 6}, {3, 5}, {7, 8}}, {{1, 4}, {2, 6}, {3, 7}, {5, 8}}, {{1, 4}, {2, 6}, {3, 8}, {5, 7}}, {{1, 4}, {2, 7}, {3, 5}, {6, 8}}, {{1, 4}, {2, 7}, {3, 6}, {5, 8}}, {{1, 4}, {2, 7}, {3, 8}, {5, 6}}, {{1, 4}, {2, 8}, {3, 5}, {6, 7}}, {{1, 4}, {2, 8}, {3, 6}, {5, 7}}, {{1, 4}, {2, 8}, {3, 7}, {5, 6}}, {{1, 5}, {2, 3}, {4, 6}, {7, 8}}, {{1, 5}, {2, 3}, {4, 7}, {6, 8}}, {{1, 5}, {2, 3}, {4, 8}, {6, 7}}, {{1, 5}, {2, 4}, {3, 6}, {7, 8}}, {{1, 5}, {2, 4}, {3, 7}, {6, 8}}, {{1, 5}, {2, 4}, {3, 8}, {6, 7}}, {{1, 5}, {2, 6}, {3, 4}, {7, 8}}, {{1, 5}, {2, 6}, {3, 7}, {4, 8}}, {{1, 5}, {2, 6}, {3, 8}, {4, 7}}, {{1, 5}, {2, 7}, {3, 4}, {6, 8}}, {{1, 5}, {2, 7}, {3, 6}, {4, 8}}, {{1, 5}, {2, 7}, {3, 8}, {4, 6}}, {{1, 5}, {2, 8}, {3, 4}, {6, 7}}, {{1, 5}, {2, 8}, {3, 6}, {4, 7}}, {{1, 5}, {2, 8}, {3, 7}, {4, 6}}, {{1, 6}, {2, 3}, {4, 5}, {7, 8}}, {{1, 6}, {2, 3}, {4, 7}, {5, 8}}, {{1, 6}, {2, 3}, {4, 8}, {5, 7}}, {{1, 6}, {2, 4}, {3, 5}, {7, 8}}, {{1, 6}, {2, 4}, {3, 7}, {5, 8}}, {{1, 6}, {2, 4}, {3, 8}, {5, 7}}, {{1, 6}, {2, 5}, {3, 4}, {7, 8}}, {{1, 6}, {2, 5}, {3, 7}, {4, 8}}, {{1, 6}, {2, 5}, {3, 8}, {4, 7}}, {{1, 6}, {2, 7}, {3, 4}, {5, 8}}, {{1, 6}, {2, 7}, {3, 5}, {4, 8}}, {{1, 6}, {2, 7}, {3, 8}, {4, 5}}, {{1, 6}, {2, 8}, {3, 4}, {5, 7}}, {{1, 6}, {2, 8}, {3, 5}, {4, 7}}, {{1, 6}, {2, 8}, {3, 7}, {4, 5}}, {{1, 7}, {2, 3}, {4, 5}, {6, 8}}, {{1, 7}, {2, 3}, {4, 6}, {5, 8}}, {{1, 7}, {2, 3}, {4, 8}, {5, 6}}, {{1, 7}, {2, 4}, {3, 5}, {6, 8}}, {{1, 7}, {2, 4}, {3, 6}, {5, 8}}, {{1, 7}, {2, 4}, {3, 8}, {5, 6}}, {{1, 7}, {2, 5}, {3, 4}, {6, 8}}, {{1, 7}, {2, 5}, {3, 6}, {4, 8}}, {{1, 7}, {2, 5}, {3, 8}, {4, 6}}, {{1, 7}, {2, 6}, {3, 4}, {5, 8}}, {{1, 7}, {2, 6}, {3, 5}, {4, 8}}, {{1, 7}, {2, 6}, {3, 8}, {4, 5}}, {{1, 7}, {2, 8}, {3, 4}, {5, 6}}, {{1, 7}, {2, 8}, {3, 5}, {4, 6}}, {{1, 7}, {2, 8}, {3, 6}, {4, 5}}, {{1, 8}, {2, 3}, {4, 5}, {6, 7}}, {{1, 8}, {2, 3}, {4, 6}, {5, 7}}, {{1, 8}, {2, 3}, {4, 7}, {5, 6}}, {{1, 8}, {2, 4}, {3, 5}, {6, 7}}, {{1, 8}, {2, 4}, {3, 6}, {5, 7}}, {{1, 8}, {2, 4}, {3, 7}, {5, 6}}, {{1, 8}, {2, 5}, {3, 4}, {6, 7}}, {{1, 8}, {2, 5}, {3, 6}, {4, 7}}, {{1, 8}, {2, 5}, {3, 7}, {4, 6}}, {{1, 8}, {2, 6}, {3, 4}, {5, 7}}, {{1, 8}, {2, 6}, {3, 5}, {4, 7}}, {{1, 8}, {2, 6}, {3, 7}, {4, 5}}, {{1, 8}, {2, 7}, {3, 4}, {5, 6}}, {{1, 8}, {2, 7}, {3, 5}, {4, 6}}, {{1, 8}, {2, 7}, {3, 6}, {4, 5}}}

```

# Answer
# Jelly, 9 bytes

```
Œ!HĊĠ€Ṣ€Q

```

Try it online!

```
Œ!           All permutations of [1 .. n].
  H          Halve each number in each permutation
   Ċ         rounding up,
    Ġ€       group indices of equal values in each,
      Ṣ€     sort each index-grouping,
        Q    and uniquify.

```
> 7 votes

# Answer
# Vyxal `R`, 9 bytes

```
Ṗƛ2ẇvss;U

```

Try it Online!

Takes \\$n\\$ as input.

```
Ṗƛ2ẇvss;U
Ṗ         # Permutations of [1, n]
 ƛ        # For each:
  2ẇ      #  Split into chunks of length 2
    vs    #  Sort each
      s   #  Sort
       ;  # Close map
        U # Uniquify

```

# Vyxal, 9 bytes

```
dɾ2ḋḋ'fÞu

```

Try it Online!

Port of caird's Jelly answer, takes \\$\frac{n}{2}\\$ as input.

```
dɾ2ḋḋ'fÞu
d         # Double, n × 2
 ɾ        # Range [1, that]
  2ḋ      # Combinations without replacement of length 2
    ḋ     # Combinations without replacement of length {input}
     '    # Filter for:
      fÞu #  Is it unique after flattening?

```
> 5 votes

# Answer
# Curry (PAKCS), 44 bytes

```
f n=g[1..n]
g[]=[]
g(a:b++c:d)=(a,c):g(b++d)

```

Try it online!

This is a non-deterministic function whose return values are the all the ouputs.
> 5 votes

# Answer
# Python, 84 bytes

```
def f(n,o={}):(n>sum(1>o[K]!=f(n-1,o|{K:n})for K in o)==f(n-1,o|{n:0}))==n==print(o)
```

Attempt This Online!

Using dictionaries instead of sets.

### Previous Python, 91 bytes

```
def f(n,*o):[f(n-1,*{*o}^{(K,n),K})for K in o if-1*K][n-1:]or f(n-1,*o,n)if n else print(o)
```

Attempt This Online!

Takes `n` and prints all unique pairings.

How?

Counting down `n` either add the current value to an existing unfinished pair or start a new pair. One can check that this visits each pairing exactly once.
> 5 votes

# Answer
# 05AB1E, 10 bytes

```
Lœε2ô€{{}ê

```

Try it online or verify all test cases.

Alternative with the same byte-count (thanks to *@CommandMaster*):

```
L©.Ææʒ˜{®Q

```

Try it online or verify all test cases.

**Explanation:**

```
L          # Push a list in the range [1, (implicit) input]
 œ         # Get all permutations of this list
  ε        # Map over each permutation:
   2ô      #  Split it into parts of size 2
     €{    #  Sort each inner pair
       {   #  Then sort all pairs
  }ê       # After the map: sort and uniquify the list of lists of pairs
           # (which in this case is faster than just an uniquify)
           # (after which the result is output implicitly)

L          # Push a list in the range [1, (implicit) input]
 ©         # Store this list in variable `®` (without popping)
  .Æ       # Create all sorted unique pairs of this list
    æ      # Get the powerset of this list of pairs
     ʒ     # Filter each inner list of pairs by:
      ˜    #  Flatten it to a single list
       {   #  Sort it
        ®Q #  Check if it's equal to list [1,input] from variable `®`
           # (after which the filtered list is output implicitly)

```
> 4 votes

# Answer
# Python, ~~101~~ ~~98~~ 94 bytes

```
def f(r,*x):
 if r:a,*r=r;[f({*r}-{b},*x,(a,b))for b in r]
 else:print(x)
def g(n):f(range(n))

```

Attempt This Online!

Takes \\$n\\$ as input, operates on the set \\$\[0,n)\\$, prints tuples of tuples.

---

-3 bytes from @Unrelated String by using splatting instead of passing in an array
-4 bytes from @pxeger by using list comprehension
> 4 votes

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
Map[Union,{#~Partition~2&/@Permutations@Range@#},3]&

```

Try it online!

Input \\$n\\$. Returns a list of pair-lists, wrapped in a list.

```
Map[Union,{#~Partition~2&/@Permutations@Range@#},3]&
                           Permutations@Range@#     permutations
           #~Partition~2&/@                           pair
          {                                    }        increase depth by 1
Map[Union,                                      ,3]     unique all

```

Since `Map` does not apply at level `0` by default, wrapping the output with `{ }` saves 2 bytes over including that level explicitly, e.g. with `Map[Union,...,{0,2}]` or `u@Map[u=Union,...,2]`.

-1 if output wrapped in a `Derivative[1]` rather than a `List` is acceptable.
> 4 votes

# Answer
# Haskell, 60 bytes

```
f n=g[1..n]
g[]=[[]]
g(h:t)=[(h,e):x|e<-t,x<-g$filter(e/=)t]
```

Attempt This Online!

Not sure if it can be improved.
> 4 votes

# Answer
# , ~~95~~ 92 bytes

```
f=\(n,v=1:n,a={},`+`=list)`if`(n,sapply(seq(v)[-1],\(i,b=c(1,i))f(n-2,v[-b],c(+v[b],a))),+a)
```

Attempt This Online!
> 3 votes

# Answer
# Factor \+ `math.combinatorics`, 75 bytes

```
[ iota [ natural-sort ] dup '[ 2 group _ map @ ] map-permutations members ]

```

Try it online!

Uses \\$\[0..n)\\$ instead of \\$\[1..n\]\\$ to save a byte.

This would be more clearly written as

```
[ iota [ 2 group [ natural-sort ] map natural-sort ] map-permutations members ]

```

However, `natural-sort` is so long it's shorter to stick in a quotation, dup it, and fry them into the `map-permutations` quotation appropriately. I'll explain the second version since the first version constructs it.

* `iota` Get an integer range from 0 inclusive to the input exclusive.
* `[ ... ] map-permutations` Apply `[ ... ]` to each permutation of the above range and collect the results in a new sequence.
* `2 group` Group a sequence into pairs. e.g. `{ 1 2 3 4 }` -\> `{ { 1 2 } { 3 4 } }`.
* `[ natural-sort ] map` Sort each pair.
* `natural-sort` Sort the sequence of pairs.
* `members` Take the unique elements of a sequence.
> 3 votes

# Answer
# Jelly, 10 bytes

```
ŒcœcHFQƑ$Ƈ

```

Try it online!

## How it works

```
ŒcœcHFQƑ$Ƈ - Main link. Takes n on the left
Œc         - Unordered pairs
    H      - Halve
  œc       - Combinations without replacement of length n/2
        $Ƈ - Keep those for which the following is true:
     F     -   When flattened,
       Ƒ   -   the list is unchanged after
      Q    -   deduplication

```
> 2 votes

# Answer
# Husk, 10 bytes

```
umȯOmOC2Pḣ

```

Try it online!

Range () =\> permutations (`P`) =\> map (`m`) 3 functions (`ȯ`) over each: cut into sublists of 2 (`C2`), sort each sublist (`mO`), and sort each (`O`) =\> finally keep only unique elements (`u`).
> 2 votes

# Answer
# Python, 124 bytes

*Thanks to user `Steffan` for -4 bytes.*

Takes the integer \\$ \frac n 2 \\$ as input and operates on the set \\$ \[0, n) \\$. Outputs a set of tuples of tuples.

```
lambda n:{t for t in c(sorted(c(range(2*n),2)),n)if len(sum(t,()))==len({*sum(t,())})}
from itertools import*;c=combinations

```

Attempt This Online!
> 2 votes

# Answer
# Ruby, 68 bytes

```
->n{[*1..n].permutation.map{|c|c.each_slice(2).map(&:sort).sort}|[]}

```

Try it online!
> 2 votes

# Answer
# SageMath, 35 bytes

```
lambda n:PerfectMatchings(n).list()
```

Try it on SageMathCell!
> 2 votes

# Answer
# Rust, 225 bytes

My other attempts where even longer. So much `collect().collect()..`

```
fn f(e:u8)->Vec<Vec<(u8,u8)>>{let g=|t,e|if t+1<e{t+1}else{t+2};if e==0{vec![vec![]]}else{(1..e).flat_map(|q|f(e-2).iter().map(|o|o.iter().map(|m|(g(m.0,q),g(m.1,q))).chain([(0,q)]).collect()).collect::<Vec<_>>()).collect()}}

```
> 2 votes

# Answer
# Rust, <sup>~~191~~</sup> 186 bytes

```
fn f(e:u8)->Vec<Vec<[u8;2]>>{if e>0{(1..e).flat_map(|q|{let mut k=f(e-2);for r in&mut k{for m in r.iter_mut(){for n in m{*n+=(*n>=q)as u8}}r.push([q,e])}k}).collect()}else{vec![vec![]]}}
```

Attempt This Online!

A golfed version of mousetail's solution.

-5 bytes thanks to alephalpha. Didn't realize that `r.iter_mut()` can save a separate `for r in &mut k`.

List of changes:

* I decided to remove `.collect::<Vec<_>>()` right inside `flat_map` in favor of taking an owned Vec (that is returned from `f(e-2)`) and modifying it.
* Then, since both fields of `(u8,u8)` are being modified using the same formula, I decided to change its type to `[u8;2]` and iterate over it instead.
* Finally, switching to 1-based solution saved a few bytes related to arithmetic.
> 2 votes

# Answer
# lin, 52 bytes

```
.\n $`.n `t2`comb.n2/ `comb \; `#
`flat dup `uniq `=

```

Try it here! Returns an iterator with 0-indexed results.

For testing purposes (use `-i` flag if running locally):

```
6 ; `_ wrap_
.\n $`.n `t2`comb.n2/ `comb \; `#
`flat dup `uniq `=

```

## Explanation

Assuming even integer input *n* (`.\n`).

* ``$ `.n `t` push range `[0..n)`
* `2`comb` length-2 combinations
* `.n2/ `comb` length-(*n*/2) combinations
* `\; `#` filter...
    + ``flat dup `uniq `=` check if element flattened is unique
> 2 votes

# Answer
# Pip, 20 bytes

```
UQ(SNSN*_CHa/2MPM,a)

```

Try It Online!

Operating on the range \\$\[0,n)\\$ instead of \\$\[1,n\]\\$.

I'm just porting some of the other answers here like the Jelly and Vyxal one, so hopefully it is right.
> 2 votes

# Answer
# Pyth, ~~12~~ 11 bytes

```
{mSSMcd2.PS

```

Try it online!

```
{mSSMcd2.PS
          S  Range from 1 to the input
        .P   Permutations
 m           For each permutation:
     cd2      - Chop into chunks of size 2
   SM         - Sort each chunk
  S           - Sort the list of chunks
{            Deduplicate

```
> 1 votes

# Answer
# JavaScript (V8), 112 bytes

Prints space-separated lists of comma-separated 0-indexed values.

```
f=(n,i=0,m,o,g=j=>++j<n?g(j,m&(q=1<<i|1<<j)||f(n,i,m|q,[o]+[i,j]+' ')):f(n,i+1,m,o))=>2**n+~m?i<n&&g(i):print(o)

```

Try it online!
> 1 votes

# Answer
# Jelly, 10 bytes

```
Œ!s2Ṣ€ṢƊ€Q
```

Attempt This Online!

Now that it's been beaten, I'll post my own answer (also previously shared in chat).

Explanation:

```
Œ!            permutations of (implicit range from 1 to) n
       Ɗ€     for each permutation:
  s2            split into chunks of 2
    Ṣ€          sort each pair
      Ṣ         sort the list of pairs
         Q    remove duplicates

```
> 1 votes

# Answer
# Charcoal, 59 bytes

```
Ｎθ⊞υ⟦⟧Ｆ⊗θ«≔⟦⟧ηＦυ«Ｆ⌕ＡＥκＬλ¹⊞ηＥκ⎇⁻λνμ⁺μ⟦ι⟧¿‹Ｌκθ⊞η⊞Ｏκ⟦ι⟧»≔ηυ»Ｉη

```

Try it online! Link is to verbose version of code. Takes `ⁿ⁄2` as input. Explanation:

```
Ｎθ

```

Input `ⁿ⁄2`.

```
⊞υ⟦⟧

```

Start with a pairing of no numbers.

```
Ｆ⊗θ«

```

Loop from `0` to `n`.

```
≔⟦⟧η

```

Start collecting pairings

```
Ｆυ«

```

Loop over the existing pairings.

```
Ｆ⌕ＡＥκＬλ¹

```

Loop over the unpaired numbers in this pairing.

```
⊞ηＥκ⎇⁻λνμ⁺μ⟦ι⟧

```

Pair the current number with that unpaired number.

```
¿‹Ｌκθ⊞η⊞Ｏκ⟦ι⟧

```

If there is room then also add the number as an unpaired number.

```
»≔ηυ

```

Save the resulting pairings.

```
»Ｉη

```

Output the final pairings.
> 1 votes

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

```
f=(n,[i,...a]=[...Array(n)].map((_,i)=>i+1))=>i?a.flatMap(j=>f(n,a.filter(k=>k-i&&k-j)).map(r=>[[i,j],...r])):[[]]

```

Attempt This Online!
> 1 votes

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


# Question
Title: Calculate the binary split sum of a word
Take a string, `s` containing printable ASCII-characters as input, and output its "binary split sum". Need an explanation?

**How do you get the binary split sum?**

We'll use the string `A4` as an example in the following explanation.

* Convert the characters to binary, treating each letters as a 7-bit ASCII character

```
A -> ASCII 65 -> 1000001
4 -> ASCII 52 -> 0110100

```
* Concatenate the binary numbers into a new binary number

```
A4 -> 1000001 & 0110100 -> 10000010110100

```
* Split the new binary number into chunks, where no `1` can have a `0` to its left. You should not split consecutive `1`s.

```
10000010110100 -> 100000, 10, 110, 100

```
* Convert these binary numbers to decimal

```
100000, 10, 110, 100 -> 32, 2, 6, 4

```
* Take the sum of these numbers:

```
32 + 2 + 6 + 4 = 44

```

So, the output for the string `A4` should be `44`.

---

**Test cases:**

```
a
49

A4
44

codegolf
570

Hello, World!
795

```

# Answer
> 13 votes
# Python 2, ~~86~~ ~~81~~ 76 bytes

-5 bytes thanks Adnan
-5 bytes thanks xnor

```
s=0
for c in input():s=s*128+ord(c)
print eval(bin(s).replace('01','0+0b1'))

```

Try it online!

`for c in input():s=s*128+ord(c)` to do the ASCII conversion numerically, where `*128` is used to left shift `s` 7 times (steps 1 and 2)
`eval(('0'+new_bin).replace('01','0+0b1'))` to split and sum (steps 3, 4 and 5)

# Answer
> 7 votes
# Jelly, 13 bytes

```
Oḅ128BŒg;2/ḄS

```

Try it online!

### How it works

```
Oḅ128BŒg;2/ḄS  Main link. Argument: s (string)

O              Ordinal; map characters to their code points.
 ḅ128          Unbase 128; convert the resulting list from base 128 to integer.
     B         Binary; Convert the resulting integer to base 2.
      Œg       Group consecutive, equal bits.
        ;2/    Concatenate all non-overlapping pairs.
           Ḅ   Unbinary; convert from base 2 to integer.
            S  Take the sum.

```

# Answer
> 6 votes
# MATL, 14 bytes

```
YB!'1+0*'XXZBs

```

Try it online!

### Explanation

Consider input `'A4'` as an example.

```
YB        % Implicit input. Convert to binary using characters '0' and '1'.
          % Gives a char matrix, where each row corresponds to a number
          % STACK: ['1000001'; '0110100']
!         % Transpose. This is necessary because MATL uses column-major
          % order when linearizing a matrix into a vector
          % STACK: ['10'; '01'; '01'; '00'; '01'; '00'; '10']
'1+0*'    % Push this string: regexp pattern
          % STACK: ['10'; '01'; '01'; '00'; '01'; '00'; '10'], '1+0*'
XX        % Regexp. Linearizes the first input into a row (in column-major
          % order), and pushes a cell array of substrings that match the
          % pattern given by the second input
          % STACK: {'100000'; '10'; 110'; '100'}
ZB        % Convert each string into a decimal number. Gives numeric vector
          % STACK: [32; 2; 6; 4]
s         % Sum. Implicitly display
          % STACK: 44

```

# Answer
> 5 votes
# 05AB1E, 18 bytes

Code:

```
Çžy+b€¦JTR021:2¡CO

```

Explanation:

```
Ç                   # Take the ASCII value of each character
 žy+                # Add 128 to each value (to pad each with enough zeros)
    b               # Convert to binary
     €¦             # Remove the first character
       J            # Join the array
        TR021:      # Replace 01 by 021
              2¡    # Split on the number 2
                C   # Convert from binary to decimal
                 O  # Sum them all up

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 5 votes
# 05AB1E, 14 bytes

```
Çžy+b€¦Jγ2ôJCO

```

A port of my Jelly answer, using the 128 offset from Adnan's 05ab1e answer (rather than the 256 in the Jelly answer I wrote).

**Try it online!**

### How?

```
Çžy+b€¦Jγ2ôJCO
Ç              - to ordinals
   +           - add
 žy            - literal 128
    b          - to binary
     €         - for each
      ¦        -   dequeue
       J       - join
        γ      - group into chunks of equal elements
          ô    - split into chunks of
         2     - literal 2
           J   - join
            C  - from binary
             O - sum

```

# Answer
> 3 votes
## JavaScript (ES6), ~~97~~ 92 bytes

```
s=>eval(s.replace(/./g,c=>(128+c.charCodeAt()).toString(2).slice(1)).replace(/1+/g,'+0b$&'))

```

Edit: Saved 5 bytes with some help from @ConorO'Brien.

# Answer
> 3 votes
# Japt, ~~18~~ 12 bytes

```
c_¤ùT7Ãò< xÍ
c_           // Firstly, take the input and map over it as charcodes.
  ¤          // Take the binary representation of each item
   ùT7       // and left-pad it with zeroes to standardize the items.
      Ã      // After all of the above,
       ò<    // partition the result where ever a 0 precedes a 1.
          xÍ // Then sum the numbers from base 2.

```

Takes input as a single string.
I also tried out the 128 or 256 addition used by other answers, but 0-padding was shorter to use.

Shaved off a whole whopping 6 bytes thanks to ETHproductions and Oliver.

Try it out here.

# Answer
> 2 votes
# Jelly, ~~16~~ 15 bytes

-1 byte thanks to Dennis (no need to flatten by 1 when a full flatten is fine - replace `;/` with `F`)

```
O+⁹Bṫ€3FŒg;2/ḄS

```

**Try it online!**

### How?

```
O+⁹Bṫ€3FŒg;2/ḄS - Main link: list of characters, s    e.g. "A4"
O               - cast to ordinal (vectorises)        [65,52]
  ⁹             - literal 256
 +              - add (vectorises)                    [321, 308]
   B            - convert to binary (vectorises)      [[1,0,1,0,0,0,0,0,1],[1,0,0,1,1,0,1,0,0]]
    ṫ€3         - tail €ach from index 3              [[1,0,0,0,0,0,1],[0,1,1,0,1,0,0]]
       F        - reduce with concatenation           [1,0,0,0,0,0,1,0,1,1,0,1,0,0]
        Œg      - group runs of equal elements        [[1],[0,0,0,0,0],[1],[0],[1,1],[0],[1],[0,0]]
          ;2/   - pairwise reduce with concatenation  [[1,0,0,0,0,0],[1,0],[1,1,0],[1,0,0]]
             Ḅ  - convert from binary (vectorises)    [32,2,6,4]
              S - sum                                 44

```

# Answer
> 2 votes
# PHP, 116 Bytes

```
for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);$t=mb_split("(?<=0)(?=1)",$r);echo array_sum(array_map(bindec,$t));

```

Online Version

# PHP, 117 Bytes

```
for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);$t=preg_split("#0\K(?=1)#",$r);echo array_sum(array_map(bindec,$t));

```

Try it online!

# PHP, 120 Bytes

```
for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);preg_match_all("#1+0+#",$r,$t);foreach($t[0]as$b)$s+=bindec($b);echo$s;

```

Try it online!

or

```
for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);preg_match_all("#1+0+#",$r,$t);echo array_sum(array_map(bindec,$t[0]));

```

# Answer
> 1 votes
# Pyth, 21 bytes

It's too long...

```
siR2:.BiCMQ128"1+0+"1

```

Test suite.

# Answer
> 1 votes
# \[F#\], ~~249~~ 245 bytes

```
open System
let rec c a=function|[]->[a]|'0'::'1'::y->(a+"0")::(c""('1'::y))|x::y->c(a+string x)y
let x i=c""(String.Join("",(Seq.map(fun c->Convert.ToString(int c,2).PadLeft(7,'0'))i))|>Seq.toList)|>Seq.map(fun c->Convert.ToInt32(c,2))|>Seq.sum

```

Try it online!

Note: the version on tio.run has "open System" in the header, I've added its count to the code above. I'm not sure what the rules are on imports.

# Ungolfed

```
let rec convert acc = function
    | [] -> [acc]
    | '0'::'1'::xs -> (acc + "0") :: (convert "" ('1'::xs))
    | x::xs -> convert (acc + string x) xs

let calculateSum input =
    let binary = Seq.map (fun x -> Convert.ToString(int x, 2).PadLeft(7, '0')) input

    String.Join("", binary)
    |> Seq.toList
    |> convert ""
    |>Seq.map (fun x -> Convert.ToInt32(x, 2))
    |>Seq.sum

```

# Answer
> 1 votes
# Ruby, 60 bytes

```
->s{s.bytes.map{"%07b"%_1}.join.scan(/1+0*/).sum{_1.to_i 2}}

```

Attempt This Online!

# Answer
> 0 votes
# Perl 6, 62 bytes

```
{sum map {:2(~$_)},.comb».ord».fmt('%07b').join~~m:g/11*0*/}

```

# Answer
> 0 votes
## mathematica 193 bytes

```
f=FromDigits;l=Flatten;(S=Split@l@Table[PadLeft[IntegerDigits[ToCharacterCode@#,2][[k]],7],{k,StringLength@#}];Plus@@Table[f[RealDigits@f@Join[S[[i]],S[[i+1]]],2],{i,1,Length@S-1,2}]+Last@l@S)&

```

# Answer
> 0 votes
# , 34 bytes

```
[:+/@(,#.;.1~1,1=2#.\,)(7#2)#:3&u:

```

Try it online!

## Explanation

```
[:+/@(,#.;.1~1,1=2#.\,)(7#2)#:3&u:  Input: array of characters S
                              3&u:  Get ASCII values of each character
                       (7#2)        Array with 7 copies of the value 2
                            #:      Convert each value to a base 2 array with length 7
[:  (                 )             Operate on those binary values
                     ,                Flatten it
                 2  \                 For each infix of size 2
                  #.                    Convert it to decimal from binary
               1=                     Test each value for equality to 1
             1,                       Prepend a 1
      ,                               The flattened binary values
         ;.1~                         Chop that at each occurrence of a 1
       #.                               Convert each chop from binary to decimal
 +/@                                Reduce by addition

```

# Answer
> 0 votes
# , 40 bytes

```
+/>#.&.>(1,}.|.1 0 E.|.b)<;.1 b=.,#:a.i.

```

usage:

```
+/>#.&.>(1,}.|.1 0 E.|.b)<;.1 b=.,#:a.i.'A4'

```

returns 44

# Answer
> 0 votes
## Clojure, 150 bytes

```
#(loop[[c & C](for[i % j[64 32 16 8 4 2 1]](mod(quot(int i)j)2))p 0 r 0 R 0](if c(if(=(dec c)p 0)(recur C c 1(+ R r))(recur C c(+(* 2 r)c)R))(+ R r)))

```

Well I was hoping the conversion from ASCII to bytes was shorter than this. The actual loop body is quite short, using `r` to accumulate the current result and `R` to accumulate the total result. If the previous bit `p` is `0` and the current bit `c` is `1` then we split a new chunk and accumulate to `R`, otherwise we update the `r` and keep `R` as it was.

# Answer
> 0 votes
# **Python** 123 bytes

```
lambda w:sum(map(lambda x:int(x,2),"".join(map(lambda x:bin(ord(x))[2:].zfill(7),list(w))).replace("01","0:1").split(":")))

```

Updated, thanks to Martin Ender.

# Answer
> 0 votes
# K (oK), 31 bytes

**Solution:**

```
+/2/'_[;x]&x&~~':x:,/(7#2)\'`i$

```

Try it online!

**Examples:**

```
+/2/'_[;x]&x&~~':x:,/(7#2)\'`i$,"a"
49
+/2/'_[;x]&x&~~':x:,/(7#2)\'`i$"A4"
44
+/2/'_[;x]&x&~~':x:,/(7#2)\'`i$"codegolf"
570
+/2/'_[;x]&x&~~':x:,/(7#2)\'`i$"Hello, World!"
795

```

**Explanation:**

Convert to ASCII values, convert to 7-bit binary, flatten, find where differs, and against original list to find where `1`s differ. Cut at these indices, convert back to decimal and sum up:

```
+/2/'_[;x]&x&~~':x:,/(7#2)\'`i$ / the solution
                            `i$ / convert to integer
                     (7#2)      / draw from 2, 7 times => 2 2 2 2 2 2 2
                          \'    / decode each (convert to binary)
                   ,/           / flatten
                 x:             / save as x
             ~~':               / not-not-each previous (differ)
            &                   / and with
           x                    / x
          &                     / indices where true
     _[;x]                      / projection, cut x at ...
  2/'                           / encode each (convert from binary)
+/                              / sum up

```

**Bonus**

Managed a **31 byte** version in K4 too, but as there's no TIO for it I'm posting my oK solution.

```
+/2/:'_[;x]@&x&~~':x:,/1_'0b\:'

```

# Answer
> 0 votes
# APL (Dyalog), 30 bytes

```
{+/2⊥¨(1∘+⊆⊢)∊¯7↑¨2⊥⍣¯1¨⎕UCS⍵}

```

Try it online!

**How?**

`⎕UCS⍵` \- Unicodify

`2⊥⍣¯1¨` \- encode each in binary

`¯7↑¨` \- and pad to the left with zeros to 7 places

\- flatten

`1∘+⊆⊢` \- partition by self increased by one

`2⊥¨` \- decode each from binary

`+/` \- sum

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

```
[ [ "%07b"sprintf ] map-concat R/ (?<=0)(?=1)/ re-split [ bin> ] map Σ ]

```

Try it online!

* `[ "%07b"sprintf ] map-concat` Convert each code point in the input string to a 7-bit binary number string and join them all together.
* `R/ (?<=0)(?=1)/ re-split` Split into a sequence of strings down the middle of every `01`.
* `[ bin> ] map Σ` Convert each from binary string to decimal integer and sum.

---
Tags: code-golf, string, base-conversion, binary
---