title: Fill In the Blanks

text:
# Question
Title: Fill In the Blanks
# Input

A nonnegative integer `n`, and a nonempty string `s` containing only alphanumeric characters and underscores `_`. The first character of `s` is not `_`. The underscores of `s` are interpreted as blank spaces that can be filled with other characters.

We define an infinite sequence of "infinite strings" as follows. The string `s<sub>1</sub> = s s s...` is just `s` repeated infinitely many times. For all `k > 1`, the string `s<sub>k+1</sub>` is obtained from `s<sub>k</sub>` by filling its blank spaces with the characters of `s<sub>1</sub>`, so that the first `_` of `s<sub>k</sub>` is replaced with `s<sub>1</sub>[0]`, the second with `s<sub>1</sub>[1]`, and so on. Since the first letter of `s` is not `_`, every blank space gets filled eventually, and we denote by `s` the infinite string where every `_` has been replaced by its eventual value.

# Output

The first `n` characters of `s` as a string.

# Example

Consider the inputs `n = 30` and `s = ab_c_`. We have

```
s<sub>1</sub> = ab_c_ab_c_ab_c_ab_c_ab_c_ab_c_ab_c_...
```

Substituting `s<sub>1</sub>` to the blanks of `s<sub>1</sub>`, we have

```
s<sub>2</sub> = abacbab_ccab_caabbc_abcc_abacbab_cc...
```

We again substitute `s<sub>1</sub>` to the blanks, which results in

```
s<sub>3</sub> = abacbabaccabbcaabbc_abcccabacbab_cc...
```

One more substitution:

```
s<sub>4</sub> = abacbabaccabbcaabbcaabcccabacbabbcc...
```

From this we can already deduce the first 30 characters of `s`, which are

```
abacbabaccabbcaabbcaabcccabacb

```

This is the correct output.

# Rules

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Crashing on incorrect input is acceptable.

# Test Cases

```
0  "ab__"    -> ""
1  "ab__"    -> "a"
3  "ab__"    -> "aba"
20 "ab"      -> "abababababababababab"
20 "ab__"    -> "abababababababababab"
20 "ab_"     -> "abaabbabaabaabbabbab"
30 "ab_c_"   -> "abacbabaccabbcaabbcaabcccabacb"
50 "ab_a_cc" -> "abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca"
50 "abc____" -> "abcabcaabcbcaaabcbcbcabcaaababccbcbabccabcabcaaaba"

```

# Answer
# Pyth, 17

```
<ussC,cG\_GUQ*zQQ

```

Input should be given with the string on the first line, and the length on the second, on STDIN. For example:

```
abc____
50

```

Try it here.

**Explanation:**

```
                             Implicit:
                             z = input()              z is the string.
                             Q = eval(input())        Q is the length.

<               Q            First Q characters of
 u         UQ*zQ             Reduce, with an initial value of z repeated Q times,
                             on the list range(len(Q)).
                             Since the reduce function doesn't use the sequence variable H
                             this function amounts to applying the inner code Q times to
                             the initial value, where the working variable is G.
  ss                         Sum from list of tuples of strings, to tuple of strings,
                             to string.
    C,                       Zip together
      cG\_                   G split on underscores
          G                  with G.
                             This inserts a character of G between every underscore
                             separated group of G, which amounts to replacing the
                             underscores with characters of G, after summation.

```
> 4 votes

# Answer
# CJam, ~~26~~ ~~24~~ 20 bytes

4 bytes saved thanks to Peter.

```
l~:I*{_'_/[\]zsI<}I*

```

Test it here. Takes the string first and `n` second on STDIN.

You can run all test cases by pasting them into the input as they are (include the `-> output` if you want), and using the following test harness (which reverses the order for the code):

```
qN/{"->"/0=S/W%S*

~:I*{_'_/[\]zsI<}I*

]oNo}/

```

## Explanation

```
l~:I*{_'_/[\]zsI<}I*
l~                       "Read the input and evaluate.";
  :I                     "Store n in I for future use.";
    *                    "Repeat s n times to ensure it's long enough for the output.";
     {           }I*     "Repeat this block n times. This will always be enough passes.";
      _                  "Duplicate the string.";
       '_/               "Split the string on underscores.";
          [\]            "Swap with the other copy, putting both in an array.";
             z           "Zip the two arrays together, interleaving substrings from the split
                          copy with characters from the unsplit copy. Extraneous
                          characters from the unsplit copy just go at the end and
                          can be ignored.";
              s          "Convert the result into a string, flattening the array in the
                          process. This basically joins the two interleaved strings together.";
               I<        "Truncate to n characters.";

```

The result is printed automatically at the end of the program.

**A note on `[\]`:** In principle, `[` remembers the current size of the stack and `]` collects everything down to the last remembered size in an array. However, if the array size falls below the remembered size in between, then the start of the array gets adjusted accordingly. Now you might think that swapping the top two array elements doesn't affect the array size at all, but `\` actually pops two value and then pushes them in reverse order. This is what pushes the start of the array down by two. Therefore, `[\]` is the shortest way to wrap the top two stack elements in an array. Sometimes, the side effect of collecting them in reverse order is quite annoying, but in this case, it's exactly what I need.
> 7 votes

# Answer
# APL ~~29~~ 28

```
{a⊣(b/a)←a↑⍨+/b←'_'=a←⍺⍴⍵}⍣≡

```

it's used like this:

```
fun←{a⊣(b/a)←a↑⍨+/b←'_'=a←⍺⍴⍵}⍣≡
20 fun 'ab_c_'
abacbabaccabbcaabbca

```

**Explanation:**

```
a←⍺⍴⍵           makes vector long as left argument using repeated chars in right argument
a↑⍨+/b←'_'=a   takes a string from the beginning of string a (a↑⍨), long as the number of _'s in a (+/b←'_'=a)
(b/a)←          puts those chars in place of the _'s in the original vector
a⊣             and returns a
{}⍣≡            repeats function ( {} ) until results doesn't change anymore

```

Tryapl.org
> 7 votes

# Answer
# Python 3, 110 bytes

```
n=int(input())
*b,=input()*n
a=b[:n]
while"_"in a:b,a=b[:],[x*(x!="_")or b.pop(0)for x in a]
print("".join(a))

```

Needs a fair bit more golfing, but here is some sheer insanity. Reads in `n` then `s` from STDIN.

The fun part is, in the loop's assignment we **copy `b`, then start popping from `b` during a list comprehension**. If the assignment was the other way around, it wouldn't work!
> 6 votes

# Answer
# k, 30

```
{{@[x;i;:;(#i:&"_"=x)#x]}/x#y}

```
> 4 votes

# Answer
# Java - 162 ~~174~~

It's not every day I get to use a do/while loop when golfing in Java :D

This just iterates and fills in blanks as they come. It just keeps going until there are no more `_` in the result.

```
char[]a(int n,char[]s){char[]o=new char[n];if(n>0)do for(int i=0,j=0;i<n;i++)if(o[i]==95|o[i]<1)o[i]=s[j++%s.length];while(new String(o).contains("_"));return o;}

```

With line breaks:

```
char[]a(int n,char[]s){
    char[]o=new char[n];
    if(n>0)
        do
            for(int i=0,j=0;i<n;i++)
                if(o[i]==95|o[i]<1)
                    o[i]=s[j++%s.length];
        while(new String(o).contains("_"));
    return o;
}

```
> 4 votes

# Answer
# Java 8, 238

```
(n,s)->{int i=0,j=0;for(s=String.join("",java.util.Collections.nCopies(n,new String(s))).toCharArray();j<1;){for(i=0;i<n;i++){for(;s[++j]!=95&j<n;);if(j<n)s[j]=s[i];}for(j=1,i=0;i<n;)j=s[++i]==95?0:1;}return java.util.Arrays.copyOf(s,n);}

```

Less golfed:

```
(Integer n, char[] s) -> {
    int i = 0, j = 0;
    for (s = String.join("", java.util.Collections.nCopies(n, new String(s))).toCharArray(); j < 1;) {
        for (i = 0; i < n; i++) {
            for (; s[j] != 95 & j < n; j++);
            if (j < n) {
                s[j] = s[i];
            }
        }
        for (j = 1, i = 0; i < n;) {
            j = s[++i] == 95 ? 0 : 1;
        }
    }
    return java.util.Arrays.copyOf(s, n);
}

```
> 3 votes

# Answer
## Haskell (93) 67

I haven't written any Haskell in a while, so this can probably be shortened by a lot. *but it was so good, we had to shorten it and make it better!*

```
('_':b)&(d:e)=d:b&e;(a:b)&c=a:b&c
f n s=take n$q where q=cycle s&q

```

Usage:

```
*Main> f 50 "ab_a_cc"
"abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca"

```
> 3 votes

# Answer
# Ruby, 60

```
->n,s{eval"r=%1$p.chars;s.gsub!(?_){r.next};"*n%s*=n;s[0,n]}

```

Concatenates `s` to itself `n` times, then generates `n` copies of code that replaces underscores with `s`, evaluates those copies, and returns the first `n` characters of the result. Since at least one underscore is removed in each loop, this is guaranteed to give us `n` underscore-free characters.
> 3 votes

# Answer
# Python 2, 75

```
n,s=input()
S='';c=0
for x in s*n:b=x=='_';S+=S[c:c+b]or x;c+=b
print S[:n]

```

This expects input like `(30,"ab_c_")`.

In Python, strings don't allow assignment. So, replacing the blanks with the desired character is hard. One can get around this by converting to a list and back, but I found it shorter to just generate the output string from scratch, adding on the desired characters one at a time.

The output being constructed is `S`, which starts empty. We loop through the characters of the input `s` copied many times to simulate a circle. We check if it's a blank via the Boolean `b`. We check equality `x=='_'` rather than comparison because the underscore lies between capital and lowercase letters.

If the character is not a blank, we just add it onto `S`. If it is blank, we add the next unused letter of the output-so-far `S`. We track used letters by an index pointer `c` that starts at 0 and is incremented each time we encounter a blank.

At the end, we print the first `n` characters of the resulting string `S`.

We have to use `S[c:c+b]` in place of the shorter `b*S[c]` because the latter gives an out-of-bounds error when `S` starts empty and `c` is 0. It never matters because we're guaranteed the first character of `s` is non-blank, so this `S[c]` is never needed, but the code doesn't know it. Flipping the `or` to short-circuit could also solve this, but costs more characters.

---

# Python 2, 83

A Pyth-to-Python port of isaacg's solution, which uses `split` and `zip` to perform the replacement:

```
n,s=input()
s*=n
exec"s=''.join(a+b for a,b in zip(s.split('_'),s));"*n
print s[:n]

```

It turned out longer because, suprise, named methods are long in python. But it can perhaps be improved by riffling `s` and `s.split('_')` together in a shorter way.
> 3 votes

# Answer
## Batch - 425

Do I lose?

```
@echo off&setLocal enableDelayedExpansion&set s=%2
if "%3"=="" (for /l %%a in (1,1,%1)do set o=!o!%s%)else set o=%3
set o=!o:~0,%1!&set l=0
:c
if defined s set/al+=1&set "s=%s:~1%"&goto c
set s=%2&set/ap=%1-1
set y=&set c=0&for /l %%a in (0,1,%p%)do set x=!o:~%%a,1!&if !x!==_ (for %%b in (!c!)do set y=!y!!s:~%%b,1!&set/ac+=1)else (set y=!y!!x!)&if !c!==%l% set c=0
if "!y:_=!"=="!y!" echo !y!&goto :EOF
%0 %1 %2 !y!

```

Batch has limitations - I accept this. For example; I had to use a for loop to get a single variable in a usable format due to limitations of variable parsing syntax. `for %%b in (!c!)do...` just exists so I can use `%%b` instead of `!c!` so I can actually do the string manipulation `!s:~%%b,1!` and have the variables expand at the correct time.

There are a couple of pretty basic things I could do to golf this further, but probably not below 400 bytes. I'll have another crack soon.
> 2 votes

# Answer
# ECMAScript 6, 78

```
f=(s,n,i=0)=>[...s.repeat(n)].reduce((s,x)=>s+(x=='_'?s[i++]:x),'').slice(0,n)

```

Starts off with an empty string and for every occurrence of underscore, replaces it with the character at the next index of the current string.
> 2 votes

# Answer
# Python 2 - ~~99~~ 97 bytes

---

Because 4 python-based submissions aren't enough...

```
n,s=input();S=s=s*n
while"_"in S:x=iter(s);S="".join(j>"_"and j or next(x)for j in S)
print S[:n]

```

Example:

```
$ python2 t.py
(50, "ab_a_cc")
abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca

```
> 1 votes

# Answer
# ECMAScript 6, ~~93~~ 91

```
(n,s)=>{for(x="_".repeat(n);n=0,/_/.test(x);)x=x.replace(/_/g,a=>s[n++%s.length]);return x}

```

Shaved off 2 characters from the first version.

```
(n,s)=>{x="_".repeat(n);while(/_/.test(x)){n=0,x=x.replace(/_/g,a=>s[n++%s.length])}return x}

```
> 0 votes

# Answer
# C# - 162

I stole Geobits solution and changed it to C#

```
char[]p(int n,string s){var r=new char[n];if(n>0)do for(int i=0,j=0;i<n;i++)if(r[i]=='_'||r[i]<1)r[i]=s[j++%s.Length];while(r.ToList().IndexOf('_')>=0);return r;}

```

1 char better, so you can improve Geobits ;)
> 0 votes

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


# Question
Title: Print all multiples of 32 from 0 to `n`...imperfectly
**Objective:** Print all multiples of 32 from 0 to an arbitrary number n.

**Rules:**

1. One argument will be given: a single integer from 0 to 231 \- 1. This will be `n` here on out.
2. The first iteration must be 0, and the last iteration must be `n`. 0 is to be counted as a multiple of 32.
3. Each time a multiple is encountered, the multiple itself must be printed with no leading whitespace, and then it must be immediately followed by a newline (CR, CRLF, and LF are all acceptable as long as they are consistent.
4. A bug must be introduced such that a minimum of `n+1 floor 32` cases are incorrectly printed/omitted (in the average case).

* Perfection is allowed for `n` less than or equal to 32.
5. Your source code must be in pure ASCII. Exceptions only include APL and others that use non-ASCII operators.
6. This is an contest. The best code is clear, concise, obvious, and wrong.

**Example in C++ (except for clear bug):**

```
// This conforms to the rules, but is a bad entry.
#include <iostream>
#include <cstdlib>
#include <cstdint>

int main(int argc, char* argv[]) {
  int32_t max = (int32_t) atol(argv[1]);
  int32_t i = 0;
  while (i != max) {
    if (!(i % 32) && !((int) (4 * random()) / 4)) {
      cout << i << endl;
    }
    i++;
  }
  return 0;
}

```

Most popular answer wins, so make it good!

# Answer
## C

```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    int n = atoi(argv[1]);
    for(int i = 0; i < n; i++) {
        if(i & 31 == 0) {
            printf("%d\n", i);
        }
    }
}

```
> 1 votes

# Answer
modified from the example.

```
#include <iostream>
#include <cstdlib>
#include <cstdint>

using namespace std;

int main(int argc, char* argv[]) {
  int32_t n = (int32_t) atol(argv[1]);
  int32_t i = 0;

  while (i != n) {
    if (!(i % 32) && n > 32 ? rand() % 4 != 0 : 1) {
      cout << i << endl;
    }
    ++i;
  }
  return 0;
}

```

Issues:

```
rule 1: 1 argument. check.
rule 2: first iteration must be 0.
            check.
        last iteration must be n.
            fail. "while (i != n)" means the last iteration is n - 1.
rule 3: print multiples of 32.
            check, except for the bug below
rule 4: print "n+1 floor 32" entries incorrectly.
            not sure what this means, but I certainly don't meet it. I chose to have each multiple of 32 have a 1 in 4 chance of being incorrectly omitted.
rule 5: allowable characters
            I didn't actually check, but I didn't intentionally break this rule.
rule #6: there is no rule #6
rule 6: underhanded
            the program actually prints all numbers from 1 to n - 1, except a random number of multiples of 32.
            the bug is in the operator precedence of the conditional operator:
                if (!(i % 32) && n > 32 ? ((rand() % 4) != 0) : 1) {
            the condition says "if i is a multiple of 32 AND n is greater than 32, (return true if a random number is a multiple of 4. return false if it is not). Otherwise, return true.
            all multiples of 32 have a 1 in 4 chanse of being omitted.
            all other numbers are always printed.
            the line should be:
                if (!(i % 32) && (n > 32 ? rand() % 4 != 0 : 1)) {

```
> 0 votes

---
Tags: popularity-contest, underhanded
---


# Question
Title: Split a word into parts with equal scores
Assuming A=1, B=2... Z=26, and the value of a word is the sum of these letter values, it is possible to split some words into two pieces such that they have equal values.

For example, "wordsplit" can be broken into two pieces like so: ordsl wpit, because o+r+d+s+l = w+p+i+t.

This was a challenge given to us by my computing teacher - it is an old Lionhead Studios challenge, apparently. I have solved it in Python, and will post my answer shortly.

**Challenge:** The shortest program which can list **all** the possible splits which have equal scores. Note that it only has to list one for each group of letters - ordsl wpit is the same as rdosl wtip, for example. It is easier to list them in the order they come in the word.

**Bonus:**

* If you highlight pairs where both words are valid English words (or some permutation of the letters is), using a word list of some kind. (This could be done by placing an asterisk next to each or some other method, but make it clear.)
* Adding the option for removing duplicates (this should not be the default.)
* Supporting more than two splits, for example, three, four or even n-way splits.

# Answer
> 4 votes
# Perl, 115 ~~118~~ ~~123~~

```
@_=~/./g;for$i(1..1<<@_){$l=$
r;$i&1<<$_?$l:$r+=64-ord$_[$_
]for 0..$#_;$l-$r||$i&1<<$_&&
print$_[$_]for 0..$#_;say""}

```

Run with `perl -nE '<code goes here>'`. That 'n' is counted in the code size.

## Respaced:

```
@_ = /./g;
for $i (1 .. 1<<@_) {
  $l = $r;
  $i & 1<<$_ ? $l : $r -= 64 - ord $_[$_] for 0 .. $#_;

  $l - $r      ||
  $i & 1<<$_   &&
  print $_[$_]
    for 0 .. $#_;

  say ""
}

```

## With comments and variable names:

```
# split a line of input by character
@chars = /./g;

# generate all binary masks of same length
for $mask (1 .. 1<<@_) {

  # start at "zero"
  $left_sum = $right_sum;

  # depending on mask, choose left or right count
  # 1 -> char goes left; 0 -> char goes right
  $mask & 1<<$_ ? $left_sum : $right_sum
    -= 64 - ord $chars[$_]   # add letter value
      for 0 .. $#chars;      # for all bits in mask

  # if left = right
  $left_sum - $right_sum ||

  # if character was counted left (mask[i] = 1)
  $mask & 1<<$_          &&

  # print it
  print $chars[$_]

  # ...iterating on all bits in mask
    for 0 .. $#chars;

  # newline
  say ""
}

```

## Some of the tricks used:

* `1..1<<@_` covers the same bit range as `0..(1<<@_)-1` , but is shorter. (note that considering the problem from further away, including the range boundaries multiple times wouldn't result in a wrong output anyway)
* $left\_range and $right\_range aren't reset to actual "0" numeric zero: since we just accumulate and compare them in the end, all we need is them to start at the same value.
* subtracting `64-ord$_[$_]` instead of adding `ord$_[$_]-64` wins an invisible character: since it ends with a delimiter, it makes the space before `for` unnecessary.
* Perl lets you assign to a variable determined by the ternary conditional operator: `cond ? var1 : var2 = new_value`.
* boolean expressions chained with `&&` and `||` are used instead of proper conditionals.
* `$l-$r` is shorter than `$l!=$r`
* will output a newline even on splits that don't balance. Empty lines are ok by the rules! I asked!

# Answer
> 3 votes
## J (109)

```
~.(/:{[)@:{&a.@(96&+)&.>>(>@(=/@:(+/"1&>)&.>)#[),}.@(split~&.>i.@#@>)@<@(96-~a.&i.)"1([{~(i.@!A.i.)@#)1!:1[1

```

Output for `wordsplit`:

```
┌─────┬─────┐
│lorw │dipst│
├─────┼─────┤
│diltw│oprs │
├─────┼─────┤
│iptw │dlors│
├─────┼─────┤
│dlors│iptw │
├─────┼─────┤
│oprs │diltw│
├─────┼─────┤
│dipst│lorw │
└─────┴─────┘

```

Explanation:

* `1!:1[1`: read a line from stdin
* `([{~(i.@!A.i.)@#)`: get all permutations
* `"1`: for each permutation:
* `(96-~a.&i.)`: get letter scores
* `}.@(split~&.>i.@#@>)@<`: split each permutation of the scores at each possible space, except before the first and after the last number
* `>(>@(=/@:(+/"1&>)&.>)#[)`: see which permutations have matching halves and select these
* `{&a.@(96&+)&.>`: turn the scores back into letters
* `~.(/:{[)`: remove trivial variations (e.g. `ordsl wpit` and `ordsl wpti`)

# Answer
> 2 votes
## c99 -- 379 necessary characters

```
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int s(char*w,int l,int m){int b,t=0;for(b=0;b<l;++b){t+=(m&1<<b)?toupper(w[b])-64:0;}return t;}
void p(char*w,int l,int m){for(int b=0;b<l;++b){putchar((m&1<<b)?w[b]:32);}}
int main(){char w[99];gets(w);int i,l=strlen(w),m=(1<<l),t=s(w,l,m-1);
for(i=0;i<m;i++){if(s(w,l,i)==t/2){p(w,l,i);putchar(9);p(w,l,~i);putchar(10);}}}

```

The approach is pretty obvious. There is a function which sums a words according to a mask and one that prints it also according to a mask. Input from the standard input. One oddity is that the printing routine inserts spaces for letter not in the mask. A tab is used to separate the groups.

I do none of the bonus items, nor is it easily converted to support them.

**Readable and commented:**

```
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int s(char *w, int l, int m){ /* word, length, mask */
  int b,t=0;                  /* bit and total */
  for (b=0; b<l; ++b){
/*     printf("Summing %d %d %c %d\n",b,m&(1<<b),w[b],toupper(w[b])-'A'-1); */
    t+=(m&1<<b)?toupper(w[b])-64:0; /* Add to toal if masked (A-1 = @ = 64) */
  }
  return t;
}
void p(char *w, int l, int m){
  for (int b=0; b<l; ++b){
    putchar((m&1<<b)?w[b]:32);  /* print if masked (space = 32) */
  }
}
int main(){
  char w[99];
  gets(w);
  int i,l=strlen(w),m=(1<<l),t=s(w,l,m-1);
/*   printf("Word is '%s'\n",w); */
/*   printf("...length %d\n",l); */
/*   printf("...mask   0x%x\n",m-1); */
/*   printf("...total  %d\n",t); */
  for (i=0; i<m; i++){
/*     printf("testing with mask 0x%x...\n",i); */
    if (s(w,l,i)==t/2) {p(w,l,i); putchar(9); p(w,l,~i); putchar(10);}
    /* (tab = 9; newline = 10) */
  }
}

```

**Validation**

```
 $ wc wordsplit_golf.c
  7  24 385 wordsplit_golf.c
 $ gcc -std=c99 wordsplit_golf.c
 $ echo wordsplit | ./a.out
warning: this program uses gets(), which is unsafe.
 or sp          w  d  lit
wor   l            dsp it
 ords l         w    p it
w    p it        ords l
   dsp it       wor   l
w  d  lit        or sp

```

# Answer
> 2 votes
# Ruby: 125 characters

```
r=->a{a.reduce(0){|t,c|t+=c.ord-96}}
f=r[w=gets.chomp.chars]
w.size.times{|n|w.combination(n).map{|s|p([s,w-s])if r[s]*2==f}}

```

Sample run:

```
bash-4.2$ ruby -e 'r=->a{a.reduce(0){|t,c|t+=c.ord-96}};f=r[w=gets.chomp.chars.to_a];w.size.times{|p|w.combination(p).map{|q|p([q,w-q])if r[q]*2==f}}' <<< 'wordsplit'
[["w", "o", "r", "l"], ["d", "s", "p", "i", "t"]]
[["w", "p", "i", "t"], ["o", "r", "d", "s", "l"]]
[["o", "r", "s", "p"], ["w", "d", "l", "i", "t"]]
[["w", "d", "l", "i", "t"], ["o", "r", "s", "p"]]
[["o", "r", "d", "s", "l"], ["w", "p", "i", "t"]]
[["d", "s", "p", "i", "t"], ["w", "o", "r", "l"]]

```

# Answer
> 1 votes
# Mathematica 123 111

Finds all subsets of word that have 1/2 the "ascii total" of the word, `d`. Then finds the complements of those subsets.

d = "WORDSPLIT"

```
{#, Complement[w, #]}&/@Cases[Subsets@#,x_/;Tr@x==Tr@#/2]&[Sort[ToCharacterCode@d - 64]];
FromCharacterCode[# + 64] & /@ %

```

> {{"IPTW", "DLORS"}, {"LORW", "DIPST"}, {"OPRS", "DILTW"}, {"DILTW", "OPRS"}, {"DIPST", "LORW"}, {"DLORS", "IPTW"}}

# Answer
> 1 votes
# J, 66 chars

Using digits of base2 numbers to select every possible subset.

```
   f=.3 :'(;~y&-.)"{y#~a#~(=|.)+/"1((+32*0&>)96-~a.i.y)#~a=.#:i.2^#y'
   f 'WordSplit'
┌─────┬─────┐
│Worl │dSpit│
├─────┼─────┤
│Wdlit│orSp │
├─────┼─────┤
│Wpit │ordSl│
├─────┼─────┤
│ordSl│Wpit │
├─────┼─────┤
│orSp │Wdlit│
├─────┼─────┤
│dSpit│Worl │
└─────┴─────┘

```

# Answer
> 0 votes
My solution is below. It is an almost anti-golf in its size, but it works very well. It supports n-way splits (although computational time becomes very long for any more than about 3 splits) and it supports removing duplicates.

```
class WordSplitChecker(object):
    def __init__(self, word, splits=2):
        if len(word) == 0:
            raise ValueError, "word too short!"
        if splits == 0:
            raise ValueError, "splits must be > 1; it is impossible to split a word into zero groups"
        self.word = word
        self.splits = splits

    def solve(self, uniq_solutions=False, progress_notifier=True):
        """To solve this problem, we first need to consider all the possible
        rearrangements of a string into two (or more) groups.

        It turns out that this reduces simply to a base-N counting algorithm,
        each digit coding for which group the letter goes into. Obviously
        the longer the word the more digits needed to count up to, so
        computation time is very long for larger bases and longer words. It
        could be sped up by using a precalculated array of numbers in the
        required base, but this requires more memory. (Space-time tradeoff.)

        A progress notifier may be set. If True, the default notifier is used,
        if None, no notifier is used, and if it points to another callable,
        that is used. The callable must take the arguments as (n, count,
        solutions) where n is the number of iterations, count is the total
        iteration count and solutions is the length of the solutions list. The
        progress notifier is called at the beginning, on every 1000th iteration,
        and at the end.

        Returns a list of possible splits. If there are no solutions, returns
        an empty list. Duplicate solutions are removed if the uniq_solutions
        parameter is True."""
        if progress_notifier == True:
           progress_notifier = self.progress
        solutions = []
        bucket = [0] * len(self.word)
        base_tuple = (self.splits,) * len(self.word)
        # The number of counts we need to do is given by: S^N,
        # where S = number of splits,
        #       N = length of word.
        counts = pow(self.splits, len(self.word))
        # xrange does not create a list in memory, so this will work with very
        # little additional memory.
        for i in xrange(counts):
            groups = self.split_word(self.word, self.splits, bucket)
            group_sums = map(self.score_string, groups)
            if len(set(group_sums)) == 1:
                solutions.append(tuple(groups))
            if callable(progress_notifier) and i % 1000 == 0:
                progress_notifier(i, counts, len(solutions))
            # Increment bucket after doing each group; we want to include the
            # null set (all zeroes.)
            bucket = self.bucket_counter(bucket, base_tuple)
        progress_notifier(i, counts, len(solutions))
        # Now we have computed our results we need to remove the results that
        # are symmetrical if uniq_solutions is True.
        if uniq_solutions:
            uniques = []
            # Sort each of the solutions and turn them into tuples.  Then we can
            # remove duplicates because they will all be in the same order.
            for sol in solutions:
                uniques.append(tuple(sorted(sol)))
            # Use sets to unique the solutions quickly instead of using our
            # own algorithm.
            uniques = list(set(uniques))
            return sorted(uniques)
        return sorted(solutions)

    def split_word(self, word, splits, bucket):
        """Split the word into groups. The digits in the bucket code for the
        groups in which each character goes in to. For example,

        LIONHEAD with a base of 2 and bucket of 00110100 gives two groups,
        "LIHAD" and "ONE"."""
        groups = [""] * splits
        for n in range(len(word)):
            groups[bucket[n]] += word[n]
        return groups

    def score_string(self, st):
        """Score and sum the letters in the string, A = 1, B = 2, ... Z = 26."""
        return sum(map(lambda x: ord(x) - 64, st.upper()))

    def bucket_counter(self, bucket, carry):
        """Simple bucket counting. Ex.: When passed a tuple (512, 512, 512)
        and a list [0, 0, 0] it increments each column in the list until
        it overflows, carrying the result over to the next column. This could
        be done with fancy bit shifting, but that wouldn't work with very
        large numbers. This should be fine up to huge numbers. Returns a new
        bucket and assigns the result to the passed list. Similar to most
        counting systems the MSB is on the right, however this is an
        implementation detail and may change in the future.

        Effectively, for a carry tuple of identical values, this implements a
        base-N numeral system, where N+1 is the value in the tuple."""
        if len(bucket) != len(carry):
            raise ValueError("bucket and carry lists must be the same size")
        # Increase the last column.
        bucket[-1] += 1
        # Carry numbers. Carry must be propagated by at least the size of the
        # carry list.
        for i in range(len(carry)):
            for coln, col in enumerate(bucket[:]):
                if col >= carry[coln]:
                    # Reset this column, carry the result over to the next.
                    bucket[coln] = 0
                    bucket[coln - 1] += 1
        return bucket

    def progress(self, n, counts, solutions):
        """Display the progress of the solve operation."""
        print "%d / %d (%.2f%%): %d solutions (non-unique)" % (n + 1, counts, (float(n + 1) / counts) * 100, solutions)

if __name__ == '__main__':
    word = raw_input('Enter word: ')
    groups = int(raw_input('Enter number of required groups: '))
    unique = raw_input('Unique results only? (enter Y or N): ').upper()
    if unique == 'Y':
        unique = True
    else:
        unique = False
    # Start solving.
    print "Start solving"
    ws = WordSplitChecker(word, groups)
    solutions = ws.solve(unique)
    if len(solutions) == 0:
        print "No solutions could be found."
    for solution in solutions:
        for group in solution:
            print group,
        print

```

Sample output:

```
Enter word: wordsplit
Enter number of required groups: 2
Unique results only? (enter Y or N): y
Start solving
1 / 512 (0.20%): 0 solutions (non-unique)
512 / 512 (100.00%): 6 solutions (non-unique)
dspit worl
ordsl wpit
orsp wdlit

```

# Answer
> 0 votes
# Lua - 195

```
a=io.read"*l"for i=0,2^#a/2-1 do z,l=0,""r=l for j=1,#a do b=math.floor(i/2^j*2)%2 z=(b*2-1)*(a:byte(j)-64)+z if b>0 then r=r..a:sub(j,j)else l=l..a:sub(j,j)end end if z==0 then print(l,r)end end

```

input must be in caps:

```
~$ lua wordsplit.lua
>WORDSPLIT
WDLIT   ORSP
DSPIT   WORL
WPIT    ORDSL

```

# Answer
> 0 votes
Python - 127

```
w=rawinput()
for q in range(2**len(w)/2):
 a=[0]*2;b=['']*2
 for c in w:a[q%2]+=ord(c)-96;b[q%2]+=c;q/=2
 if a[0]==a[1]:print b

```

and here a n-split Version with 182 bytes without duplicates:

```
n,w=input()
def b(q):
 a=[0]*n;b=['']*n
 for c in w:a[q%n]+=ord(c)-96;b[q%n]+=c;q/=n
 return a[0]==a[1] and all(b) and frozenset(b)
print set(filter(None,map(b,range(n**len(w)/n))))

```

Input is e.g.:

```
3, 'wordsplit'

```

---
Tags: code-golf, word
---