title: Sort-a-number. Sorta

text:
# Question
Title: Sort-a-number. Sorta
Inspired by the ill-fated sorting-a-numbers-digits-without-using-an-array, but I thought it made a better code golf than SO question.

Given a positive integer, sort the digits in that integer.

Lowest score wins!

1. Start with 0 points.
2. Add one point per character.
3. Add 20 points for each array you use.
4. Add 10 points for each multi-character string in your code. (Except the initial input as long as it is converted to an integer without any other operations done on it.)
5. Add 32 points if the maximum number of digits your program can handle is limited by your program (as opposed to the machine).
6. Subtract 10 points if your code can change the direction of the sort given another argument (whatever you want, but for example 0 for descending sort and 1 for ascending.)

*Every language is different, but the idea is to avoid any kind of iterable-of-digits hackery.*

### Example:

**Input**: 52146729

**Output**: 97654221 or 12245679

### Notes:

1. Use any built-in sorting capabilities your programming language provides, but if that sort feature involves strings or arrays, take the penalty!
2. You can write the solution as a function that takes an integer directly, or as a program that takes an argument from argv, a file or stream and converts it to an integer. As long as you convert it to an integer immediately and discard the original char\* input without doing any further operations on it, no penalty applies.
3. The penalties apply not only to string literals in your program text, but any part of your program feature that arguably inputs or outputs a string or iterable. For example, JavaScript `String.prototype.split` has at least one string as input (`this`) and an Array as output, so +30 for using that.
4. I've tried to make these rules guide the principle of the algorithm design, not the initial/final I/O (hence note #2). I don't think the penalty ought to apply to `int(input())` even if `input`'s signature says it returns a string, as long as that expression is the *initial entry point* of the program. Likewise, if the final output of the program is `print(x)` and `x` must be a string, the penalty doesn't apply to the last-ditch string casting operation. All that said, I explicitly never said that this had to be a *program* or where the I/O had to come from or go. A function that takes an `int` and returns an `int` would serve, and wouldn't suffer from these ambiguities.

# Answer
# GolfScript, ~~11~~ 4

### (4 + 10 (string) - 10 (reverse option))

Input on STDIN.

```
~`$%

```

Input format is this:

```
(1 or -1) (the number)

```

`1` to sort normally, `-1` to reverse. 4 characters - 10 for reverse option = score of -6.

The input is technically a string, so I'm not sure whether that counts for +10. I'm interpreting the rule as "a string declared in your program" (since it says "in your code").

---

Old answer (score of 11):

```
$

```
> 13 votes

# Answer
# Haskell 106

```
t=10;d=divMod;s z|z<w z=s$w z|t>0=z
w x|x<t=x|y>z=(q*t+y)*t+z|t>0=y+t*(w v)where{(v,y)=d x t;(q,z)=d v t}

```

example:

```
ghci> s 502010406072952146729521467295214672952146729
999997777766666555554444422222222221111100000

```

An answer that doesn't dodge the question.

An explanation was requested, here it is ungolfed. It's a very inefficient bubble sort.

```
-- t=10 - alias for 10. d=divMod - alias for divMod.
-- The alias for '10' turns out to be unnecessary; inlining it
-- and using '1>0' for True has the same character count. It's
-- a relic of earlier versions of the code.

-- 's': if no digits need swapped, return the number,
-- otherwise return 's' applied to the number with
-- that pair of digits swapped.
sort z=
  let temp=sort_pair z
  -- because we are sorting in descending order,
  -- sorting a pair of digits always increases the number.
  -- testing > costs one less char than ==.
  if z<temp then
    -- golfed version uses guards instead of if/else to save space.
    -- t>0 is '10 > 0', which is 'True', in fewer chars.
    sort temp
  else
    z
-- 'w': recursively swap one pair of out of order digits, or
-- return the original number if no pairs needed swapped.
sort_pair x=
  -- haskell does the assignments below lazily, they aren't
  -- calculated unless I use them. 'divMod' lets me do this
  -- with fewer chars.
  let y = x `mod` 10 -- last digit
      v = x `div` 10 -- all but last digit
      z = v `mod` 10 -- second last digit
      q = v `div` 10 -- all but last 2 digits
  in
  if x < 10 then
    x
  else if y > z then
    -- last 2 digits are out of order. swap them & return
    -- This is rearranged using Horner's method to save space
    -- http://en.wikipedia.org/wiki/Horner%27s_method
    -- ... although it turns out not to save anything, it's a relic.
    (q * 10 + y)*10 + z
  else
    -- last digit is ok, so try sort_pair on remaining digits
    let temp = sort_pair v in
    -- put last digit back on the end and return
    -- having the bracketed expression last here
    -- let me remove a space before 'where'
    y+(10*temp)

```

Shorter answers exist in Haskell, equivalent to some of the others posted, eg:

```
import Data.List;s=read.sort.show::Integer->Integer

```

... scores 52+20=72, or this, scoring 45+20=65:

```
import Data.List;main=interact(reverse.sort)

```

... but the spirit of the question - no arrays, strings, or characters - is more interesting.
> 14 votes

# Answer
# C + x86 assembly, 636

I know this isn't gonna win but it felt so much unnatural and twisted that I had to share it. No arrays or strings (as long as you don't count the input arguments). The number of digits its limited by the 32 bit range.

So here's a little explanation on what I did:

I thought I'd do this without using any arrays or strings, and then recursion came into mind, but of course, with recursion I wouldn't be able to swap values from other recursive calls... and then was when I realized that there was a way. Linking my C program with an assembly function I could jump up in the stack and return a pointer to the base pointer of the desired call, that's what "recursionStackAt" function does. Of course recursionStackAt is a very ugly function, its result doesn't only depend on the input or program's state but on the caller itself. Note that that's what made me change the indexes from 0 based to 1 based.

Without further ado, here's the code:

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

int numberToSort;
int totalLength = 0;
int decreasing;

int* recursionStackAt(int pos); //Here's the magic

void swapAtStack(int pos1, int pos2) {
    int a = *(recursionStackAt(pos1)+3);
    *(recursionStackAt(pos1)+3) = *(recursionStackAt(pos2)+3);
    *(recursionStackAt(pos2)+3) = a;
}

int getAt(i) {
    return *(recursionStackAt(i)+3);
}

void printNumber(int len) {
    int i = 0;
    for(i = 1; i <= len; ++i) {
        printf("%d",*(recursionStackAt(i)+3));
    }
    printf("\n");
}

void computeNextDigit(int remainingNumber, int nextDigit) {

    if(remainingNumber == 0) {
        //Bubble sort cause I was lazy and it's quite compact
        ++totalLength;

        int i, j;

        for(i = 1; i <= totalLength; ++i)
            for(j = 1; j <= totalLength-1; ++j) {
                if(decreasing) {
                    if(getAt(j) > getAt(j+1))
                        swapAtStack(j,j+1);
                }
                else {
                    if(getAt(j) < getAt(j+1))
                        swapAtStack(j,j+1);
                }
            }

        printNumber(totalLength);
    }
    else {
        ++totalLength;
        computeNextDigit(remainingNumber/10, remainingNumber%10);
    }
}

int main(int argc, char* argv[]) {
    if(argc == 3) {
        numberToSort = atoi(argv[1]);
        decreasing = atoi(argv[2]);
    }
    else exit(1);
    computeNextDigit(numberToSort/10, numberToSort%10);
}

```

And of course the x86 (AT&T sintax, btw) assembly code for the recursionStackAt function:

```
.text
    .align 4
    .globl  recursionStackAt
    .type   recursionStackAt, @function
recursionStackAt:
        pushl %ebp
        movl %esp,%ebp
        pushl %esi
        movl $0, %esi #i = 0
        movl (%ebp), %eax #pointer
while:
        cmp %esi, 8(%ebp)
        je endwhile
        movl (%eax),%eax
        incl %esi
        jmp while
endwhile:
        popl %esi
        movl %ebp, %esp
        popl %ebp
        ret

```

Some examples on the output: (1 means increasing and 0 decreasing)

```
$ ./sortasort 6543210 1
0123456
$ ./sortasort 32507345 1
02334557
$ ./sortasort 32507345 0
75543320

```

Here's the obfuscated version (which is unreadable but works fine):

http://pastebin.com/XkYt9DLy (C code) http://pastebin.com/h0S0dfeU (x86 code)

So if LibreOffice isn't lying my obfuscated code consists of 646 characters (without spaces, should I count them?) and with all the other conditions met I get a -10 for the incresing/decreasing choice.

Oh, and to compile this you should do (On Unix-like systems)

```
gcc -c [-m32] recursionStackAt.s
gcc -o sortasort [-m32] sortasort.c recursionStackAt.o

```

Note that the -m32 flag is only if you're on a 64 bit machine. You also need the 32 bit libraries to compile it.
> 13 votes

# Answer
## Bash (echo) (0+7+0+0+32-10) = 29

Sorta:

```
echo $*

```

Usage:

```
sorta 5
5

```

Use "-e" to sort in reverse:

```
sorta -e 3
3

```
* produces the correct result for positive integers 1-9, plus 0
* avoids any kind of iterable-of-digits hackery.
* 7 characters (+7)
* no arrays
* no multi-character strings
* maximum number of digits it can handle: 1 (+32)
* can optionally reverse the sort (-10)

EDIT: changed "cat" to "echo" so it would actually work. EDIT 2: Added " $\*" and put it into "sorta" script
> 9 votes

# Answer
# Python3

My script features:

**No arrays**

**No strings**

**Complexity is O(n):** I used countingsort (modified by me to not use arrays, but **prime numbers** to count occourences)

**No limitations in size**

**Characters: 260 234**

```
n=int(input())
def C(n,k):
    return (n//(10**(k-1)))%10
P=lambda l:((((29-6*l%2,19-2*l%2)[l<9],13-2*l%2)[l<7],2*l-1)[l<5],2)[l==1]

p=1
while n>=1:
    c =C(n,1)
    p*=P(c+1)
    n=n//10
f=1
k=r=0
while p>2:
    if(p%P(f)==0):
        r+=(f-1)*10**k
        p=p//P(f)
        k+=1
    else: f+=1
print(r)

```
> 8 votes

# Answer
# Bash+coreutils, 14 (24 chars - 10 for reverse)

I think this might be bending the rules a bit, but here goes, its Friday...

I assume use of standard libraries is allowed. My interpretation of standard library for `bash` is `coreutils`:

```
fold -1|sort $1|tr -d\\n

```
* No arrays - streams are used instead
* No quotes == no multi-character strings
* No limit to input/output length
* optional arg "-r" reverses the output.

Input from stdin. In use:

```
$ declare -i i=52146729
$ ./ksort.sh <<< $i
12245679 $
$ ./ksort.sh -r <<< $i
97654221 $
$

```
> 7 votes

# Answer
# c function (little-endian arch), 131 108 chars

No sorting challenge is complete without a sleepsort answer. This one will take up to 10 seconds to return, but it does work, and I think it is fully within spec. This function takes a single int param and returns an int with the decimal digits sorted:

```
c=0,d;
k(i){
    for(;i;i/=10,fork()?c++:(sleep(d),exit(d)))
        d=i%10;
    for(;c--;i=i*10+(d>>8&255))
        wait(&d);
    return i;
}

```

*newlines and indentation added for readability*

Call as follows:

```
int main (int argc, char **argv) {
    int i = 52146729;

    printf("%d\n", k(i));
    return (0);
}

```
> 7 votes

# Answer
# C - 64 characters, 64 points

```
main(int a,char**b){b++;qsort(*b,strlen(*b),1,strcmp);puts(*b);}

```

You might wonder how I get this to work without any headers. Simple, compile with:

```
gcc -include stdio.h stdlib.h string.h test.c -o test --std=gnu11 -Wall -g -O3

```

**Un-golfed:**

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

main(int a, char **b)
{
    b++;
    qsort(*b, strlen(*b), sizeof(char), strcmp);  // sizeof(char) is guaranteed to be 1 by standards
    puts(*b);
}

```

---

I also decided to include sorting of characters, just because I could.

Test runs:

```
$ ./test 132815
112358
$ ./test 423791
123479
$ ./test 1234767189728975213132471243985123957120837412
0111111112222222233333344445556777777788889999
$ ./test 4789359uihjasvb8ygohq9poi3n4jiouy58g
3344557888999abgghhiiijjnooopqsuuvyy

```
> 7 votes

# Answer
# TeX/LaTeX (332)

If the actual code is put in a package `s`, then the main LaTeX file looks nice and easy. The number is just given as math. If the number is negative, the sorting order is reversed. The code of package `s` can also used with plain TeX, example further below.

```
\documentclass{book}
\usepackage{s}
\begin{document}
  $52146729$

  $-52146729$ % reversed ordering

  $277981468517523153773703292073191466142223027369188752287219582183$
\end{document}

```

**The package `s`** (one line, line ends are not needed):

```
\TeXXeTstate1\everymath{\aftergroup\B\def~#1{\gdef#1{}\aftergroup#1}
~\a~\b~\c~\d~\e~\f~\g~\h~\i~\j\aftergroup\E\xdef\B{}\xdef\E{}}
\def~#1#2{\mathcode`#1"8000\lccode`~`#1\lowercase{\def~{\xdef#2{#2#1}}}}
~0\a~1\b~2\c~3\d~4\e~5\f~6\g~7\h~8\i~9\j\mathcode`-"8000\lccode`~`-
\lowercase{\def~{\xdef\B{\beginR}\xdef\E{\endR}}}

```

**Result:**

>

**Score:** hopeless

* Using plain TeX with `etex` or `pdftex`, the file can be reduced to:

`*<contents of s.sty>*\rm\shipout\hbox{$*<number>*$}\bye`

Bytes: **318** bytes (`s.sty`) + **24** bytes for the rest without the number
* Arrays are not used: **0**
* I do not see multi-character strings: **0**
* The number is not limited by the algorithm. The largest TeX number is 231 \- 1 = 2147483647. The example uses a 66-digit number, way larger: **0**
* If a minus is given, then the sorting order is reverted to descending: **−10**

0 + 318 + 24 + 0 + 0 − 10 = **332**

**Algorithm:**

The digits are made active characters in math mode. Each digit remembers and collects each usages in a macro. After the math mode the macros are output with the digits in ascending order.

The direction change is done by right-to-left text, an e-TeX feature.

**Degolfed version** of the code in `s.sty`

```
\TeXXeTstate = 1 % enable mixed direction typesetting
\everymath{%
  % \B and \E surround the number, they will be redefined
  % with right-to-left primitives to output the reverted number
  \xdef\B{}
  \xdef\E{}
  \aftergroup\B
  % the active character ~ is defined as help macro;
  % the argument is the collector macro
  \def~#1{%
    \gdef#1{}% initially the macro is empty
    \aftergroup#1%
  }%
  % the ten macros \a to \j form the result number
  ~\a~\b~\c~\d~\e~\f~\g~\h~\i~\j
  \aftergroup\E
}
% the active ~ is used as helper macro;
% first argument is the digit, the second argument is the collector macro
\def~#1#2{%
  \mathcode `#1  = "8000 % make digit active in math mode
  \lccode `~ = `#1 % trick for defining the active digit
  \lowercase{%
    \def~{%
      \xdef#2{#2#1}% the digit adds itself to its collector macro
    }%
  }%
}
~0\a~1\b~2\c~3\d~4\e~5\f~6\g~7\h~8\i~9\j
% Defining the minus character as switch for descending digits:
\mathcode `- = "8000 % minus sign active in math mode
\lccode `~ = `- % trick for defining the active minus
\lowercase{%
  % the minus sign redefines the wrapper macros \B and \E that
  % surround the result number. These macros now uses
  % primitives for right-to-left typesetting.
  \def~{%
    \xdef\B{\beginR}%
    \xdef\E{\endR}%
  }%
}

```

**Reproducing**

There are some online LaTeX compilers, a list can be found here. I tried the first item on the list, LaTeX servlet on sciencesoft.at. It can be used without signing and it can also create permanent URLs: source and result as image.
> 6 votes

# Answer
# Java : 262 points

*Yeah, yeah I know, it's hopeless, but still..*

```
class G{Object m(StringBuffer s,int o){for(int i=1;i<s.length();i++){int j=i-1,t=s.charAt(i),u=s.charAt(j);boolean c=o==0?t>u:t<u;for(;j>-1&c;){s.setCharAt(j+1,s.charAt(j));c=--j>-1;c=c?(o==0?t>s.charAt(j):t<s.charAt(j)):c;}s.setCharAt(++j,(char)t);}return s;}}

```

**Analysis (marking):**

1. Starting with 0. (score = 0)
2. 262 characters total. (score = 0 + 262 = 262)
3. +10 - for using `StringBuffer` (I used it because it's *shorter* than `StringBuilder`) (score = 262 + 10 = 272)
4. -10 - for making the output flexible. I've considered **0 = descending**, **1 = ascending**, so back to 262!

**Usage:**

When you try and compile the `G.java` file in command prompt, it generates a hell lot of problems (errors). So, the solution?

> Compile the `G.java` class in an IDE like `NetBeans` or `Eclipse` or even `BlueJ`. It should compile without any trouble (ignore any warnings).

Then, this class should be called by a `main()` method from any other class (or even that class itself). I'm putting it another class, so I'm not adding it to my character count. Compile the other class in a similar manner (without using `cmd`). Now the `main()` method in the *other* class should be something like:

```
public static void main(String[]a){
    System.out.println(new G().m(new StringBuffer(a[0]),1));
    //for descending, put '0' instead of '1'
}

```

Excluding unnecessary spaces, comments and line breaks, it's another 93 characters. I'm not adding it to my character because this is just for demonstration through console.

**Output:**

*ZERO* i.e. `0` is considered. Supposing the external class is `Helper.java`, and it has been successfully compiled, a few examples through console are:

> `INPUT :` C:...\>java Helper 008321
> `OUTPUT:`001238
>
> `INPUT :` C:...\>java Helper 79359105
> `OUTPUT:`01355799

When changed to `0` i.e. descending...

> `INPUT :` C:...\>java Helper 008321
> `OUTPUT:`832100
>
> `INPUT :` C:...\>java Helper 79359105
> `OUTPUT:`99755310

**NOTES:**

1. I didn't explicitly declare any array in `G.java`. That is the *core* class.
2. I'm using *insertion sort* to sort the number digit-wise.
3. The number can be of of the **maximum length** \- `Integer.MAX_VALUE` because that is the maximum size any array can hold (in Java).
4. This answer can be shortened (I believe) so please help me (improve my first answer).
5. *Darn those great Gods who accidentally created such a lengthy yet great language like Java (and also who came up with code conventions)!*
> 6 votes

# Answer
# C - 65

```
r,t,i;s(n){for(;++i;)for(t=n;t;t/=10)r=t%10-i?r:10*r+i;return r;}

```

The astute observer will note that this sorting algorithm runs in O(n) time on the number of digits in `n`.

The pragmatic observer will note that this sorting algorithm runs in time proportional to the range of signed integers on the platform, that it mutates global state which must be re-initialized between runs, and that many other sacrifices have been made in favor of brevity.

The ungolfed version is not exactly equivalent, but it better conveys the actual algorithm involved.

```
int s(int n)
{
    int r = 0;
    int t;
    int i;
    for(i = 0; i < 10; i++)
    {
        for(t = n; t != 0; t /= 10)
        {
            if(t % 10 == i)
            {
                r = 10 * r + i;
            }
        }
    }
    return r;
}

```

Here's a test harness for the function:

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

int main(int argc, char *argv[])
{
    if(argc != 2) return 1;
    printf("%d\n", s(atoi(argv[1])));
    return 0;
}

```
> 5 votes

# Answer
## Haskell - 96

*96 characters, no arrays, no strings, no integer limit, can't reverse*

```
d=(`divMod`10)
a&(0,0)=a
a&(y,z)=(z%d a)&d y
a%(y,z)|z>a=10*(a%d y)+z|1<3=100*y+10*z+a
s=(0&).d

```

Examples:

```
λ: s 52146729
12245679
λ: s 502010406072952146729521467295214672952146729
1111122222222224444455555666667777799999
λ: s 100
1

```

This one is insertion sort, performed directly on the integers themselves. This is similar to the other Haskell entry which is bubble sort, though I swear I was working on it before I saw that one.

Brief guide:

* `d` divides a number into units and tens, i.e.: `d 135` is the pair `(13,5)`
* `a%x` is sorted insertion of digit `a` into the number `x`
* `a&x` sorts `x` by inserting the units digit into `a` and recursing on the result and remainder
* `s x` sorts x by kicking off the `&` recursion on 0 and `x`

The trick is that the second argument of `%` and `&` isn't `x` directly, but `x` divMod'd using `d`
> 4 votes

# Answer
## J, 10 characters (+ 1 string) score = 20

```
s=./:~&.":

```

Usage:

```
   s 52146729
12245679

```

Works for all 32 bit numbers.

**Explanation:**

`/:~` sort up `&.` under `":` format. My previous version used an array as well, but they're costly so now I need to just use a string and sort the characters alphabetically. `":` converts the number that is input into a string and `/:~` sorts the digits into ascending order. Because the sort is done 'under' format, when the sort is finished, the string is converted back into a number. Adding the ability to reverse would probably cost more than it saves, so I didn't bother.

The argument could be made that since J, like APL and K, is an array-based language, the single input is an array of 1 item, but I chose not to take such a harsh view when calculating my score.

The 32-bit limit is imposed by J, rather than my program. Any higher and J switches the numbers to scientific notation. It's not clear from the question whether the 32 point penalty applies in this case, but even if both of the previous penalties apply (I don't think they should) the score goes up to 72 and still comfortably beats the vast majority of the other answers.
> 3 votes

# Answer
# Python 2.7: 174

```
import math
i=input()
d={n:0for n in xrange(10)}
for n in(i/10**c%10for c in xrange(1+math.log10(i))):d[n]+=1
print"".join(str(n)for n in xrange(10)for c in xrange(d[n]))

```
* No arrays (iterators and a dictionary are used instead)
* No multi-character strings (except output)
* No artificial maximum number of digits
* No reversing

It works by creating a dictionary mapping all 10 digits to 0. Then it iterates over the length of the number (`log10(i)`), extracting each digit (`(i / (10 ** c)) % 10`), and incrementing the counter for that digit in the dictionary. Finally it creates a string made by iterating over all 10 digits, and for each digit yielding one instance of the digit as a string.

I could change the last line to `print"".join(d[n]*str(n)for n in xrange(10))` which would be 16 characters less, but would use multi-character strings.
> 3 votes

# Answer
# **Python3.3 61 points**

```
print(''.join(sorted(input())))

```

This program takes in the input as a string, which counts as a string because it is not changed to an integer immediately. **+10**

The string is sorted into an array **+10**

This array is joined together into a string **+10**

**Note:** The `''` used to join the array's contents is not a multi character string, so +10 is not added to the score.

The program consists of 31 characters. **+31**

**31+10+10+10 = 61 points**
> 3 votes

# Answer
## C# - 179

```
using System.Linq;class S{void Main(string[] a){Console.Write(string.Concat(string.Concat(a).Replace("-","").OrderBy(o=>a[0].Contains('-')?-o:o)));}}

```

**Un-golfed**

```
using System.Linq;

class S
{
    void Main(string[] a)
    {
        Console.Write(string.Concat(
            string.Concat(a)
                .Replace("-", "")
                .OrderBy(o => a[0].Contains('-') ? -o : o )));
    }
}

```

**Test**

Normal:

```
app.exe 52313698

```

Reversed:

```
app.exe 52313698-

```

**Points:** (I hope I understood the point system properly - feel free to correct)

* Chars: 149
* Strings: 10+10
* Arrays: +20
* Order: -10
* Total: 149+10+20-10 = **179**

---

## C# with LINQPAD \- 123

```
void Main(string[] a){Console.Write(string.Concat(string.Concat(a).Replace("-","").OrderBy(o=>a[0].Contains('-')?-o:o)));}

```

**Test**

Normal:

```
lprun.exe sorta.linq 52313698

```

Reversed:

```
lprun.exe sorta.linq 52313698-

```

**Points:**

* Chars: 122
* Strings: 10+10
* Arrays: +20
* Order: -10
* Total: 122+10+20-10 = **152**
> 3 votes

# Answer
# C (up to C90) ~~or C++,~~ ~~78~~ 66 points

The function so sort an integer is called `s`.

```
s(i){t=10,a=i?s(i/t):0,b=i%t,c=a%t;return c>b?t*s(a-c+b)+c:t*a+b;}

```

Scoring:

* 66 Characters (+66)
* 0 arrays (+0)
* 0 strings (+0)
* Range defined by machine (size of `int`) (+0)
* Only one sorting direction (-0)

Old version (78 points, works also with C++ and more modern C versions)

```
int s(int i){int t=10,a=i?s(i/t):0,b=i%t,c=a%t;return c>b?t*s(a-c+b)+c:t*a+b;}

```
> 3 votes

# Answer
# Java 1469

A string and array free solution in Java. 1437 characters + 32 because it only takes up to Long.MAX\_VALUE as input. By using Double I could go to over 300 digits instead but that would be too tedious to implement. Anything bigger than that would need BigInteger and AFAIK that uses arrays internally. If you use less than 19 digits for the input the output will have leading zeroes. Negative input will give all zeroes and anything not a number will cause an exception.

For the sort I used the easiest I could think of so it's pretty inefficient. (should be O(n\*n))

```
input:  9212458743185751943
output: 1112233444555778899

```

I know this doesn't really compare to the solutions in other languages but I feel this at least is the shortest I can get it in Java. (if anyone knows how to get this even shorter feel free to edit/comment)

```
class D
{
    long c,d,e,f,g,h,k,l,m,n,o,p,q,r,s,t,u,v,w;
    long x;

    public D(Long a)
    {
        x = a;
        c = g();
        d = g();
        e = g();
        f = g();
        g = g();
        h = g();
        k = g();
        l = g();
        m = g();
        n = g();
        o = g();
        p = g();
        q = g();
        r = g();
        s = g();
        t = g();
        u = g();
        v = g();
        w = g();
        int i=0;
        while(i++ < 19) s();
        System.out.printf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",c,d,e,f,g,h,k,l,m,n,o,p,q,r,s,t,u,v,w);
    }

    long g()
    {
        if( x <= 0 ) return 0;
        long b = x % 10;
        x = x / 10;
        return b;
    }

    void s()
    {
        if(c > d) {c += d; d = c - d; c -= d;}
        if(d > e) {d += e; e = d - e; d -= e;}
        if(e > f) {e += f; f = e - f; e -= f;}
        if(f > g) {f += g; g = f - g; f -= g;}
        if(g > h) {g += h; h = g - h; g -= h;}
        if(h > k) {h += k; k = h - k; h -= k;}
        if(k > l) {k += l; l = k - l; k -= l;}
        if(l > m) {l += m; m = l - m; l -= m;}
        if(m > n) {m += n; n = m - n; m -= n;}
        if(n > o) {n += o; o = n - o; n -= o;}
        if(o > p) {o += p; p = o - p; o -= p;}
        if(p > q) {p += q; q = p - q; p -= q;}
        if(q > r) {q += r; r = q - r; q -= r;}
        if(r > s) {r += s; s = r - s; r -= s;}
        if(s > t) {s += t; t = s - t; s -= t;}
        if(t > u) {t += u; u = t - u; t -= u;}
        if(u > v) {u += v; v = u - v; u -= v;}
        if(v > w) {v += w; w = v - w; v -= w;}
    }

    public static void main(String[] y)
    {
        D d = new D(Long.parseLong(y[0]));
    }
}

```
> 3 votes

# Answer
## Python lambda function (reversible), 69

```
lambda n,d:''.join(sorted(n,reverse=d))

```
* 39 chars **(+39)**
* Two multi-char strings: `n`(input) and `''.join(...)` **(+20)**
* One list: `sorted(...)` **(+20)**
* Can reverse direction depending on the parameter `d` **(-10)**

---

## Python lambda function (non-reversible), 67

```
lambda n:''.join(sorted(n))

```

---

EDIT: Input should be a string. I am considering the penalty of using that string directly.
> 2 votes

# Answer
I don't see anything about sorting functions in the question, so... (I'm gonna remove the answer if it bends or breaks the rules, let me know)

### JavaScript ~~56~~ 96

```
function s(){alert(+prompt().split('').sort().join(''))}

```

### JavaScript ~~69~~ 109 (reversable)

```
function s(r){x=prompt().split('').sort();x=r?x.reverse():x;alert(+x.join(''))}

```

Can be golfed down a bit using EcmaScript 6 *arrow functions*:

### ES6 ~~50~~ 90

```
s=()=>{alert(+prompt().split('').sort().join(''))}

```

### ES6 ~~63~~ 103 (reversable) (73-10)

```
s=(r)=>{x=prompt().split('').sort();x=r?x.reverse():x;alert(+x.join(''))}

```
> 2 votes

# Answer
# AWK - 101

The 'x' file:

```
BEGIN{n=ARGV[1]
r=ARGV[2]
for(d=r;d<10;d++)for(p=1;p<=length(n);p++){D=r?d:9-d
if(D==substr(n,p,1))printf D}print}

```

The run:

```
$ awk -f x 52146729
97654221
$ awk -f x 52146729 0
97654221
$ awk -f x 52146729 1
12245679
$ awk -f x 1234567890123456789012345678901234567890
9999888877776666555544443333222211110000
$ awk -f x 1234567890123456789012345678901234567890 1
111122223333444455556666777788889999

```

The only array used is ARGV and this is no help in sorting, it only is access to the commandline parameters and these values are in non-array variables where actually needed for calculations. I think this won't count against this solution. The following calculation does not take the ARGV-array into account:

111 (chars) - 10 (can do reverse)
> 2 votes

# Answer
# SED 67 Chars (score either 67 or 107)

```
s/$/;0123456789/;:a;s/\(.\)\(.\)\(.*;.*\2.*\1\)/\2\1\3/;ta;s/;.*//;

```

This uses a bubble sort for brevity. Score would be 107 if each regular expression pattern and replacement count as a string (i.e. 67 + (10 * 4))

Number of digits handled limited by memory (and probably patience)
> 2 votes

# Answer
# Common Lisp - 126

```
(defun s(n p)(labels((a(n)(if(= 0 n)()(cons(mod n 10)(a (floor n 10)))))(b(a)(if(null a)0(+(car a)(* 10(b(cdr a)))))))(b(sort(a n) p))))

```

The ungolfified (stylistically as well as lexically, but functionally identical) version:

```
(defun sorta (n p)
  (labels ((digits (n)
             (unless (zerop n)
               (multiple-value-bind (quotient remainder)
                   (truncate n 10)
                 (cons remainder (digits quotient)))))
           (digit-cat (digits)
             (if (null digits)
                 0
               (+ (car digits)
                  (* 10 (digit-cat (cdr digits)))))))
    (digit-cat (sort (digits n) p))))

```

The digits of a negative number are treated as having negative value, and digits are sorted least-significant-first (i.e., little-endian). Examples:

```
CL-USER> (sorta 1234 #'<)
=> 4321
CL-USER> (sorta 12344321 #'<)
=> 44332211
CL-USER> (sorta 12344321 #'>)
=> 11223344
CL-USER> (sorta -12344321 #'>)
=> -44332211
CL-USER> (sorta 0 #'>)
=> 0
CL-USER> (sorta 8675309 #'<)
=> 9876530

```

There are 136 characters in the golfed version, including whitespace. It uses no strings and no arrays, and handles arbitrary-precision integers, including negative integers. The sorting is parameterized on a binary predicate which defines a total ordering on the integers in `[-9, 9]`, including but not limited to `<` and `>`:

```
CL-USER> (sorta 3546219870 (lambda (a b)
                             (cond ((and (evenp a)
                                         (oddp b))
                                    t)
                                   ((and (evenp b)
                                         (oddp a))
                                    nil)
                                   (t
                                    (< a b)))))
=> 9753186420

```

This gives a score of 126.
> 2 votes

# Answer
# JavaScript 416 / 185

**No Arrays, no Strings, no arbitrary length constraint**...

But sorting up/down would have used up more than 10 characters ^^ But I found the idea of counting digits and printing them interesting - maybe someone can use this idea in GolfScript and win the prize ;-)

```
var x=window.prompt(),y=0,z=0,a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0;
do
{
    z=x%10;
    x=(x-z)/10;
    if(!z)a++;
    if(z==1)b++;
    if(z==2)c++;
    if(z==3)d++;
    if(z==4)e++;
    if(z==5)f++;
    if(z==6)g++;
    if(z==7)h++;
    if(z==8)i++;
    if(z==9)j++;
}while(x);

while(a--)y=y*10;
while(b--)y=y*10+1;
while(c--)y=y*10+2;
while(d--)y=y*10+3;
while(e--)y=y*10+4;
while(f--)y=y*10+5;
while(g--)y=y*10+6;
while(h--)y=y*10+7;
while(i--)y=y*10+8;
while(j--)y=y*10+9;

alert(y);

```

The same code shorter, using eval: (but that would likely be considered using strings...)

```
var i = window.prompt(),o=0,i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;
do
{
    eval("i"+i%10+"++");
    i = ~~(i/10);
} while (i > 0)

for(var j=0;j<10;j++) while (eval("i"+j+"--")>0) o = o*10+j;

alert(o);

```
> 2 votes

# Answer
# C (222)

```
static int a[10],r=1;o(n,c){while(n--)printf("%""i",c);}p(){int n;for(n=r<0?9:0;n>=0&&n<10;n+=r)o(a[n],n);}main(int _,char**v){char*s=v[1];if(*s=='-'){r=-1;++s;}do++a[*s-'0'];while(*++s);p();}

```

Points:

* 192 (192 Chars)
* 40 (2 Arrays: argv(v) and a)
* 0 (no multi char strings)
* 0 (it's not limited to n digits)
* -10 (sorts reverse if the number (argv\[1\]) is negative)

= 222 Points

Flags needed to get rid of the 1000 compiler warnings: `gcc -Wno-implicit-function-declaration -Wno-return-type -Wno-implicit-int -Wno-char-subscripts -o count2 counta2.c`

"Better" readable:

```
static int a[10],r=1;
o(n,c){while(n--)printf("%""i",c);}
p(){int n;for(n=r<0?9:0;n>=0&&n<10;n+=r)o(a[n],n);}
main(int _,char**v){char*s=v[1];if(*s=='-'){r=-1;++s;}do++a[*s-'0'];while(*++s);p();}

```

Somewhat ungolfed:

```
static int a[10],r=1;
o(n,c){
    while(n--) printf("%""i",c);
}
p(){
    int n;
    for(n=r<0?9:0;n>=0&&n<10;n+=r) o(a[n],n);
}
main(int _,char**v){
    char*s=v[1];
    if(*s=='-'){
        r=-1;
        ++s;
    }
    do ++a[*s-'0']; while(*++s);
    p();
}

```
> 1 votes

# Answer
Is there a reason I dont see this solution already?

**Ruby**

```
pry(main)> 52146729.to_s.split("").sort.join.to_i
=> 12245679

```

Am not sure how to score this. The split would generate an array, but beyond that not sure.. 38 chars + 2x20 for arrays? Or should it include all arrays that sort might create internally?
> 1 votes

# Answer
## VBScript - 76 (96?)

```
x = "7892347684578892348025023389054859034234"

for i=0 to 9:n=n&string(len(x)-len(replace(x,i,"")),""&i):next:x=n

' x -> 00002222233333344444455556777888888889999

```

66 character + 10 for the use of string `n`
(Don't know if the use of the `replace` function and `string` function that returns n amount of character x is counted as an extra string).

It counts the amount of a certain digit by comparing the length of the original string with the same string with the certain digit replaced. Then it attaches that amount of digits to n.
> 1 votes

# Answer
# Python 3 sleepsort (168)

With absolutely no list or loop, only generators.

```
import math, threading
n=input()
if any(threading.Timer(x,lambda x:print(x,end='',flush=1),(x,)).start()for x in(n//10**i%10for i in range(math.log10(n)//1+1))):pass

```

could probably be improved.
> 1 votes

# Answer
# Racket 97

97 points (87 +20 for two strings, -10 for sorting, no arrays)

```
(define(s n <)(string->number(list->string(sort(string->list(number->string n))<))))

```

This uses lists of chars so you need to give it a char comparison function like `char<?` or `char>?`. I feel this also passes as ungolfed since it's not much to do than add spaces and increase variable names. My old version is perhaps more honorable :)

Old version without strings:

110 points (120 bytes (utf-8) - 10 for allowing for changing sort order. It uses no strings and no arrays)

```
(define(S d <)(foldl(λ(x a)(+(* a 10)x))0(sort(let L((l'())(
d d))(if(= d 0)l(L(cons(modulo d 10)l)(quotient d 10))))<)))

```

Ungolfed:

```
(define (number-digit-sort number <)
  (foldl (λ (x a) (+ (* a 10) x))
         0
         (sort (let loop ((acc '()) (number number))
                 (if (= number 0)
                     acc
                     (loop (cons (modulo number 10) acc)
                           (quotient number 10))))
               <)))

```

I tested it with the 100,000th fibonacci number:

```
(number-digit-sort (fibonacci 100000) <)
;==> 1111... basically it's the digits:
; 1 2135 times
; 2 2149 times
; 3 2096 times
; 4 2023 times
; 5 2053 times
; 6 2051 times
; 7 2034 times
; 8 2131 times
; 9 2118 times

```

And the same in opposite order:

```
(number-digit-sort (fibonacci 100000) >)
; ==> 999... and the digest is
; 9 2118 times
; 8 2131 times
; 7 2034 times
; 6 2051 times
; 5 2053 times
; 4 2023 times
; 3 2096 times
; 2 2149 times
; 1 2135 times
; 0 2109 times

```
> 1 votes

---
Tags: code-challenge, sorting
---


title: Anonymize names - sort of

text:
# Question
Title: Anonymize names - sort of
**Edit: There will be a bonus of -20 for random masking**

Hello fellow Whistleblowers and carriers of secret knowledge.

I am due to an interview by mail and I - of course - cannot say specific names in full length. But as I want to disclose it in a rather not-so-obvious-way I need your help.

I will provide these names in the form of

> "evil\_company\_that\_makes\_me\_shiver"

but surely I do not want to spell it out completely. Your task to help me and the whole world is that you provide a nice program that turns the above into

```
"ev**************************"

```

or

```
"**il************************"

```

or even

```
"****_c**********************"

```

I think you get it. But there is one flaw: I want to disclose the name in total, so I need to pass the number of occurrences and the word itself to the script and it will disclose the letters bit by bit. An example could be

```
~$ ./whistle NSA 3
> "N**"
> "**A"
> "*S*"

```

or

```
~$ ./whistle nuclear 3
> "nu*****"
> "***lea*"
> "**c***r"

```

or

```
~$ ./whistle nuclear 2
> "nuc****"
> "***lear"

```

I hope you can help me and as we know that size matters the shortest code wins. Help make this world a better place!

# Answer
> 12 votes
### GolfScript, 26 charaters

Since no specific way of disclosure was specified I decided to go for the shortest:

```
:f,\`{{\)f%.!@42if}%\;n}+%

```

You may experiment with this code online.

*Example:*

```
> "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 7
******G******N******U*****
*****F******M******T******
****E******L******S******Z
***D******K******R******Y*
**C******J******Q******X**
*B******I******P******W***
A******H******O******V****

```

*Commented code:*

```
:f           # Save the second input to variable f
,            # Makes the array [0 1 2 .... f-1]
\`{          # \´{}+% builds a code block where
             # first the input string is pushed (done
             # via the + operator and afterwards the whole
             # block is applied to above array, i.e.
             # For each line 0, 1, ...
             #   Here, the stack contains the line number (counter)
             #   and the string
  {          #   {}% -> map to each character of the string
             #     Stack contains counter and current character
    \)f%     #     Increase the counter by one and calculate modulo f
    .        #     Duplicate counter (will be used for the if below)
    !        #     and test for zero
             #     I.e. if counter==0
    @        #       Then Current character
    42       #       Else 42 (which is '*')
    if       #
  }%         #   The mapping operation masked most of the characters
  \;         #   Discard the counter
  n          #   Add newline
}+%

```

# Answer
> 7 votes
## PHP - 80 bytes

```
<?for(;($c=$argv[1][~-$i+=1])?:$k^++$j;)echo$c?$i%$k=&$argv[2]^$j?'*':$c:$i='
';

```

Sample usage:

```
$ php whistle-blower.php ABCDEFGHIJKLMNOPQRSTUVWXYZ 7
******G******N******U*****
A******H******O******V****
*B******I******P******W***
**C******J******Q******X**
***D******K******R******Y*
****E******L******S******Z
*****F******M******T******

```

# Answer
> 7 votes
# Python (~~157~~ ~~149~~ ~~139~~ 138-20=118):

```
def f(a,b):
 from random import*;c=[["*"]*len(a) for i in range(b)]
 for d in range(len(a)):choice(c)[d]=a[d]
 for e in c:print "".join(e)

```

# Cheesy python (~~55~~ 35):

You didn't tell me the required distribution ;)

```
g=lambda a,b:["*"*len(a)]*(b-1)+[a]

```

# Uniform python (~~129~~ ~~123~~ 122):

```
def h(a,b):
 c=[["*"]*len(a)for i in range(b)]
 for d in range(len(a)):c=c[1:]+c[:1];c[0][d]=a[d]
 for e in c:print"".join(e)

```

# Output:

```
a="Synthetica 'Evil' the Second"
b=7
f(a,b)
print
for i in g(a,b): print i
print
h(a,b)

```

gives

```
***t***i***'***** *********d
******************t** ******
******t*** ***********Se**n*
S**************l****e*******
*y******c***E************o**
**n*h****a**************c***
*****e*******vi*'**h********

****************************
****************************
****************************
****************************
****************************
****************************
Synthetica 'Evil' the Second

******t******v******e******d
S******i******i****** ******
*y******c******l******S*****
**n******a******'******e****
***t****** ****** ******c***
****h******'******t******o**
*****e******E******h******n*

```

# Answer
> 3 votes
# Bash, 80 bytes

```
m=${1//?/*}
for((i=1;d=i*${#1}/$2,i++<=$2;c=d)){
echo "${m:0:c}${1:c:d-c}${m:d}"
}

```

In action:

```
$ ./anon.sh stackoverflow.com 6
st***************
**ack************
*****ove*********
********rfl******
***********ow.***
**************com
$

```

# Answer
> 2 votes
## C#, 226

This can be trimmed down if you replace the random stuff with a more simple distribution (think modulus) but the randomness is what got me interested. =)

Anyway, putting everything on just one line I get 226 characters. In readable code it looks like this:

```
private void F(string n, int i)
{
    var l = n.Length;
    var r = new Random();
    var a = new string[i];

    for (var p = 0; p < l; p++)
    {
        var x = r.Next(0, i);
        for (var j = 0; j < i; j++)
        {
            a[j] += j == x ? n.Substring(p, 1) : "*";
        }
    }

    for (var j = 0; j < i; j++)
    {
        Console.WriteLine(a[j]);
    }
}

```

Sample output:

```
Anonymize.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ 7
*****F**I**********T**W***
A*****************S****X**
**CDE**H*JKL**************
*************N************
**************O*****U****Z
*B****G*****M***QR********
***************P*****V**Y*

```

# Answer
> 2 votes
# Perl, 24

```
$_ x=<>;s/(.|
)./\1*/g

```

Requires the `-p` switch, which accounts for two of the bytes. Reads from STDIN.

### How it works

* Because of the `-p` switch, Perl reads the first input lie and stores its contents in `$_`.
* The command `$_ x=<>;` duplicates the first input line the number of times the second input line (`<>`) specifies.
* The command `s/(.|\n)./\1*/g;` consumes two characters and replaces the second (which cannot be a newline) with an asterisk. It does this until it has consumed the entire contents of `$_`.

Since newlines count as the first character, this will obfuscate all even characters on the first line and all odd characters on the remaining lines.
* Because of the `-p` switch, Perl prints the contents of `$_`.

### Example input

```
codegolf
4

```

### Example output

```
c*d*g*l*
*o*e*o*f
*o*e*o*f
*o*e*o*f

```

# Answer
> 1 votes
# JavaScript - 170

```
function s(a,e){o="",b=a.length,x=b/e|0,y=b-x*e;for(c=1;c<=e;c++){r="*";o+=Array((c-1)*x+1).join(r)+a.substr(c*x-x,c==e?x+y:x)+Array(c<e?b-c*x+1:0).join(r)+"\n"}return o}

```

Quick one, breaks if you supply a name and ask for more pieces than characters, but works up to that point and down to 1. Could be golfed more I assume, so may revise or take advice, as it's a bit of a mess.

Edit: Golfed further (from 187) with removal of brackets (@Synthetica) and Math.floor replacement from @toothbrush. For loop change as suggested results in errors in the output.

# Answer
> 1 votes
# Java - 490

Yeah, not really golfed or anything. Oh well, here it is:

```
import java.util.ArrayList;public class Anonymise {public static void  main(String[] args){ArrayList[] c=new ArrayList[Integer.parseInt(args[1])];for(int i=0;i<c.length;i++)c[i]=new ArrayList();for(char a:args[0].toCharArray()){int f=new java.util.Random().nextInt(c.length);c[f].add(a);for(int i=0;i<c.length;i++)if(i!=f)c[i].add('*');}ArrayList<String> b = new ArrayList<String>();for(ArrayList a:c){String s = "";for(Object o : a)s += o;b.add(s);}for(String s : b)System.out.println(s);}}

```

In a nice, legible format:

```
import java.util.ArrayList;

public class Anonymise {

public static void main(String[] args){
    ArrayList[] c = new ArrayList[Integer.parseInt(args[1])];
    for(int i=0;i<c.length;i++)
        c[i]=new ArrayList();
    for(char a:args[0].toCharArray()){
        int f = new java.util.Random().nextInt(c.length);
        c[f].add(a);
        for(int i=0;i<c.length;i++)
            if(i!=f)c[i].add('*');
    }
    ArrayList<String> b = new ArrayList<String>();
    for(ArrayList a:c){
        String s = "";
        for(Object o : a)
            s += o;b.add(s);
    }
    for(String s : b)
        System.out.println(s);
}
}

```

Sample usage (When run from the compiled class)

```
> java Anonymise OnlinePerson 3
*n****P***o*
O*li***e****
****ne**rs*n

```

# Answer
> 1 votes
# Python 3 - 187 (-20 = 167)

Took me a while to write, could probably be golfed more.

```
import sys,random as a
b=sys.argv
x=[""for i in' '*int(b[2])]
for i in range(len(b[1])):n=a.randrange(len(x));x=[c+["*",b[1][len(c)]][j==n]for j,c in enumerate(x)]
for i in x:print(i)

```

Sample usage:

```
$ python tx.py super_anonymous_user 3
s******n**y*ou****e*
**p***a**n*m**s_us*r
*u*er_**o***********

```

## As a function - 161 (-20 = 141)

```
from random import*
def f(c,n):
    x=[""for i in' '*n]
    for i in range(len(c)):n=randrange(len(x));x=[v+["*",c[len(v)]][j==n]for j,v in enumerate(x)]
    return x

```

# Answer
> 1 votes
# C# 184

```
namespace System.Linq{class P{static void Main(string[] a){int n=int.Parse(a[1]);for(int i=0;i<n;i++)Console.WriteLine(new String(a[0].Select((c,x)=>(i+x)%n==0?c:'*').ToArray()));}}}

```

Non-golfed

```
namespace System.Linq
{
    class P
    {
        static void Main(string[] a)
        {
            int n = int.Parse(a[1]);
            for (int i = 0; i < n; i++)
                Console.WriteLine(new String(a[0].Select((c, x) => (i + x) % n == 0 ? c : '*').ToArray()));
        }
    }
}

```

Sample:

```
> Anonymize.exe "qwertyuio" 4
q***t***o
***r***i*
**e***u**
*w***y***

```

# Answer
> 1 votes
# Perl 6 (77 bytes)

This may count as cheating, but it solves the problem (it doesn't print the string entirely).

```
($_,$!)=@*ARGS;.say for .chop~"*","*"x.chars-1~.substr(*-1),"*"x.chars xx$!-2

```

And the sample output.

```
> ./script.p6 ultimately_awesome 6
ultimately_awesom*
*****************e
******************
******************
******************
******************

```

# Answer
> 1 votes
# R, (120-20)=100 bytes (2 different solutions of same length)

Beside the conciseness, R for sure features the best random number generator! :) Here the 1st solution of length 120:

```
function(s,n){
  c=strsplit(s,"")[[1]]
  e=sample(n,nchar(s),T)
  sapply(1:n,function(i)paste(ifelse(e==i,c,"*"),collapse=""))
}

```

If the function is named as *f*, the output looks like:

```
> f("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 7)
"******GH*****************Z"
"ABCD*********N************"
"***********L**O***********"
"*********J**M**P*RS*U**X**"
"**********K***********W***"
"*****F**I*******Q*********"
"****E**************T*V**Y*"

```

And here the 2nd solution, again with random masking, and again 120 bytes long:

```
function(s,n){
  x=matrix("*",n,(m=nchar(s)))
  x[cbind(sample(n,m,T),1:m)]=strsplit(s,"")[[1]]
  apply(x,1,paste,collapse="")
}

```

# Answer
> 0 votes
# Scala (1) 177 bytes

After the solution in R I also found one in Scala, here it is:

```
def f(s:String, n:Int)={
  def c=s map (z=>z.toString)
  def r=(1 to s.length) map (v=>v%n+1)
  (for (i<-1 to n) yield s zip r map (t=>if(t._2==i) t._1 else "*") mkString "") map println
}

```

# Scala (2) 129 bytes

After a short research I found the method *zipWithIndex*. Wonderful :)

```
def f(s:String, n:Int)={
  (for (i<-0 until n) yield s.zipWithIndex.map (t=>if(t._2 % n==i) t._1 else "*") mkString "") map println
}

```

Here the solution:

```
f("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4)
***D***H***L***P***T***X**
A***E***I***M***Q***U***Y*
*B***F***J***N***R***V***Z
**C***G***K***O***S***W***

```

# Answer
> 0 votes
# Javascript - 166

```
function s(b,a){o="";k=Array(a).join("*");t=k+b+k;for(i=a;0<i;i--)o+=t.replace(RegExp(".{"+(a-1)+"}(.)","g"),k+"$1").substr(i-1,b.length)+"\n",t=t.substr(1);return o}

```

Using regex.

Sample

```
> s("four",5)
f***
*o**
**u*
***r
****

> s("evil_company_that_makes_me_shiver",3)
e**l**o**a**_**a**m**e**m**s**v**
*v**_**m**n**t**t**a**s**e**h**e*
**i**c**p**y**h**_**k**_**_**i**r

```

# Answer
> 0 votes
# k \[50-20=30 chars\]

```
{.{@[y#"*";z;:;x z]}[x;c]'=_d*y%#d:<<(-d)?!d:c:#x}

```

### Explanation

1. Input: x=String which needs to be masked, y=number of lines
2. Count the number of characters c in string and create y buckets.
3. Place c mod y characters in each bucket.
4. For each bucket, print "\*" for the remaining numbers not in that bucket.

### Example

```
{.{@[y#"*";z;:;x z]}[x;c]'=_d*y%#d:<<(-d)?!d:c:#x}["abcdefghijklmnopqrstuvwxyz";4]

```

### Output

```
"ab*d*f***j**********u*w***"
"**c*e*gh**k*****q*s*******"
"********i***mn*****t*v**y*"
"***********l**op*r*****x*z"

```

# Answer
> 0 votes
## JavaScript - 139-20=119

```
function e(s,c){r=[];for(i=c;i--;)r[i]='';for(i=0;i<s.length*c;i++)x=i%c,n=(x<1?Math.random()*c|0:n),r[x]+=(n!=x?'*':s[(i/c)|0]);return r}

```

Usage and sample output:

```
console.log(e("evil_company_that_makes_me_shiver", 3));

["**i*_**mp*****h**_ma**********v**",
 "*****co**a***t*a******s*me_*hi*e*",
 "ev*l******ny_***t***ke*_***s****r"]

```

As the masking is random, the output may also look like this:

```
console.log(e("evil_company_that_makes_me_shiver", 2));

["evil_company_that_makes_me_shiver",
 "*********************************"]

```

# Answer
> 0 votes
# F# - ~~81~~ ~~80~~ 75

This is fairly similar to others that have been offered:

```
let a s n=[for i in 0..n-1->String.mapi(fun j c->[c;'*'].[min((j+i)%n)1])s]

```

Sample:

```
a "evil_company_that_makes_me_shiver" 7

e******m******h******e******h****
******o******t******k******s*****
*****c******_******a******_******
****_******y******m******e******r
***l******n******_******m******e*
**i******a******t******_******v**
*v******p******a******s******i***

```

As a full, stand-alone application it comes out to ~~160~~ ~~155~~ 156 characters:

```
[<EntryPoint>]let m (a:string array)=
 let n=System.Int32.Parse a.[1]
 for i in 0..n-1 do printfn"%s"(String.mapi(fun j c->[c;'*'].[min((j+i)%n)1])a.[0])
 0

```

# Answer
> 0 votes
# Julia 56-20=36 (works often)

```
f(s,n)=[join([rand()<1.9/n?c:"*" for c in s]) for r=1:n]

julia> f("evilcompany!!!",4)
4-element Array{Union(UTF8String,ASCIIString),1}:
 "e**l**mp*ny*!*"
 "***lco********"
 "e*il**m*a*y!*!"
 "evil**m*an***!"

```

Trying to go for a shorter random solution I decided to sacrifice guaranteed functioning for a shorter solution. It's really not a very good solution.

---
Tags: code-golf
---


# Question
Title: Calculate your stack exchange reputation
**Background:**

I often find that, when browsing a Stackexchange site, I begin to wonder how people get the amount of reputation that they have. I know I can always count on codegolf SE to solve my problems, so here it is:

Create a program that will accept a positive integer which represents a person's reputation. We will ignore bounties, and say that these are the only ways to gain/lose rep on SE (full table here):

* Every account starts out with 1 rep and cannot go below that
* Your question is upvoted = +5
* Your answer is upvoted = +10
* Your question is downvoted = -2
* Your answer is downvoted = -2
* You downvote an answer = -1
* Your answer is accepted = +15
* You accept an answer = +2

Your program must figure out how many of those actions occurred on that user's account to get to the rep they have. It must figure out the shortest number of actions to get to this level of rep. Examples:

> Input: 11 Output: 1 answer upvote
>
> Input: 93 Output: 6 answer accepts, 1 answer accepted

In these examples when I say 'question upvote', it means that person's queston got upvoted. When I say 'answer downvoted', it means they downvoted someone else's answer.

**Rules:**

, so the shortest code that can do this wins.

# Answer
# Golfscript, ~~162~~ 144 bytes

```
{{}if}:?;~.)15/:^15*-:~3>1~8>' answer ':A' question 'if'upvote'++?^^A'accept'+:C+^1>{'s'+}??~5%:,4<,1>&1C'ed'++?,2%!1A'downvote'++,4<{'d'+}??]n*

```

# How it works

The general idea is exactly the same as in my Bash answer.

```
{{}if}:?;         # Create an `if' statement with an empty `else' block.
                  #
~.)15/:^          # Interpret the input string, subtract 1 from its only element (the
                  # reputation score), divide by 15 and save the result in `^'. This gives
                  # the number of accepted answers.
                  #
15*-:~            # Multiply the number of accepted answer by 15 and subtract the product
                  # from the reputation score. Save the result in `~'.
                  #
3>                # If the result is greater than 3:
                  #
  1               # Push 1 on the stack.
                  #
  ~8>             # If the result is greater than 8:
                  #
    ' answer ':A  # Push `answer' on the stack. Either way, save the string in `A'.
                  #
    ' question '  # Otherwise, push `question' on the stack.
                  #
  if              #
                  #
  'upvote'++      # Push `upvote' on the stack and concatenate the three strings.
                  #
?                 #
                  #
^                 # If the number of accepted answers is positive:
                  #
  ^A'accept'+:C+  # Push the number, concatenated with the string ` answer accept', on the
                  # stack. Either way, the string in `C'.
                  #
  ^1>             # If the number of accepted answers is greater than 1:
                  #
    {'s'+}        # Cocatenate the previous string with `s', for proper pluralization.
                  #
  ?               #
                  #
?                 #
                  #
~5%:,             # Calculate the reputation score modulus 5. Save the result in `,'.
                  #
4<,1>&            # If the result is less than 4 and greater than 1:
                  #
  1C'ed'++        # Push the string `1 answer accepted' on the stack.
                  #
?                 #
                  #
,2%!              # If the result is odd:
                  #
  1A'downvote'++  # Push the string `1 answer downvote' on the stack.
                  #
  ,4<             # If the result is less than 4:
                  #
    {'d'+}        # Concatente the previous string with `d'.
                  #
  ?               #
                  #
?                 #
                  #
]n*               # Join the array formed by all strings on the stack, separating the
                  # strings by newlines. This is the output.

```
> 3 votes

# Answer
# Bash, ~~247~~ ~~202~~ 192 bytes

```
n=$1 bash <(sed 's/E/)echo /;s/C/ Aaccept/;s/A/answer /
s/.*)/((&)\&\&/'<<<'a=(n+1)/15,a-1)s=s;q=question
aE$aC$s
r=n%5,r-4)d=d&&
r>1E1Ced
1-r%2E1 Adownvote$d
n-=15*a,n>8)q=A
n>3E1 $q upvote')

```

### How it works

After the *sed* command does it job, the following bash script gets executed:

```
((a=(n+1)/15,a-1))&&s=s;q=question
((a))&&echo $a answer accept$s
((r=n%5,r-4))&&d=d&&
((r>1))&&echo 1 answer accepted
((1-r%2))&&echo 1 answer downvote$d
((n-=15*a,n>8))&&q=answer
((n>3))&&echo 1 $q upvote

```

To obtain the optimal solution (minimal number of events to get `n` reputation), it suffices to compute the number of accepted answers (`a`) necessary to get to a reputation below 16 (1 answer accept) and handle the residue as follows:

```
1  (no rep change)
2  answer accepted, answer downvoted
3  answer accepted
4  question upvote, answer downvote
5  question upvote, answer downvoted
6  question upvote
7  question upvote, answer accepted, answer downvoted
8  question upvote, answer accepted
9  answer upvote, answer downvote
10 answer upvote, answer downvoted
11 answer upvote
12 answer upvote, answer accepted, answer downvoted
13 answer upvote, answer accepted
14 answer accept, answer downvote
15 answer accept, answer downvoted

```
> 9 votes

# Answer
# Perl, 500 263 256 208 bytes

Script `rep.pl`:

```
$_=1+pop;sub P($){print$=,@_,$/}$;=" answer ";$:="$;downvote";($==$_/15)&&P"$;accept"."s"x($=>1);$_%=15;$==1;P"$;upvote",$_-=10if$_>9;P" question upvote",$_-=5if$_>4;P"$;accepted"if$_>2;P$:."d"if$_%2;P$:if!$_

```

## Usage

The input is expected as positive integer, given as argument to the script. The different actions are output as lines.

## Tests

```
perl rep.pl 11
1 answer upvote

perl rep.pl 93
6 answer accepts
1 answer accepted

perl rep.pl 1

perl rep.pl 4
1 question upvote
1 answer downvote

perl rep.pl 12
1 answer upvote
1 answer accepted
1 answer downvoted

perl rep.pl 19
1 answer accept
1 question upvote
1 answer downvote

perl rep.pl 34
2 answer accepts
1 question upvote
1 answer downvote

perl rep.pl 127
8 answer accepts
1 question upvote
1 answer accepted
1 answer downvoted

perl rep.pl 661266
44084 answer accepts
1 question upvote

```

## Ungolfed

```
$_ = pop() + 1; # read the reputation as argument,
                # remove the actionless start reputation
                # and add a bias of two to calculate
                # the answer accepts in one division.

# Actions
# -------
# answer accepts:      Your answer is accepted    = +15
# answer upvotes:       Your answer is upvoted     = +10
# question upvotes:     Your question is upvoted   = +5
# answers accepted:     You accept an answer       = +2
# answers downvoted:    You downvote an answer     = -1
# answer downvotes:     Your answer is downvoted   = -2
# (questions downvoted: Your question is downvoted = -2) not used

# Function P prints the number of actions in $= and
# the action type, given in the argument.
# The function is prototyped "($)" to omit the
# parentheses in the usage.
sub P ($) {
    print $=, @_, $/ # $/ is the line end "\n"
}
# abbreviations,
# special variable names to save a space if a letter follows
$; = " answer ";
$: = "$;downvote";

# Calculation and printing the result
# -----------------------------------
($= = $_ / 15) && # integer division because of the special variable $=
P "$;accept" .
  "s" x ($= > 1); # short for: ($= == 1 ? "" : "s")
$_ %= 15;
$= = 1;           # now the action count is always 1 if the action is used
P "$;upvote",         $_ -= 10 if $_ > 9;
P " question upvote", $_ -=  5 if $_ > 4;
P "$;accepted"                 if $_ > 2;
P $: . "d"                     if $_ % 2;
P $:                           if ! $_

```

## Older version

```
$_ = pop() + 1; # read the reputation as argument
                # subtract start reputation (1)
                # add bias (2)

# Actions
# -------
# $= answer accepts:      Your answer is accepted    = +15
# $b answer upvotes:      Your answer is upvoted     = +10
# $c question upvotes:    Your question is upvoted   = +5
# $d answers accepted:    You accept an answer       = +2
# $e answers downvoted:   You downvote an answer     = -1
# $f answer downvotes:    Your answer is downvoted   = -2
# -- questions downvoted: Your question is downvoted = -2

# Calculaton of answer accepts by a simple division that is
# possible because of the bias.
$= = $_ / 15; # integer division because of the special variable $=
$_ %= 15;

# The older version of the calculation can be simplified further, see below.
# Also the older version did not use the bias.
#
# function E optimizes the construct "$_ == <num>" to "E <num>"
# sub E {
#     $_ == pop
# }
#
# $d = $e = 1 if E 1;       #  1 =     +2 -1
# $d++ if E 2;              #  2 =     +2
#
# $c = $f = 1 if E 3;       #  3 =  +5 -2
# $c = $e = 1 if E 4;       #  4 =  +5 -1
# $c++ if E 5;              #  5 =  +5
# $c = $d = $e = 1 if E 6;  #  6 =  +5 +2 -1
# $c = $d = 1 if E 7;       #  7 =  +5 +2
#
# $b = $f = 1 if E 8;       #  8 = +10 -2
# $b = $e = 1 if E 9;       #  9 = +10 -1
# $b++ if E 10;             # 10 = +10
# $b = $d = $e = 1 if E 11; # 11 = +10 +2 -1
# $b = $d = 1 if E 12;      # 12 = +10 +2
#
# $=++, $f++ if E 13;       # 13 = +15 -2
# $=++, $e++ if E 14;       # 14 = +15 -1

$b++, $_ -= 10 if $_ > 9;
$c++, $_ -=  5 if $_ > 4;

# Now $_ is either 0 (-2), 1 (-1), 2 (0), 3 (1), or 4 (2).
# The number in parentheses is the remaining reputation change.

# The following four lines can be further optimized.
# $f++        if ! $_;    # "! $_" is short for "$_ == 0"
# $e++        if $_ == 1;
# $d = $e = 1 if $_ == 3;
# $d++        if $_ == 4;

# Optimized version of the previous four lines:

$f++ if ! $_;
$e++ if $_ % 2;
$d++ if $_ > 2;

# function P optimizes the printing and takes the arguments for "print";
# the first argument is the action count and the printing is suppressed,
# if this action type is not needed.
sub P {
    print @_, $/ if $_[0]
    # $/ is "\n"
}

# some abbreviations to save some bytes
$; = " answer ";
$D = "$;downvote";

# output the actions

P $=, "$;accept", ($= == 1 ? "" : "s");
P $b, "$;upvote";
P $c, " question upvote";
P $d, "$;accepted";
P $e, $D, "d";
P $f, $D

```

## Edits

* Case 4 is fixed.
* This also simplifies the calculation that is now done without a loop.
* Unreachable plural "s" removed, function `S` no longer needed.
* Calculation optimized, function `E` no longer needed.
* Bias of 2 added for optimized calculation.
* Larger rewrite to remove most variables some other tricks to save some bytes.
> 6 votes

# Answer
# R, ~~454~~ 421

```
r=as.integer(commandArgs(T)[1])-1;p=function(...){paste(...,sep='')};a='answer ';b='accept';e='ed';f='d';v='vote';d=p('down',v);u=p('up',v);q='question ';z=c();t=r%/%15;if(t>0){z=c(p(t,' ',a,b));r=r%%15;};if(r%in%(8:12))z=c(z,p(a,u));if(r%in%(3:7))z=c(z,p(q,u));if(r%in%c(1,2,6,7,11,12))z=c(z,p(a,b,e));if(r%in%(13:14))z=c(z,p(a,b));if(r%in%c(3,8,13))z=c(z,p(a,d));if(r%in%c(1,4,6,9,11,14))z=c(z,p(a,d,f));cat(z,sep=', ')

```

Thanks to Dennis for his answer which helped me a lot.

## Ungolfed version

```
# read input
r = as.integer(commandArgs(T)[1]) - 1

# shortcut to join strings (... will pass the parameter to paste() *as is*)
p = function(...) {paste(..., sep = '')}

# strings
a = 'answer '; b = 'accept'; e = 'ed'; f = 'd'
v = 'vote'; d = p('down',v); u = p('up',v)
q = 'question '

z = c()

# +15
t = r %/% 15;
if (t > 0) {
    z = c(p(t,' ',a,b))
    r = r %% 15
}

if (r %in% (8:12))              z = c(z,p(a,u));    # answer upvote
if (r %in% (3:7))               z = c(z,p(q,u));    # question upvote
if (r %in% c(1,2,6,7,11,12))    z = c(z,p(a,b,e));  # answer accepted
if (r %in% (13:14))             z = c(z,p(a,b));    # answer accept
if (r %in% c(3,8,13))           z = c(z,p(a,d));    # answer downvote
if (r %in% c(1,4,6,9,11,14))    z = c(z,p(a,d,f));  # answer downvoted

# print operations
cat(z,sep = ', ')

```
> 4 votes

# Answer
# JavaScript - ~~270~~ ~~237~~ ~~227~~ ~~206~~ 192 characters

```
p=prompt,r=p()-1,a="1answer ",v="vote,";s=(r/15|0)+"answer accept,",r%=15;if(r>9)s+=a+"+"+v,r-=10;if(r>2)s+="1question +"+v,r-=5;r>0?s+=a+"accepted,":0;r<-1?s+=a+"-"+v:0;p(r&1?s+=a+"-voted":s)

```

Exactly as many chars as Bash (yeah!), and beats Python and Perl :) It cuts down the reputation until `14` after which it takes after which it takes the other necessary actions, completely loop-style.

EDIT 1: Converted `\n`s to `,`s and converted one `if` block to ternary, and better flooring with short names.

EDIT 2: Big thanks to Alconja who helped me cut down **11** chars. After which I made some more corrections to cut down 2 more chars.

---

**Older Version:**

```
r=prompt()-1,a="1answer ",q="1question ",v="vote,";s=(c=r/15|0)+"answer accept,",r-=c*15;if(r>9)s+=a+"+"+v,r-=10;if(r>2)s+=q+"+"+v,r-=5;r>0?s+=a+"accepted,":0;if(r<-1)s+=a+"-"+v;r&1?s+=a+"-voted":0;alert(s)

```

---

## Test:

**INPUT:** `42`
**OUTPUT:**

```
2answer accept,1answer +vote,1answer accepted,1answer -voted

/*I sincerely hope the output is clear and easy to make out*/

```

**INPUT:** `1337`
**OUTPUT:**

```
89answer accept,1answer accepted,1answer -voted

```

---

## Ungolfed Code:

```
// different version from the golfed code
rep = prompt() - 1
string = ""

function $(z, c, k){
  while(rep > 0 && rep >= z - 2) c += 1 , rep -= z;

  if(c) string += c + k + "\n"
}

a=" answer ", q=" question "

$(15, 0, a + "accept")
$(10, 0, a + "upvote")
$(5, 0, q + "upvote")
$(2, 0, a + "accepted")

function _(z, c, str){
  while(rep <= z) c += 1, rep -= z

  if(c) string += c + str + "\n";
}

_(-2, 0, a + "downvote");
_(-1, 0, a + "downvoted");

alert(string);

```
> 4 votes

# Answer
# JavaScript - 273 256 235

```
p=prompt(s=j="\n")-1;z=" answer",w=" accept",x=" upvoted"+j,y=w+"ed",v=" question",u=" downvoted";if(m=p/15|0)s+=m+z+y+j;r=p-m*15;if(m=r/10|0)s+=m+z+x;r-=m*10;if(m=r/5|0)s+=m+v+x;r-=m*5;n=r/2|0;if(m=r-=n*2)n++,s+=m+u+z+j;alert(s+n+y+z)

```

Combined calculation and output, and golfed further to a total of 287.

Edit: took out some variables for a few shorter.

Removed Math.Floor for |0 approach.

Moved some initialisation to the prompt() param, removed some brackets, alert with final string append.
> 1 votes

# Answer
## C# - 391

A bit long, and I haven't tested this thoroughly (much). :)

```
class R{void Main(string[] a){var r=int.Parse(a[0])-1;var a=new[]{15,10,5,2};var o=new List<string>();Func<int,string>y=z=>{var w="";if(z==15)w=" answer accepted";if(z==10)w=" answer upvotes";if(z==5)w=" question upvotes";if(z==2)w=" answer accepts";return w;};foreach(var x in a)if(r/x>0){o.Add(r/x+y(x));r-=(r/x)*x;}if(r==1)o.Add("1 question downvotes");Console.Write(string.Join(", ",o));

```

**Un-golfed - NEW**

```
class R
{
    void Main(string[] a)
    {
        var r = int.Parse("122")-1; // subtracts 1 from total rep
        var a = new[] {15,10,5,2};
        var o = new List<string>();

        Func<int,string> y =
            z =>
                {
                    var w="";
                    if(z==15) w=" answer accepted";
                    if(z==10) w=" answer upvotes";
                    if(z==5) w=" question upvotes";
                    if(z==2) w=" answer accepts";
                    return w;
                };

        foreach(var x in a) {
            if (r/x>0) {
                o.Add(r/x+y(x));
                r-=(r/x)*x;
            }
        }

        if(r==1)
            o.Add("1 question downvotes");

        Console.Write(string.Join(", ",o));
    }
}

```

**Un-golfed - OLD (409)**

```
class R
{
    void Main(string[] a)
    {
        var r = int.Parse(a[0])-1; // subtracts 1 from total rep
        var v = new[] {" question"," answer"," downvotes"," upvotes"," accepts"," accepted"};
        var o = new List<string>();

        // Starts from 15, then checks all the lower values.
        if (r/15>0) {
            o.Add(r/15+v[1]+v[5]);
            r-=(r/15)*15; // automatic rounding down due to int
        }
        if(r/10>0) {
            o.Add(r/10+v[1]+v[3]);
            r-=(r/10)*10;
        }
        if(r/5>0) {
            o.Add(r/5+v[0]+v[3]);
            r-=(r/5)*5;
        }
        if(r/2>0) {
            o.Add(r/2+v[1]+v[4]);
            r-=(r/2)*2;
        }
        if(r==1) {
            o.Add("1"+v[0]+v[2]);
        }
        Console.Write(string.Join(", ",o));
    }
}

```

**Test:**

```
> prog.exe 120

7 answer accepted, 1 answer upvotes, 2 answer accepts

```
> 1 votes

# Answer
**Python - 213 207**

```
p,k=__import__('itertools').combinations_with_replacement,int(input())
t,m,u=[5,10,-2,-1,15,2],[],iter(range(0,k))
while not m:m=list(filter(lambda v:k-1==sum(v),p(t,next(u))))
print(''.join(map(chr,m[0])))

```

Curse you long function names!

Example: (ignore the trailing newline)

```
$ echo "93" | python per.py | hexdump -C
00000000  0f 0f 0f 0f 0f 0f 02 0a                           |........|

$ echo "11" | python per.py | hexdump -C
00000000  0a 0a                                             |..|

```
> 1 votes

# Answer
## Game Maker Language, 276

```
p=real(keyboard_string())-1j="#"s=""z=" answer"w=" accept"x=" upvoted"+j;y=w+"ed"v=" question"u=" downvoted"if m=floor(p/15)s+=(m+z+y)+j;r=p-m*15if m=floor(r/10)s+=(m+z+x)r-=m*10if m=floor(r/5)s+=(m+v+x)r-=m*5n=floor(r/2)r-=n*2if m=r{n++;s+=(m+u+z)+j}s+=(n+y+z)show_message(s)

```
> 1 votes

# Answer
# C++, 276 (316 w/ includes)

```
#include <stdio.h>
#include <stdlib.h>
p(int&q,int*d){int r;char*s[]={"downvoted","accepted","question","answer","upvoted"};
if(r=(q&&q>=*d)){q-=(*d?*d:2);printf("%s %s\n",s[*(++d)],s[*(++d)]);}return r;}main(
int n,char**v){int q=atoi(v[1]);int d[]={-1,3,0,0,3,1,5,4,2,10,4,3,15,1,3};n=15;while
(p(q,d+n-3)||(n-=3));}

```

Compiles with GCC, with warnings. Example:

```
$ ./a.out 0
$ ./a.out 1
accepted answer
downvoted answer
$ ./a.out 2
accepted answer
$ ./a.out 5
question upvoted
$ ./a.out 10
answer upvoted
$ ./a.out 15
answer accepted
$ ./a.out 16
answer accepted
accepted answer
downvoted answer
$ ./a.out 17
answer accepted
accepted answer

```

Feel free to port this to a language that doesn't require type declarations and post it as your own.
> 1 votes

# Answer
# Python3, 188B

```
n=input()+1
a=n//15
n%=15
A='answer '
print("%d %saccepted\n%d %supvoted\n%d question upvoted\n%d accept %s\n%d downvote %s\n%d %sdownvoted"%(a,A,n//10,A,n%10//5,n%5>2,A,n%5%2,A,n%5==0,A))

```

Usage: `python3 score.py <ret> 11 <ret>` where this script is saved as score.py.

Sample output:

```
$ python score.py
5543
369 answer accepted
0 answer upvoted
1 question upvoted
1 accept answer
0 downvote answer
0 answer downvoted

```
> 1 votes

---
Tags: code-golf
---


title: Golfed+Fast sorting in C

text:
# Question
Title: Golfed+Fast sorting in C
\[**Latest update: benchmark program and preliminary resuls available, see below\]**

So I want to test the speed/complexity tradeoff with a classic application: sorting.

Write an ANSI C function that sorts an array of floating point numbers in *increasing* order.

You can't use *any* libraries, system calls, multithreading or inline ASM.

Entries judged on two components: code length *and* performance. Scoring as follows: entries will be sorted by length (log of #characters without whitespace, so you can keep some formatting) and by performance (log of #seconds over a benchmark), and each interval \[best,worst\] linearly normalised to \[0,1\]. The total score of a program will be the average of the two normalised scores. Lowest score wins. One entry per user.

Sorting will have to (eventually) be in place (i.e. the input array will have to contain sorted values at return time), and you must use the following signature, including names:

```
void sort(float* v, int n) {

}

```

Characters to be counted: those in the `sort` function, signature included, plus additional functions called by it (but not including testing code).

The program must handle any numeric value of `float` and arrays of length \>=0, up to 2^20.

I'll plug `sort` and its dependencies into a testing program and compile on GCC (no fancy options). I'll feed a bunch of arrays into it, verify correctness of results and total run time. Tests will be run on an Intel Core i7 740QM (Clarksfield) under Ubuntu 13.
Array lengths will span the whole allowed range, with a higher density of short arrays. Values will be random, with a fat-tail distribution (both in the positive and negative ranges). Duplicated elements will be included in some tests.
The test program is available here: https://gist.github.com/anonymous/82386fa028f6534af263
It imports the submission as `user.c`. The number of test cases (`TEST_COUNT`) in the actual benchmark will be 3000. Please provide any feedback in the question comments.

Deadline: 3 weeks (7 April 2014, 16:00 GMT). I will post the benchmark in 2 weeks.
It may be advisable to post close to the deadline to avoid giving away your code to competitors.

**Preliminary results, as of benchmark publication:**
Here are some results. The last column shows the score as a percentage, the higher the better, putting Johnny Cage in first place. Algorithms that were orders of magnitude slower than the rest were run on a subset of tests, and time extrapolated. C's own `qsort` is included for comparison (Johnny's is faster!). I'll perform a final comparison at closing time.

# Answer
> 6 votes
## 150 character

Quicksort.

```
/* 146 character.
 * sizeup 1.000; speedup 1.000; */
#define REC_SIZE    \
    sort(l, v+n-l); \
    n = l-v;

/* 150 character.
 * sizeup 1.027; speedup 1.038; */
#define REC_FAST  \
    sort(v, l-v); \
    n = v+n-l;    \
    v = l;

void sort(float* v, int n)
{
    while ( n > 1 )
     {
       float* l = v-1, * r = v+n, x = v[n/2], t;
L:
       while ( *++l < x );
       while ( x < (t = *--r) );

       if (l < r)
        {
          *r = *l; *l = t;
          goto L;
        }
       REC_FAST
     }
}

```

Compressed.

```
void sort(float* v, int n) {
while(n>1){float*l=v-1,*r=v+n,x=v[n/2],t;L:while(*++l<x);while(x<(t=*--r));if(l<r){*r=*l;*l=t;goto L;}sort(v,l-v);n=v+n-l;v=l;}
}

```

# Answer
> 3 votes
## 150 chars (without whitespaces)

```
void sort(float *v, int n) {
    int l=0;
    float t, *w=v, *z=v+(n-1)/2;

    if (n>0) {
      t=*v; *v=*z; *z=t;
      for(;++w<v+n;)
        if(*w<*v)
        {
          t=v[++l]; v[l]=*w; *w=t;
        }
      t=*v; *v=v[l]; v[l]=t;
      sort(v, l++);
      sort(v+l, n-l);
    }
}

```

# Answer
> 3 votes
# 67 70 69 chars

Not fast at all, but incredibly small. It's a hybrid between a selection sort and bubble sort algorithm I guess. If you are actually trying to read this, then you should know that `++i-v-n` is the same as `++i != v+n` .

```
void sort(float*v,int n){
    while(n--){
        float*i=v-1,t;
        while(++i-v-n)
            *i>v[n]?t=*i,*i=v[n],v[n]=t:0;
    }
}

```

# Answer
> 2 votes
## 123 chars (+3 newlines)

A standard Shell sort, compressed.

```
d,i,j;float t;
void sort(float*v,int n){
for(d=1<<20;i=d/=2;)for(;i<n;v[j]=t)for(t=v[j=i++];j>=d&&v[j-d]>t;j-=d)v[j]=v[j-d];
}

```

PS: discovered it is still 10x slower than quicksort. You might as well ignore this entry.

# Answer
> 2 votes
## ~~511~~ 424 character

Inplace radixsort

**Update:** Switches to insertion sort for smaller array sizes (increases benchmark performance by a factor of 4.0).

```
#define H p[(x^(x>>31|1<<31))>>s&255]
#define L(m) for(i=0;i<m;i++)
void R(int*a,int n,int s){if(n<64){float*i,*j,x;for(i=a+1;i<a+n;i++){x=*i;for(
j=i;a<j&&x<j[-1];j--)*j=j[-1];*j=x;}}else{int p[513]={},*q=p+257,z=255,i,j,x,t
;L(n)x=a[i],H++;L(256)p[i+1]+=q[i]=p[i];for(z=255;(i=p[z]-1)>=0;){x=a[i];while
((j=--H)!=i)t=x,x=a[j],a[j]=t;a[i]=x;while(q[z-1]==p[z])z--;}if(s)L(256)R(a+p[
i],q[i]-p[i],s-8);}}void sort(float* v,int n){R(v,n,24);}

```

Formatted.

```
/* XXX, BITS is a power of two. */
#define BITS 8
#define BINS (1U << BITS)
#define TINY 64

#define SWAP(type, a, b) \
    do { type t=(a);(a)=(b);(b)=t; } while (0)

static inline unsigned int floatbit_to_sortable_(const unsigned int x)
{   return x ^ ((0 - (x >> 31)) | 0x80000000);
}

static inline unsigned int sortable_to_floatbit_(const unsigned int x)
{   return x ^ (((x >> 31) - 1) | 0x80000000);
}

static void insertsort_(unsigned int* a, unsigned int* last)
{
    unsigned int* i;
    for ( i = a+1; i < last; i++ )
     {
       unsigned int* j, x = *i;
       for ( j = i; a < j && x < *(j-1); j-- )
          *j = *(j-1);
       *j = x;
     }
}

static void radixsort_lower_(unsigned int* a, const unsigned int size,
  const unsigned int shift)
{
    /* @note setup cost can be prohibitive for smaller arrays, switch to
     * something that performs better in these cases. */
    if (size < TINY)
     {
       insertsort_(a, a+size);
       return;
     }

    unsigned int h0[BINS*2+1] = {}, * h1 = h0+BINS+1;
    unsigned int i, next;

    /* generate histogram. */
    for ( i = 0; i < size; i++ )
       h0[(a[i] >> shift) % BINS]++;

    /* unsigned distribution.
     * @note h0[BINS] == h1[-1] == @p size; sentinal for bin advance. */
    for ( i = 0; i < BINS; i++ )
       h0[i+1] += (h1[i] = h0[i]);

    next = BINS-1;
    while ( (i = h0[next]-1) != (unsigned int) -1 )
     {
       unsigned int x = a[i];
       unsigned int j;
       while ( (j = --h0[(x >> shift) % BINS]) != i )
          SWAP(unsigned int, x, a[j]);
       a[i] = x;
       /* advance bins.
        * @note skip full bins (zero sized bins are full by default). */
       while ( h1[(int) next-1] == h0[next] )
          next--;
     }

    /* @note bins are sorted relative to one another at this point but
     * are not sorted internally. recurse on each bin using successive
     * radii as ordering criteria. */
    if (shift != 0)
       for ( i = 0; i < BINS; i++ )
          radixsort_lower_(a + h0[i], h1[i] - h0[i], shift-BITS);
}

void sort(float* v, int n)
{
    unsigned int* a = (unsigned int*) v;
    int i;

    for ( i = 0; i < n; i++ )
       a[i] = floatbit_to_sortable_(a[i]);

    radixsort_lower_(a, n, sizeof(int)*8-BITS);

    for ( i = 0; i < n; i++ )
       a[i] = sortable_to_floatbit_(a[i]);
}

```

# Answer
> 2 votes
## 395 character

Mergesort.

```
void sort(float* v,int n){static float t[16384];float*l,*r,*p,*q,*a=v,*b=v+n/2,
*c=v+n,x;if(n>1){sort(v,n/2);sort(v+n/2,n-n/2);while(a!=b&&b!=c)if(b-a<=c-b&&b-
a<=16384){for(p=t,q=a;q!=b;)*p++=*q++;for(p=t,q=t+(b-a);p!=q&&b!=c;)*a++=(*p<=
*b)?*p++:*b++;while(p!=q)*a++=*p++;}else{for(l=a,r=b,p=t,q=t+16384;l!=b&&r!=c&&
p!=q;)*p++=(*l<=*r)?*l++:*r++;for(q=b,b=r;l!=q;)*--r=*--q;for(q=t;p!=q;)*a++=
*q++;}}}

```

Formatted.

```
static float* copy(const float* a, const float* b, float* out)
{   while ( a != b ) *out++ = *a++; return out;
}
static float* copy_backward(const float* a, const float* b, float* out)
{   while ( a != b ) *--out = *--b; return out;
}

static void ip_merge(float* a, float* b, float* c)
{
    /* 64K (the more memory, the better this performs). */
#define BSIZE (1024*64/sizeof(float))
    static float t[BSIZE];

    while ( a != b && b != c )
     {
       int n1 = b - a;
       int n2 = c - b;

       if (n1 <= n2 && n1 <= BSIZE)
        {
          float* p = t, * q = t + n1;
          /* copy [a,b] sequence. */
          copy(a, b, t);
          /* merge. */
          while ( p != q && b != c )
             *a++ = (*p <= *b) ? *p++ : *b++;
          /* copy remaining. */
          a = copy(p, q, a);
        }
       /* backward merge omitted. */
       else
        {
          /* there are slicker ways to do this; all require more support
           * code. */
          float* l = a, * r = b, * p = t, * q = t + BSIZE;
          /* merge until sequence end or buffer end is reached. */
          while ( l != b  && r != c && p != q )
             *p++ = (*l <= *r) ? *l++ : *r++;
          /* compact remaining. */
          copy_backward(l, b, r);
          /* copy buffer. */
          a = copy(t, p, a);
          b = r;
        }
     }
}

void sort(float* v, int n)
{
    if (n > 1)
     {
       int h = n/2;
       sort(v, h); sort(v+h, n-h); ip_merge(v, v+h, v+n);
     }
}

```

# Answer
> 2 votes
## 331 326 327 312 chars

Does radix sort 8 bits at a time. Uses a fancy bithack to get negative floats to sort correctly (stolen from http://stereopsis.com/radix.html). It's not that compact, but it is really fast (~8x faster than the fastest prelim entry). I'm hoping for speed trumping code size...

```
#define I for(i=n-1;i>=0;i--)
#define J for(i=0;i<256;i++)
#define R for(r=0;r<4;r++)
#define F(p,q,k) I p[--c[k][q[i]>>8*k&255]]=q[i]

void sort(float *a, int n) {
  int *A = a,i,r,x,c[4][257],B[1<<20];
  R J c[r][i]=0;
  I {
    x=A[i]^=A[i]>>31|1<<31;
    R c[r][x>>8*r&255]++;
  }
  J R c[r][i+1]+=c[r][i];

  F(B,A,0);
  F(A,B,1);
  F(B,A,2);
  F(A,B,3)^(~B[i]>>31|1<<31);
}

```

# Answer
> 1 votes
## ~~154~~ 166 characters

OK, here is a longer but faster quicksort.

```
void sort(float*v,int n){while(n>1){float*j=v,*k=v+n-1,t=*j;while(j<k){while(j<k&&*k>=t)k--;*j=*k;while(j<k&&*j<t)j++;*k=*j;}*k++=t;sort(k,v+n-k);n=j-v;}}

```

Here is a correction to survive sorted inputs. And formatted since white space doesn't count.

```
void sort(float*v, int n){
    while(n>1){
        float*j=v, *k=j+n/2, t=*k;
        *k = *j;
        k = v+n-1;
        while(j<k){
            while(j<k && *k>=t) k--;
            *j=*k;
            while(j<k && *j<t) j++;
            *k=*j;
        }
        *k++ = t;
        sort(k,v+n-k);
        n = j-v;
    }
}

```

# Answer
> 1 votes
# ~~121~~ ~~114~~ 111 characters

Just a quick-and-dirty bubblesort, with recursion. Probably not very efficient.

```
void sort(float*v,int n){int i=1;float t;for(;i<n;i++)v[i-1]>(t=v[i])&&(v[i]=v[i-1],v[i-1]=t);n--?sort(v,n):0;}

```

Or, the long version

```
void sort(float* values, int n) {
  int i=1;  // Start at 1, because we check v[i] vs v[i-1]
  float temp;
  for(; i < n; i++) {
    // If v[i-1] > v[i] is true (!= 0), then swap.
    // Note I am assigning values[i] to temp here. Below I want to use commas
    // so the whole thing fits into one statement, but if you assign temp there you will get sequencing issues (i.e unpredictable swap results)
    values[i - 1] > (temp = values[i]) && (
    // I tried the x=x+y,y=x-y,x=x-y trick, but using a temp
    // turns out to be shorter even if we have to declare the t variable.
      values[i] = values[i - 1],
      values[i - 1] = temp);
  }

  // If n == 1, we are done. Otherwise, sort the first n - 1 elements recursively.
  // The 0 is just because the third statement cannot be empty.
  n-- ? sort(values, n) : 0;
}

```

# Answer
> 1 votes
## ~~221~~ ~~193~~ 172 characters

Heapsort - Not the smallest, but in-place and guarantees O(n\*log(n)) behavior.

```
static void sink(float* a, int i, int n, float t)
{
    float* b = a+i;

    for ( ; (i = i*2+2) <= n; b = a+i )
     {
       i -= (i == n || a[i] < a[i-1]) ? 1 : 0;

       if (t < a[i])
          *b = a[i];
       else
          break;
     }
    *b = t;
}

void sort(float* a, int n)
{
    int i;
    /* make. */
    for ( i = n/2-1; i >= 0; i-- )
       sink(a, i, n, a[i]);
    /* sort. */
    for ( i = n-1; i > 0; i-- )
     {
       float t = a[i]; a[i] = a[0];
       sink(a, 0, i, t);
     }
}

```

Compressed.

```
void sort(float* a,int n){
#define F(p,q,r,x,y) for(i=n/p;q>0;){t=a[i];r;for(j=x;(b=a+j,j=j*2+2)<=y&&(j-=(j==y||a[j]<a[j-1]),t<a[j]);*b=a[j]);*b=t;}
float*b,t;int i,j;F(2,i--,,i,n)F(1,--i,a[i]=*a,0,i)
}

```

# Answer
> 1 votes
# C 270 (golfed)

```
#define N 1048576
void sort(float*v,int n)
{
float f[N],g;
int m[N],i,j,k,x;
g=v[0];k=0;
for(i=0;i<n;i++){for(j=0;j<n;j++){if(m[j]==1)continue;if(v[j]<g){g=v[j];k=j;}}f[i]=g;m[k]=1;for(x=0;x<n;x++){if(m[x]==0){g=v[x];k=x;break;}}}
for(i=0;i<n;i++){v[i]=f[i];}
}

```

Explanation: A blank array is used to store each successive minimum number. An int array is a mask with 0 indicating the number has not yet been copied. After getting the minimum value a mask=1 skips already used numbers. Then the array is copied back to original.

I changed the code to eliminate use of library functions.

# Answer
> 1 votes
## 150 character

Shellsort (w/Knuth gap).

```
void sort(float* v, int n) {
float*p,x;int i,h=0;while(2*(i=h*3+1)<=n)h=i;for(;h>0;h/=3)for(i=h;i<n;i++){x=v[i];for(p=v+i-h;p>=v&&x<*p;p-=h)p[h]=*p;p[h]=x;}
}

```

Formatted.

```
static void hsort(float* v, const int h, const int n)
{
    int i;
    for (i = h; i < n; i++) {
        float* p, x = v[i];
        for (p = v + i-h; p >= v && x < *p; p -= h)
            p[h] = *p;
        p[h] = x;
    }
}

void sort(float* v, int n)
{
    int i, h = 0;
    while (2*(i = h*3+1) <= n)
        h = i;
    for (; h > 0; h /= 3)
        hsort(v, h, n);
}

```

# Answer
> 0 votes
## 144

I shamelessly took Johnny's code, added a tiny optimization and compressed the code in a very dirty way. It should be shorter and faster.

Note that depending on your compiler, sort(q,v+n- ++q) must be replaced by sort(++q,v+n-q).

```
#define w ;while(
void sort(float*v, int n){
    w n>1){
        float *p=v-1, *q=v+n, x=v[n/2], t
        w p<q){
            w *++p<x )
            w *--q>x );
            if( p<q ) t=*p, *p=*q, *q=t;
        }
        sort(q,v+n- ++q);
        n = p-v;
    }
}

```

Well, actually, I started form my code and optimized it, but it seems Johnny already made all the right choices. So I ended up with quasi his code. I didn't think of the goto trick, but I could do without.

# Answer
> 0 votes
## 228 character

Radixsort.

```
void sort(float* v, int n) {
#define A(x,y,z) for(x=y;x<z;x++)
#define B h[(a[i]^(a[i]>>31|1<<31))>>j*8&255]
    int m[1<<20],*a=v,*b=m,*t,i,j;
    A(j,0,4) {
        int h[256] = {};
        A(i,0,n) B++;
        A(i,1,256) h[i] += h[i-1];
        for (i = n-1; i >= 0; i--)
            b[--B] = a[i];
        t = a, a = b, b = t;
    }
}

```

---
Tags: code-challenge, sorting, c
---