# Question
Title: Underhanded code contest: Not-so-quick sort
# The Task

Write a program, in the language of your choice, that reads lines of input from standard input until EOF, and then writes them to standard output in ASCIIbetical order, similar to the `sort` command-line program. A short, non-underhanded example in Python is:

```
import sys

for line in sorted(sys.stdin):
    print(line.rstrip('\n'))

```

# The underhanded part

Similar to The OS War, your goal is to prove that your favored platform is “better”, by having your program deliberately run much more slowly on a competing platform. For the sake of this contest, a “platform” consists of any combination of:

* Processor
    + Architecture (x86, Alpha, ARM, MIPS, PowerPC, etc.)
    + Bitness (64-bit vs. 32-bit vs. 16-bit)
    + Big- versus little-endian
* Operating System
    + Windows vs. Linux vs. Mac OS, etc.
    + Different versions of the same operating system
* Language implementation
    + Different compiler/interpreter vendors (e.g., MSVC++ vs. GCC)
    + Different versions of the same compiler/interpreter

Although you could meet the requirements by writing code like:

```
#ifndef _WIN32
    Sleep(1000);
#endif

```

Such an answer should not be upvoted. The goal is to be subtle. Ideally, your code should *look* like it's not platform-dependent at all. If you *do* have any `#ifdef` statements (or conditions based on `os.name` or `System.Environment.OSVersion` or whatever), they should have a plausible justification (based on a lie, of course).

# Include in your answer

* The code
* Your “favorite” and “unfavorite” platforms.
* An input with which to test your program.
* The running time on each platform, for the same input.
* A description of *why* the program runs so slowly on the unfavorite platform.

# Answer
# C

### CleverSort

CleverSort is a state-of-the-art (i. e. over-engineered and sub-optimal) two-step string sorting algorithm.

In step 1, it starts by pre-sorting the input lines using radix sort and the first two bytes of each line. Radix sort is non-comparative and works very well for strings.

In step 2, it uses insertion sort on the pre-sorted list of strings. Since the list is almost sorted after step 1, insertion sort is quite efficient for this task.

### Code

```
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Convert first two bytes of Nth line into integer

#define FIRSTSHORT(N) *((uint16_t *) input[N])

int main()
{
    char **input = 0, **output, *ptemp;
    int first_index[65536], i, j, lines = 0, occurrences[65536];
    size_t temp;

    // Read lines from STDIN

    while(1)
    {
        if(lines % 1000 == 0)
            input = realloc(input, 1000 * (lines / 1000 + 1) * sizeof(char*));

        if(getline(&input[lines], &temp, stdin) != -1)
            lines++;
        else
            break;
    }

    output = malloc(lines * sizeof(char*));

    // Radix sort

    memset(occurrences, 0, 65536 * sizeof(int));

    for(i = 0; i < lines; i++) occurrences[FIRSTSHORT(i)]++;

    first_index[0] = 0;

    for(i = 0; i < 65536 - 1; i++)
        first_index[i + 1] = first_index[i] + occurrences[i];

    memset(occurrences, 0, 65536 * sizeof(int));

    for(i = 0; i < lines; i++)
    {
        temp = FIRSTSHORT(i), output[first_index[temp] + occurrences[temp]++] = input[i];
    }

    // Insertion sort

    for(i = 1; i < lines; i++)
    {
        j = i;

        while(j > 0 && strcmp(output[j - 1], output[j]) > 0)
            ptemp = output[j - 1], output[j - 1] = output[j], output[j] = ptemp, j--;
    }

    // Write sorted lines to STDOUT

    for(i = 0; i < lines; i++)
        printf("%s", output[i]);
}

```

### Platforms

We all know that big-endian machines are much more efficient than their little-endian counterparts. For benchmarking, we'll compile CleverSort with optimizations turned on and create randomly a huge list (just over 100,000 strings) of 4-byte lines:

```
$ gcc -o cleversort -Ofast cleversort.c
$ head -c 300000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input
$ wc -l input
100011 input

```

### Big-endian benchmark

```
$ time ./cleversort < input > /dev/null

real    0m0.185s
user    0m0.181s
sys     0m0.003s

```

Not too shabby.

### Little-endian bechmark

```
$ time ./cleversort < input > /dev/null

real    0m27.598s
user    0m27.559s
sys     0m0.003s

```

Boo, little Endian! Boo!

### Description

Insertion sort is really rather efficient for almost-sorted lists, but it is horribly inefficient for randomly sorted ones.

CleverSort's underhanded part is the *FIRSTSHORT* macro:

```
#define FIRSTSHORT(N) *((uint16_t *) input[N])

```

On big-endian machines, ordering a string of two 8-bit integers lexicographically or converting them to 16-bit integers and ordering them afterwards yields the same results.

Naturally, this is possible on little-endian machines as well, but the macro should have been

```
#define FIRSTSHORT(N) (input[N][0] | (input[N][1] >> 8))

```

which works as expected on all platforms.

The "big-endian benchmark" above is actually the result of using the proper macro.

With the wrong macro and a little-endian machine, the list is pre-sorted by the **second** character of every line, resulting in a random ordering from the lexicographical point of view. Insertion sort behaves very poorly in this case.
> 31 votes

# Answer
# Python 2 vs. Python 3

Obviously, Python 3 is several orders of magnitude faster than Python 2. Let's take this implementation of the Shellsort algorithm as an example:

## Code

```
import sys
from math import log

def shellsort(lst):

    ciura_sequence = [1, 4, 10, 23, 57, 132, 301, 701]  # best known gap sequence (Ciura, 2001)

    # check if we have to extend the sequence using the formula h_k = int(2.25h_k-1)
    max_sequence_element = 1/2*len(lst)
    if ciura_sequence[-1] <= max_sequence_element:
        n_additional_elements = int((log(max_sequence_element)-log(701)) / log(2.25))
        ciura_sequence += [int(701*2.25**k) for k in range(1,n_additional_elements+1)]
    else:
        # shorten the sequence if necessary
        while ciura_sequence[-1] >= max_sequence_element and len(ciura_sequence)>1:
            ciura_sequence.pop()

    # reverse the sequence so we start sorting using the largest gap
    ciura_sequence.reverse()

    # shellsort from http://sortvis.org/algorithms/shellsort.html
    for h in ciura_sequence:
        for j in range(h, len(lst)):
            i = j - h
            r = lst[j]
            flag = 0
            while i > -1:
                if r < lst[i]:
                    flag = 1
                    lst[i+h], lst[i] = lst[i], lst[i+h]
                    i -= h
                else:
                    break
            lst[i+h] = r

    return lst

# read from stdin, sort and print
input_list = [line.strip() for line in sys.stdin]
for line in shellsort(input_list):
    print(line)

assert(input_list==sorted(input_list))

```

## Benchmark

Prepare a test input. This is taken from Dennis answer but with fewer words - Python 2 is sooo slow...

```
$ head -c 100000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input

```

### Python 2

```
$ time python2 underhanded2.py < input > /dev/null

real    1m55.267s
user    1m55.020s
sys     0m0.284s

```

### Python 3

```
$ time python3 underhanded2.py < input > /dev/null

real    0m0.426s
user    0m0.420s
sys     0m0.006s

```

# Where is the underhanded code?

I assume some readers may want to hunt down the trickster themselves, so I hide the answer with a spoiler tag.

> The trick is the integer division in the calculation of the `max_sequence_element`. In Python 2 `1/2` evaluates to zero and hence the expression is always zero. However, the behavior of the operator changed to floating point division in Python 3. As this variable controls the length of the gap sequence, which is a critical parameter of Shellsort, Python 2 ends up using a sequence which contains only the number one while Python 3 uses the correct sequence. This results in a quadratic run time for Python 2.

Bonus 1:

> You can fix the code by simply adding a dot after the `1` or the `2` in the calculation.

Bonus 2:

> At least on my machine Python 2 is a bit faster than Python 3 when running the fixed code...
> 17 votes

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


title: Worst Abuse of CSS?

text:
# Question
Title: Worst Abuse of CSS?
What is some of the coolest/best/worse abuses of CSS?

For example, these shapes, or using multiple box-shadows to make pixel art.

ending on 16/04/14.

# Answer
> 13 votes
Some dude created a tool to convert any image to pure CSS. This goes well beyond the original intent of CSS.

Here is an example (The famous Mona Lisa): http://codepen.io/jaysalvat/pen/HaqBf

And here is the tool : https://github.com/jaysalvat/image2css

# Answer
> 13 votes
## Changing images on the fly

I won't necessarily call it abuse, but you can use CSS to replace an `IMG` with a given `SRC` to show a completely different image.

```
@media print
{
    IMG
    {
        padding: 150px 200px 0px 0px;
        background: url('lady.jpg');
        background-size:auto;
        width:0px; height: 0px;
    }
}

```

See: https://stackoverflow.com/questions/2182716/how-can-we-specify-src-attribute-of-img-tag-in-css

Can be lots of fun combined with `@media` selectors to display completely different images when printing a webpage. (Same trick can be done in `PDF` btw. Nice to see the face of the guy that is printing a document and all serious looking charts are replaced by beautiful ladies :))

# Answer
> 1 votes
# Resizable elements:

You can add `resize:both` to allow an element to be resized by the user.
On some browsers, this is only supported on `<textarea>`'s.

# Real-time CSS preview:

This is not an actual css thing, but you can add the `contenteditable` property, add the property `style="display:block;z-index:99;width:500px;height:500px;resizable:both;"` and you can edit your CSS.

# Styled CSS Checkboxes/radiobuttons:

Using the following piece of markup as example:

```
<input type="checkbox" id="check_all" name="check_all" value="1">
<label for="check_all">Check all</label>

```

You can use `display:none` on the `<input>` and, using CSS3 selectors, you can set a 'sprite' background to show the different states of the checkbox/radiobutton.

The order of the elements is important, and matching the `for=""` property with the `id=""` in the input is even more important!

You can see some examples here: http://www.csscheckbox.com/

# Browser specific selectors:

We all have tried to use some sort of javascript mix with css classes and media-queries...

Well, here are a **few** browser specific selectors:

```
doesnotexist:-o-prefocus, #selector {}/*opera only*/
:root {}/*target all css3 browsers*/
:-moz-any(*){}/*mozilla and mozilla based only*/
:-webkit-any(*){}/*webkit only*/

```

For IE, you have tons of selectors. No need for more.

# Answer
> 0 votes
I guess it depends what you mean by abuse but this would drive your users batty:

# Jitters

```
*:hover{
  zoom:99%;
}

```

(as you mouse around the page everything jitters on you)

# Experts-Exchange/Pay-To-View Effect

```
*{
  color:transparent;
  text-shadow:0 0 5px rgba(0,0,0,0.5);
}

```

(makes all the text blurry)

# "Animated GIF's" using CSS sprite sheets

http://jsfiddle.net/simurai/CGmCe/light/

(Java's "The Dude" waving his hand)

---
Tags: popularity-contest, css
---


# Question
Title: Write a function that returns something different every time it is called
All these functional languages that return the same value every time a function is called give me a headache.

Your task is to write a function that returns something different every time it is called.

Here are the rules:

* Your function must continue to return something different every time it is run
* It must return a different value on your computer than it does on my computer
* Your function must be guaranteed to be different (no random numbers)
* +20 if your code gets time from the system or an online clock

# Answer
> 3 votes
# Perl (7 bytes)

```
sub{$$}

```

Well, until processes IDs run out, this should return something else each time it's being called.

Alternatively, if you think this is not fine, because it will return the same value for the same instance of program, there is an alternate version which only works in newer versions of Perl which automatically increases process ID every time it's being called. It's 9 bytes long, however.

```
sub{$$++}

```

# Answer
> 8 votes
## T-SQL, 13

```
PRINT NEWID()

```

Relatively uninspiring challenge, but it's rare that you can show off an instance of true brevity in SQL.

# Answer
> 4 votes
## Python, 28

```
def f(x=[f]):x+=[1];return x

```

Since python has mutable default arguments x will be different every time you call f. The starting element gives you a memory address, which changes each time you define the function. Example output:

```
>>> def f(x=[]): x+=[1]; return x
...
>>> f()
[<function f at 0x1047527d0>, 1]
>>> f()
[<function f at 0x1047527d0>, 1, 1]
>>> f()
[<function f at 0x1047527d0>, 1, 1, 1]

```

# Answer
> 4 votes
## Perl, 67 (but growing slowly) char

```
open X,"+<$0";seek X,66,0;print$y=<DATA>,%ENV;print X++$y
__END__
0

```

Output the environment of the current machine, plus a hard coded number that is updated in the source code each time you run the script.

# Answer
> 2 votes
**DOS - 27 chars**

```
echo "X" >> random.txt
dir

```

Not only will your byte size be different, even if you put it in an empty directory your volume serial number won't match mine.

# Answer
> 2 votes
# Haskell - 95

```
import Data.Time.Clock.POSIX
import System.IO.Unsafe
f _=fromEnum$unsafePerformIO getPOSIXTime

```

Example:

```
> f 0
-7269056719496922816
> f 0
-7269056004375922816
> f 0
-7269055316663922816

```

# Answer
> 2 votes
# C \[46 bytes\]

```
#include<stdio.h>
main(int*x){printf("%x",&x);}

```

Theoretically this may return the same address but practically the probability is rather low.

# Answer
> 1 votes
# Bash, 18, obvious

```
head /dev/urandom

```

# Answer
> 1 votes
## Python, 56

```
import uuid
import time
print uuid.getnode(),time.time()

```

# Answer
> 1 votes
# J, 11 bytes - True function

In J, printing the date is merely: `6!:0 ''` but the question asks for a *function* (not absolutely sure other solutions follow this requirement), which gives the idea of the following 11-characters function: `(6!:0@])&''` which outputs each time something different *whatever its argument is* (note that function with no-argument should be accepted, but answers with *statements* for printing the time shouldn't).

# Answer
> 1 votes
# C++, 38 chars

```
int *r(){int*s;int n=0;s=&n;return s;}

```

Run `int main(){std::cout<<r();}` with the above, and it is guaranteed to return a different address every time.

# Answer
> 0 votes
# bash+curl - 24 chars +20

```
curl -s time.nist.gov:13

```

# Answer
> 0 votes
## Python 52

A different version of what @Hovercouch suggested:

```
def f(x=[f]):x+=[__import__("time").time()];return x

>>> f()
[<function f at 0x049F1A30>, 1394652231.0]
>>> f()
[<function f at 0x049F1A30>, 1394652231.0, 1394652232.746]
>>> f()
[<function f at 0x049F1A30>, 1394652231.0, 1394652232.746, 1394652423.971]
>>> f()
[<function f at 0x049F1A30>, 1394652231.0, 1394652232.746, 1394652423.971, 1394652428.137]

```

Although the odds of getting different output on all computers is not zero!

---
Tags: code-golf, function
---


# Question
Title: Write a function that returns past tense of given verb
## Challenge

> Write a function which takes an argument which is a verb, and returns the past tense of the verb. (Assume that the verb is regular)

## Past tense

Note: consider y as neither consonant nor vowel.

Normally, just adding `ed` after the end of verb makes the past tense of the verb.

Ex: `jump``jumped`, `ask``asked`

However, there are other rules.

* If the last character of the given verb is `e`, just add `d`.

Ex: `love``loved`, `move``moved`
* If the verb is ended with a consonant + `y`, then change `y` to `i`, and add `ed`.

Ex: `study``studied`, `cry``cried`
* However, if the verb is ended with a vowel + `y`, then just add `ed`.

Ex: `play``played`, `stay``stayed`
* If a verb is ended with a vowel and a consonant, then write the consonant one more time, and add `ed`.

Ex: `stop``stopped`, `plan``planned`
* However, if a verb is ended with multiple vowels + a consonant or single vowel + multiple consonants, then just add `ed`.

Ex: `look``looked`, `jump``jumped`

There are more rules but let's care above rules only. For example, according to above rule, `visit``visitted`.

## Winner

Since this is code golf, the shortest code that correctly returns past tenses wins.

## Example (JS, 127)

`function f(x){return x.replace(/([^aeiouy])y$/,'$1i').replace(/([^aeiouy][aeiou])([^aeiouy])$/,'$1$2$2').replace(/e$/,'')+'ed'}`

# Answer
> 7 votes
**sed, 76 characters**

Does a sed script count as a function for this problem?

```
s/\([^aeiou]\)y$/\1i/
s/\([^aeiou][aeiou]\)\([^aeiouy]\)$/\1\2\2/
s/e\?$/ed/

```

# Answer
> 5 votes
## Mathematica 43 chars

```
f=WordData[#,"InflectedForms","List"][[1]]&

```

Usage:

```
f /@ {"call", "try", "use", "wash", "play", "stop", "look"}

{"called", "tried", "used", "washed", "played", "stopped", "looked"}

```

Also:

```
f /@ {"buy", "run", "swim"}

{"bought", "ran", "swam"}

```

# Answer
> 3 votes
## Groovy - 111 characters

```
v={it==~'[aeiou]'};p={s->r=s[0..-2];a=s[-1];b=v s[-2];(a=='e'?r:a=='y'?!b?r+'i':s:v(s[-3])|!b|v(a)?s:s+a)+'ed'}

assert ['jump', 'ask', 'love', 'move', 'study', 'cry', 'play', 'stay', 'stop', 'plan', 'look'].collect { p(it) } == ['jumped', 'asked', 'loved', 'moved', 'studied', 'cried', 'played', 'stayed', 'stopped', 'planned', 'looked']

```

# Answer
> 2 votes
Perl 5 (82 characters):

```
sub f{$_=pop;$C='[^aeiouy]';s/($C)y$/$1i/;s/($C[aeiou])($C)$/$1$2$2/;s/e?$/ed/;$_}

```

I am sure it can be improved.

# Answer
> 2 votes
# C - 120 119 characters

In typical C style, the function f updates a string buffer in place, assuming that the caller has reserved enough space for up to three extra characters. The second argument should be given as 0. The declaration of the global state variable `l` is included in the total character count.

```
#include <stdio.h>
#include <string.h>

l;void f(b,i)char*b;{*b?f(b+1,i/2+4*!strchr("aeiouy",l=*b)):(i-5?*--b=l=='y'&i/2?'i':l:(*b=l),strcpy(b+=l!='e',"ed"));}

int main()
{
  char b[10000];
  while (gets(b)) {
    f(b,0);
    puts(b);
  }
  return 0;
}

```

Explanation: The function iterates over the characters recursively. The second argument `i` encodes which of the previous three characters were consonants in its bottom three bits. At the end of the string, if `i==5` then the last three characters were a consonant, a vowel and a consonant, and thus the last character must be duplicated. Similarly, if bit 1 of `i` indicates that the second-to-last character was a consonant and the last character is 'y', then the 'y' is replaced by 'i'.

# Answer
> 1 votes
### Scala 199 273 chars

```
def v(c:Char)="aeiouy" contains c
def p(o:String)={val s=o.reverse
if(s(0)=='e')o+"d"else
if(!v(s(1))&& s(0)=='y')o.replaceAll("y$","ied")else
if(!v(s(0))&& v(s(1))&& !v(s(2)))o+s(0)+"ed"else
o+"ed"}

```

Invocation:

```
val li = List ("move", "cry", "plan", "play", "look")
li map p

```

My first approach was much longer, by moving the if-else-cascade to a list=\> to a function:

```
type S=String
def f(l:List[(Boolean,S)]):S=if(l(0)._1)l(0)._2 else f(l.tail)
def v(c:Char)="aeiouy" contains c
def c(o:S)={val s=o.reverse
f(List((s(0)=='e',o+"d"),(!v(s(1))&& s(0)=='y',o.replaceAll("y$","ied")),(!v(s(0))&& v(s(1))&& !v(s(2)),o+s(0)+"ed"),(true,o+"ed")))}

```

Maybe the approach is interesting. Degolfed and explained:

```
// just for shortening
type S=String
/* take a list of Booleans and Strings, and return early
   if a Boolean is true. This approach would work,
   if there where much more conditions, I guess.
*/
def doFirst (list: List[(Boolean, S)]): S =
  if (list(0)._1) list(0)._2 else doFirst (list.tail)
// vocal - is it a vocal
def v(c:Char)="aeiouy" contains c
// here is the key function
def toPast(o:S)={
  // reversing the String allows easy access to the last elements,
  // without considering how long the string is.
  val s=o.reverse
  doFirst (List (
    (s(0)=='e', o+"d"),
    (!v(s(1)) && s(0)=='y', o.replaceAll("y$","ied")),
    (!v(s(0)) && v(s(1)) && !v(s(2)), o+s(0)+"ed"),
    (true, o+"ed")
  ))}

```

# Answer
> 0 votes
# Ruby, 101 characters

Probably can be smaller.

```
def f x;x.sub(/([^aeiouy])y$/,'\1i').sub(/([^aeiouy][aeiou])([^aeiouy])$/,'\1\2\2').sub(/e$/,'')+'ed';end

```

Usage:

```
f("try")  #=> "tried"
f"call"   #=> "called"

```

# Answer
> 0 votes
## Poop - 72 characters

```
f[s]s^6pow>4<<last&8*(/"ed""id""eid"/|out|flush)+rep'y'1-2-3"aeiou"ord#s

```

# Answer
> 0 votes
## Python - 147

```
def f(v):T,x,m='aeiou',"ed",v[-1];return[[[v+x,v+m+x][v[-2]in T and m and v[-3]not in T],[v+x,v[:-1]+"ied"][v[-2]not in T]][m=='y'],v+"d"][m=='e']

```

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


# Question
Title: Calculate Fibonacci series from nth term to mth term
Your goal is to calculate the sum of Fibonacci series from **n** th term to **m** th term (including both terms).

* No use of `/ * %` or mathematically what they are in your language of choice.
* No use of special **functions** or **code language** specialized in doing so !
* You have to produce the series yourself and not by any special function or code language.

## OUTPUT

```
#1

0 5
series : 1 1 2 3 5 8
sum    : 20

#2

2 5
series : 2 3 5 8
sum    : 18

```

Best of luck **:\]**

# Answer
# Julia

```
fib(n)=n<2?1:fib(n-1)+fib(n-2)
sumfib(n,m)=sum([fib(i) for i=n:m])

```

Output examples:

```
julia> sumfib(0,5)  # 1  1  2  3  5  8
20

julia> sumfib(2,4)  # 2  3  5
10

julia> sumfib(2,5)  # 2  3  5  8
18

```

**EDIT:** Changed to fit question's fibonacci convention.
> 1 votes

# Answer
# J (35 characters)

A solution in J *with Fibonacci sequence starting at index 0 and value 0 according to most current conventions*. The slash `/` has absolutely nothing to do with mathematical operation in J.

```
(;+/)@:(+/@(!|.)@i."0)@([+i.@>:@-~)

```

For instance:

```
3 (;+/)@:(+/@(!|.)@i."0)@([+i.@>:@-~) 6
┌───────┬──┐
│2 3 5 8│18│
└───────┴──┘

```
> 1 votes

# Answer
# Delphi

```
uses
  System.SysUtils,idglobal;
var
  i,n,m,ires:integer;
  a:TArray<integer>;
  res:string;
begin
  ires:=0;
  readln(n,m);
  SetLength(a,m+1);
  for i:=0to m+1 do
    a[i]:=iif(i<2,1,a[i-1]+a[i-2]);
  for i:=n to m do
  begin
    write(Format('%d ',[a[i]]));
    inc(ires,a[i]);
  end;
  WriteLn('|'+IntToStr(ires));
end.

```

Input: `0 5`
Output: `1 1 2 3 5 8 | 20`

Input: `1 20`
Output: `1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 | 28655`
> 1 votes

# Answer
# C

```
int fsum (int start, int end) {
    int a[2]={1,0};
    int p=1,b=1,d=0;
    for (;p<=end+2;b=!b) {
        a[b]+=a[!b];
        d=p++==start+1?a[b]:d;
    }
    return a[!b]-d;
}

```

To make it more interesting, I've decided to see if I could a) use a static amount of memory, and b) produce the requested sum without actually adding up the \[n..m\] elements. So my code doesn't print out all the elements (since it wasn't required), but produces the correct result nevertheless.
> 1 votes

---
Tags: code-challenge
---


title: Line-wrap into proper columns

text:
# Question
Title: Line-wrap into proper columns
Input will be one or more space separated characters followed by a long string on STDIN or as an argument when called from the shell.

```
a C
WAtcIaElCpVqDRavOUejlgumcRCpfIWlaRFZpIoPYsWjsBSdlYfitfAPHpemiLpjaHheUGpFVQoZCnSCFgvpVzcoibdffoPRoJJwLIjVicPCdcvITXaQDjtMgrxQMZCkZNFmNqwGQYaSyPpdLOkAVHGVoVBiIksZCQHEaIxcRGwpIAmlChuhGEDajeJVXoCwFFuIvhEoqMuwrCDmZPcQxeaqJjynGWVjSaCCxWfupDbbEEFufDyealmbLxKfwlWCsSXwpPtuayxNVCodeEjeCIeHBYioeTogujuUFlWydOwInWGbsvlSwlwgfQaAmNTWPjsgqSCGzsJYfqGklpeLujFyrZJmNymUzpXLTkZcyPgPakAXTTfKlnnTCkjxxSZltwnLMOUCxlHOtLIUTqcbejXqyrwQgMaPUKcHBDZwMrCgwfVZUzxbdODBbBqEbpFLUOcPpVmsgLnfMXRWaddGnK

```
* Your task is to line-wrap the string at a suitable length so that there is at least one column completely filled by each input character. All lines should be wrapped to the same length (except possibly the last one if it's shorter.)

In this case, the solution could be wrapping at 50 characters giving the output

```
WAtcIaElCpVqDRavOUejlgumcRCpfIWlaRFZpIoPYsWjsBSdlY
fitfAPHpemiLpjaHheUGpFVQoZCnSCFgvpVzcoibdffoPRoJJw
LIjVicPCdcvITXaQDjtMgrxQMZCkZNFmNqwGQYaSyPpdLOkAVH
GVoVBiIksZCQHEaIxcRGwpIAmlChuhGEDajeJVXoCwFFuIvhEo
qMuwrCDmZPcQxeaqJjynGWVjSaCCxWfupDbbEEFufDyealmbLx
KfwlWCsSXwpPtuayxNVCodeEjeCIeHBYioeTogujuUFlWydOwI
nWGbsvlSwlwgfQaAmNTWPjsgqSCGzsJYfqGklpeLujFyrZJmNy
mUzpXLTkZcyPgPakAXTTfKlnnTCkjxxSZltwnLMOUCxlHOtLIU
TqcbejXqyrwQgMaPUKcHBDZwMrCgwfVZUzxbdODBbBqEbpFLUO
cPpVmsgLnfMXRWaddGnK

```

The fifteenth (`a`) and twenty-seventh (`C`) all form a single column of the given input characters. The last line may or may not be complete.

* There can be more than one solutions. Any one of them can be considered valid.
* Returning the string as-is is **NOT** allowed. (For those claiming that it forms one-row columns). The columns of the input characters must have at least two rows. You may assume that the input string is longer than 10 characters.
* If there is no possible solution, your program must indicate this in some way(return status, printing "no solution", etc.) which you must mention.
* Input will only include \[a-zA-Z\]

This is

---

Here's the actual program(python) that I use to generate these strings.

```
import random

a = 10
b = 50

s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in xrange(a):
    c = ''
    for j in xrange(b):
        c += (random.choice(s))
    print c

```

I then rectangle-edit to get columns full of input characters and strip newlines, deleting random number of characters from the end of the last line.

# Answer
### GolfScript, 73 characters

```
n%(' '-:C;~:T,,1>{T/zip{.,1>*.&.,1=*}%''*C&C=},.{0=T/n*}{'no solution'}if

```

Breaks at the first position which is possible. The input must be given on STDIN in the format specified in the question.

*Example (online):*

```
X Y
abcdeXfYghijklmnXoYpqrstuvwXxYyzXYZ

abcdeXfYghi
jklmnXoYpqr
stuvwXxYyzX
YZ

```

*Annotated code:*

```
n%               # Split the input at newlines
(' '-:C;         # Extract the first line, remove all spaces
                 # and assign the resulting string to variable C
~:T              # Take the second line and assign this string
                 # to variable T
,,1>             # Makes an array [1 2 3 ... L-1] where L is the
                 # length of T
{                # A filter block {...}, selects all possible
                 # line wrap positions from this array
  T/             #   Test the current length by splitting T (input)
                 #   in pieces
  zip            #   Transpose the result (i.e. we now have a array
                 #   of strings representing the columns)
  {              #   For each column
    .,1>*        #     Is the length greater than one, then keep the column
                 #     else transforms it to the empty string (string * 0)
    .&           #     "and"s the string with itself, i.e. the result
                 #     is a string of the distinct characters in the column
    .,1=*        #     If the length is 1 (i.e. only one character) keep
                 #     the column, otherwise reduce it to the empty string
  }%
  ''*            #   Combine the resulting characters into a string again
  C&C=           #   Check if this string contails all characters from C
},
.{               # If the filter returns at least one possible wrap position
  0=             #   Take the first one
  T/n*           #   Split the string and join again with newlines
}{               # Else
  'no solution'  #   Return 'no solution'
}if              # Endif

```
> 2 votes

# Answer
## APL (65)

```
⍞{1∊r←∧⌿↑∨/¨¨∧⌿¨¨↓⍵∘.=z←⍺∘{z⍵⍴⍺↑⍨⍵×z←⌈⍵÷⍨⊃⍴⍺}¨⍳¯1+⍴⍺:⊃r/z⋄0}⍞~' '

```

Example: (smaller one for legibility)

```
      ⍞{1∊r←∧⌿↑∨/¨¨∧⌿¨¨↓⍵∘.=z←⍺∘{z⍵⍴⍺↑⍨⍵×z←⌈⍵÷⍨⊃⍴⍺}¨⍳¯1+⍴⍺:⊃r/z⋄0}⍞~' '
r a b
abracadabra!
abracad
abra!

```

Explanation:

* `⍞{`...`}⍞~' '`: Read two lines. Remove the spaces from the first line and pass it to the function as its right argument, pass the second line unaltered as the left argument.
    + `⍺∘{`...`}¨⍳¯1+⍴⍺`: For each number `1..length ⍺-1`, split  into that many columns:
    + `z←⌈⍵÷⍨⊃⍴⍺`: calculate how many columns we'll need and store in `z`.
    + `⍺↑⍨⍵×z`: extend  with spaces to the length `⍵×z` (fill the last line up with spaces if necessary)
    + `z⍵⍴`: reshape the result into `z` lines and  columns
    + `z←`: store the array of matrices in `z`
    + `⍵∘.=z`: for each character in  (the input characters), see which elements in `z` match it
    + `∧⌿¨¨↓`: take the logical *and* of each column of each matrix for each input character
    + `∨/¨¨`: take the logical *or* of each element in the result (giving for each character and each matrix whether that character was matched in that matrix)
    + `r←∧⌿↑`: for each matrix, see whether or not *all* input characters were matched. Store a bitmask over the matrices in `r`.
    + `1∊r`...`:`: If the bitmask contains a `1`, there was a result, so:
    + `⊃r/z`: Filter `z` by `r` and take the first element (displaying the result with the smallest amount of columns.)
    + `⋄0`: otherwise, return '0'.
> 0 votes

# Answer
# Python (~~211~~ 203)

This is my first codegolf so I expect many possible improvements. I have designed two version which use different systems to print out the solution.

The input is done via 2 input()s so you would have to put quotes before and after the strings.

## Version 1 (~~211~~ 203)

```
c=input().split();i=input();l=range(len(i)//2)
for k in c:l=[w for w in l if any(all(k==y for y in i[x::w])for x in range(w))]
print'\n'.join(len(l)and __import__('textwrap').wrap(i,l[0])or'No solution')

```

**Explanation**:

```
chars = input().split()
inp = input()
wrapAfter = range(len(inp)//2) # min 2 (full) lines
for char in chars:
    wrapAfter = [wrapped for wrapped in wrapAfter if any( # filter the possiblities left
        all(char == cAt for cAt in inp[columnNbr::wrapped]) # wrap the line and check that
                                                            # cAt is char
            for columnNbr in range(wrapped))] # for all columns

# print a joined version of all strings that are returned
import textwrap
wrapped = wrapAfter[0]
print('\n'.join(textwrap.wrap(inp, wrapped) if len(wrapAfter) # if there are wrappingvalues left
                                                              # we wrap the string
                else 'No solution')) # else we print 'No solution'

```

## Version 2 (~~245~~ ~~236~~ ~~219~~ 208)

```
r=range;c=input().split();i=input();z=len(i);l=r(z//2)
for w in l:
 if set(s[0] for s in(i[x::w]for x in r(w))if len(set(s))==1)>=set(c):print'\n'.join(i[x:x+w]for x in r(0,z,w));break
else:print'No solution'

```

**Explanation**:

```
chars = input().split()
inp = input()
length = len(inp)
wrapAfter = range(length//2)
# we go through every possible wrapping
for wrap in wrapAfter:
    # if the set of all  character for that a colum exists that is purely made up of
    # this char is a superset of chars then we won
    if set(s[0] for s in
            # makes a generator that generates all columns
            (inp[x::wrap]for x in range(wrap))
            # if all characters in the column are equal
            if len(set(s))==1) >= set(chars):
        print('\n'.join(inp[x:x+wrap]for x in range(0,length,wrap))) # textwrap is
                                                                   # slower as we
                                                                   # replace range
        break
# if the loop wasn't broken nothing was found
else:
    print('No solution')

```
> 0 votes

# Answer
# Ruby, 161

Why not use one clever regular expressions instead of "brute-forcing" and checking ;)

Online version

```
d,s=STDIN.read.split("\n")
l = s.size
puts s.scan(/.{,#{d.split.map{|c|(0..l-2).map{|n|n if /^.{,#{n}}(#{c+?.*n})*.{,#{n-1}}$/=~s}}.reduce(&:&).compact.min+1}}/)

```
> 0 votes

---
Tags: code-golf
---