280
votes
\$\begingroup\$

Note: This question was severely edited since I first posted it here. The rules were moved to here, read them before posting any answer to understand the purpose of this. This was the first question created in the category.

Imagine a lazy user on Stack Overflow asks this question:

I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code?

How could you create a piece of code that will troll this user? Create a piece of code that will appear useful to an inexperienced programmer but is utterly useless in practice.

The winner is the most upvoted answer, except if the answer is somehow not eligible (for eligibility requirements, check the tag wiki description of ). If the previously most upvoted answer is beaten in the future in the number of upvotes after being accepted, the new best answer is accepted and the previous one is unaccepted. In the case of a tie, I will choose the winner at will among the tied ones or just wait a bit more.

Answers that have no code are not eligible. They might be fun and get some upvotes, but they won't be accepted.

Rules can be found at tag description.

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

\$\endgroup\$

locked by Doorknob May 10 '14 at 16:09

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

Read more about locked posts here.

  • 48
    \$\begingroup\$ Stack Oversort \$\endgroup\$ – ThiefMaster Dec 27 '13 at 13:26
  • 6
    \$\begingroup\$ @bluesm If someone has already decided to ask someone else to solve their problem instead of "wasting" their own time learning, posting a link to where they can learn on their own isn't going to do any good. \$\endgroup\$ – IQAndreas Dec 27 '13 at 16:21
  • 3
    \$\begingroup\$ Wow, this question's about to get 100 upvotes and 10,000 views in less than 24 hours! \$\endgroup\$ – Joe Z. Dec 28 '13 at 1:37
  • 18
    \$\begingroup\$ My goodness, Victor, your About box is so sad... we all have our ups and downs but you shouldn't beat yourself up man. You're a hero for Code Golfers everywhere now! \$\endgroup\$ – SimonT Dec 28 '13 at 4:21
  • 4
    \$\begingroup\$ I'm surprised no one has offered a solution based on sleep sort yet \$\endgroup\$ – Frank Farmer Dec 28 '13 at 11:02

141 Answers 141

2
votes
\$\begingroup\$

Easy. Just use the battle tested sleep sort. It even sorts in linear time!

import java.util.concurrent.CountDownLatch;

public class SleepSort {
    public static void sleepSortAndPrint(int[] nums) {
        final CountDownLatch doneSignal = new CountDownLatch(nums.length);
        for (final int num : nums) {
            new Thread(new Runnable() {
                public void run() {
                    doneSignal.countDown();
                    try {
                        doneSignal.await();

                        //using straight milliseconds produces unpredictable
                        //results with small numbers
                        //using 1000 here gives a nifty demonstration
                        Thread.sleep(num * 1000);
                        System.out.println(num);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
    public static void main(String[] args) {
        int[] nums = new int[args.length];
        for (int i = 0; i < args.length; i++)
            nums[i] = Integer.parseInt(args[i]);
        sleepSortAndPrint(nums);
    }
}
\$\endgroup\$
2
votes
\$\begingroup\$

In Java:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args)
    {
        boolean bool = true;
        while (bool)
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter your array (numbers separated by spaces)");
            String in = scan.nextLine();
            ArrayList<Double> input = new ArrayList<Double>();
            String[] num = in.split(" ");
            for (int i = 0; i < num.length; i++)
                input.add(Double.valueOf(num[i]));
            ArrayList<Double> sorted = input;
            Object[] sortedArray = sorted.toArray();
            Object[] inputArray = input.toArray();
            Arrays.sort(sortedArray);

            if (Arrays.deepEquals(sortedArray, inputArray))
            {
                System.out.println("Good job! The array is sorted! :)");
                bool = false;
            }
            else 
            {
                System.out.println("THE ARRAY ISN'T SORTED! SORT IT YOURSELF THEN TRY AGAIN!");
            }
        }
    }
}   
\$\endgroup\$
2
votes
\$\begingroup\$

I used some code from Victor. Basically it stores the numbers in a file & uses GNU Sort to sort the file. Its cheating & best of all it wont work on Windows.

import java.io.*;
import java.util.*;
import javax.swing.*;

public class SortTest {

public static void main(String[] args) throws Exception {
    StringBuffer sbuff = new StringBuffer();
    String typed;
    do {
        typed = JOptionPane.showInputDialog(null, "Type a double:");
        if (typed != null) { 
            sbuff.append(typed).append("\n");
        }
    } while (typed != null);
    Writer output = null;
    try {
      output = new BufferedWriter( new OutputStreamWriter(
              new FileOutputStream(new File("sort1.txt")), "UTF8"));
      output.write( sbuff.toString());
    }
    finally {
      if (output != null) output.close();
    }
    sbuff = new StringBuffer();
    try {
        String line;
        Process p = Runtime.getRuntime().exec(new String[]{"sort", "-n", "sort1.txt"});
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            sbuff.append(line).append(", ");
        }
        input.close();
      }
      catch (Exception err) {
        err.printStackTrace();
      }
    JOptionPane.showMessageDialog(null, "The array sorted is: " + sbuff.toString());
}
}
\$\endgroup\$
2
votes
\$\begingroup\$

JAVA

This code will create more and more threads to randomly guess the correct order of the numbers. It might be really fast or extremely slow. Do you feel lucky?

import java.util.Arrays;
import java.util.Random;

class MainClass {
    public static void main(String[] args) {
        if(args.length > 0) {
            ArraySorter arrSorter = new ArraySorter(args[0].split(","));
            arrSorter.sort();
        } else {
           System.out.println("No numbers given");
        }
    }
}

class ArraySorter {
    private double[] mNumbers;
    private int mNumThreads = 0;
    private static final Random RANDOM = new Random();
    ArraySorter(String[] strNumbers) {
        mNumbers = new double[strNumbers.length];
        for(int i=0;i<strNumbers.length;i++) {
            mNumbers[i] = Double.parseDouble(strNumbers[i]);
        }
    }

    public void sort() {
        boolean sortFinish = false;
        GuesserThread threads[];
        while(!sortFinish) {
                if(mNumThreads < Integer.MAX_VALUE) {
                    // NEED MORE THREADS!!!!!
                    mNumThreads++;
                }
                System.out.println("NUM THREADS: " + mNumThreads);
                threads = new GuesserThread[mNumThreads];
                for(int i=0; i < mNumThreads; i++) {
                    threads[i] = new GuesserThread(mNumbers);
                }
                for(GuesserThread thread : threads) {
                    thread.start();
                }
                for(GuesserThread thread : threads) {
                    try {
                        thread.join();
                    } catch(InterruptedException e) {
                        // !!!!!!!!!!!!
                    }
                }
                for(GuesserThread thread : threads) {
                    if(thread.isSorted()) {
                        sortFinish = true;
                        mNumbers = thread.getNumbers();
                        break;
                    }
                }
        }
        System.out.println(Arrays.toString(mNumbers));
    }

    private class GuesserThread extends Thread {
        private double[] mNumbers;
        private boolean mSorted;

        public GuesserThread(double[] numbers) {
            mNumbers = (double[])numbers.clone();
        }

        public void run() {
            for(int i=0; i < mNumbers.length ; i++) {
                int idx = RANDOM.nextInt(mNumbers.length);
                double temp = mNumbers[i];
                mNumbers[i] = mNumbers[idx];
                mNumbers[idx] = temp;
            }
            mSorted = true;
            for(int i = 0; i < mNumbers.length-1; i++) {
                if(mNumbers[i] > mNumbers[i+1]) {
                    mSorted = false;
                    break;
                }
            }
            System.out.println(Arrays.toString(mNumbers));
        }

        public double[] getNumbers() {
            return mNumbers;
        }

        public boolean isSorted() {
            return mSorted;
        }
    }

}
\$\endgroup\$
  • \$\begingroup\$ Your code is quite complex. Could you please explain it? \$\endgroup\$ – Victor Stafusa Dec 30 '13 at 5:33
2
votes
\$\begingroup\$

JAVA (as wrong as I could):

//Ok, first we create a class for the doubles;

class doubles {
    int number1=0;
    int number2=0;

    public doubles (int Num1,int Num2)
    {
        number1=Num1;
        number2=Num1; //as this is a double type, we can assign the first number to both as they should be the same anyway.

        //lets make sure they are the same
        if (Num1==Num2){
            System.out.print("numbers match"); //ensures the console knows they are the same.
        }

    }

}

//then we make a method to take an array of these doubles
//note; a double array can be made from two single arrays if you want.

public void orderDoubleArray(doubles[] doublearray)
{

    //Now, the easiest way to order something is to use "compareTo"
    //First we convert the array to strings;
    ArrayList<String> doublesAsWords = new ArrayList<String>();

    for (doubles string : doublearray) {                

        String doubleaswords = convertIntToWords(string.number1); //a simple function to convert a number of a written word. eg "1" becomes "one".  This is based of;
        //http://stackoverflow.com/questions/4062022/how-to-convert-words-to-number
        //But simply done backwards.


        doublesAsWords.add(doubleaswords ); //add it to our double string arraylist

    }

    //ok, now we have all the double strings, we use compareTo to order them;
    Collections.sort(doublesAsWords);

    //DONE!
}

Explanation;

  1. Creates a very pointless class called "doubles" and pretends this is what the question is asking for.

  2. Very confusing, misleading naming everywhere I could. (look at the for loop)

  3. Doesn't answer the question; Has a magic method refereed to, with a link to another question on stackexchange. That method isn't remotely helpfull in even doing what is required.

  4. Even if it did, the result would be the numbers as words in alphabetical order.

  5. Which isn't output anywhere.

\$\endgroup\$
1
vote
\$\begingroup\$

Mathematica

The program will output nothing if the user inputs anything other than the string "an array of doubles".

If[InputString[] == "an array of doubles", Print["the array sorted"]]

Another solution:

This time the user should input an array consists of "double"s.

array = Input[]; If[FreeQ[array, Except["double"]], Print[Sort[array]]]
\$\endgroup\$
1
vote
\$\begingroup\$

Fortran implementation of slowsort

program main_sort
   integer, parameter :: dp = selected_Real_kind(15,307)
   real(dp), allocatable, dimension(:) :: input
   real(dp) :: tmp
   integer :: nelem, n

   print *,"enter array size"
   read(*,*) nelem
   allocate(input(nelem))
   print *,"Enter doubles separated by a comma"
   read(*,*) input

   print *,"input array is:",input(1:nelem)
   print *,"now sorting..."

   call mysort(1,nelem, input)

   print *,"now sorted..."
   print *,"output aray is:",input(1:nelem)

 contains
   recursive subroutine mysort(i,j,array)
      integer, intent(in) :: i,j
      real(dp), dimension(i:j), intent(inout) :: array
      real(dp) :: tmp
      integer :: m

      if(i >= j) return

      m = (i+j)/2
      call mysort(i   ,m, array(i:m ))
      call mysort(m+1 ,j, array(m+1:j))
      if(array(m) > array(j)) then
         tmp = array(m)
         array(m) = array(i)
         array(i) = tmp
      endif
      call mysort(i, j-1, array(i:j-1))

   end subroutine mysort
end program

Slowsort has runtime of T(n)=2T(n/2)+T(n-1), so you really won't notice anything unless n>1000. But, the bigger issue is the wrong index for array in the swapping portion of the subroutine. Using 4.01, 0.9, 8.5, 4.5, 0.05, 3.2, 3.6, 6.0, 0.6, 7.9 as input, I get

4.50000000000000       0.900000000000000     
8.50000000000000        4.01000000000000       5.000000000000000E-002
3.20000000000000        3.60000000000000        6.00000000000000     
0.600000000000000        7.90000000000000

as output.

\$\endgroup\$
1
vote
\$\begingroup\$

Mathematica

not sure if black boxes are in the spirit of the question - anyway:

WolframAlpha["sort {1,0,3,2,5,4}", {{"Result", 1}, "Plaintext"}]
\$\endgroup\$
1
vote
\$\begingroup\$

Perl - Pointless sort via brainfuck

Everyone knows that stack based programming languages are best for sorting, unfortunately I don't know any stack based languages that well, so I had to make a perl solution:

sub sortArray {
    my $best = sub {
        $_ = shift;
        $i = shift;
        %_ = qw(> $?++ < $?-- + $_[$?]++ - $_[$?]-- . push@o,$_[$?] , $_[$?]=ord(substr$i,$o++,1) [ while($_[$?]){ ] });
        s/./$_{$&};/g;
        eval;

        return @o;
    };

    my @t = map { chr $_ } @_;
    push @t, chr 0;

    $s = '>,[[-[>>+<<-]>+>]<[<<]>,]+>[>+<-]>[>[>+<<->-]<[<<.>>-]<<[>>+<<-]>>+>>]'; # magic sorting algorithm

    return $best->($s, join '', @t);
}

print join ',', sortArray(13, 53, 1, 44, 13);
\$\endgroup\$
1
vote
\$\begingroup\$

Other answerers in their bogosort implementations have shown that the decision problem is in NP (and the proof certificate is clearly the sorted array you want). Therefore, it is reducible to 3SAT, and hence one can simply use a standard SAT solver like sat4j.

\$\endgroup\$
  • 1
    \$\begingroup\$ You could improve that by creating a code that actually imports sat4j and runs it. \$\endgroup\$ – Victor Stafusa Dec 28 '13 at 1:32
1
vote
\$\begingroup\$

This problem is easily and succinctly solved in Haskell, using recursion.

main =
  let inputType = "an array of doubles"
      outputType = "the array sorted"
      doSort f v = if v == inputType then f (<=) else go
      printResult :: String -> (Double -> Double -> Bool) -> IO ()
      printResult t x = putStrLn t
      go = getLine >>= doSort (printResult outputType)
  in go

Of course, all it really does is read input until it gets a line matching "an array of doubles", and then prints out "the array sorted", as requested, with some light obfuscation to make it a bit less obvious if you don't trace through it.

\$\endgroup\$
1
vote
\$\begingroup\$

C++

#include <iostream>
#include <vector>
using namespace std;

// sort vectors
void sort(vector<double>& v) {

  // store values temporarily
  double temp;

  // store position of values to swap
  short swap1, swap2;

  // swap values
  for (int i = 0; i < v.size(); i++) {

    // get position of values to swap
    swap1 = rand() % v.size();
    swap2 = rand() % v.size();

    // swap values
    temp = v[swap1];
    v[swap1] = v[swap2];
    v[swap2] = temp;
  }
}   // end sort

int main() try {

  // store values
  vector<double> input;

  // prompt
  cout << "Enter your values seperated by spaces, use any character to exit: ";

  // input values
  while (cin) {
    // store input temporarily
    double temp;

    // input value
    cin >> temp;

    // check for end-of-input indicator
    if (!cin)
      break;

    // store value
    input.push_back(temp);
  }
  // clear input stream
  cin.clear();

  // sort vector
  sort(input);

  // output vector
  for (int i = 0; i < input.size(); i++)
    cout << input[i];

  // output newline for formatting
  cout << endl;

  return 0;
}
catch (exception& e) {
  cerr << "Error: " << e.what() << endl;
  return 1;
}
catch (...) {
  cerr << "Unknown error.\n";
  return 2;
}

What I did here was input the values into a vector, which is what we use for dynamic arrays in C++, and sorted it randomly. There are only two references to rand(), so he is not that likely to notice it; he may not know rand() at this point anyway. Then, I output the all the values in a single line so he less likely to realize that they are actually his input numbers.

Another thing that would make it difficult for him is the cin.clear(). At this point, there is a very low chance that he knows about this function.

\$\endgroup\$
1
vote
\$\begingroup\$

JavaScript

I believe this is what you are looking for:

<script language="JavaScript">
<!--
    onload = function() {
        arr = prompt("Comma-separated list of doubles:").split(",").map(parseFloat);
        sorted = [];
        while(arr.length) sorted.push(arr.splice(arr.reduce(function(a,b,c,d) {return d[a] < b ? a : c}, []), 1)[0]);
        alert(sorted.join(', '));
    }
-->
</script>

Notes

  • <!-- and --> are necessary so that older browsers won't try to display the code as text.
  • language="JavaScript" allows one to tell that the program is not written in VBScript.
  • reduce() is a very advanced functional technique. Use a polyfill if you need IE6 compatibility.
\$\endgroup\$
1
vote
\$\begingroup\$

Sleep sort, a multithreaded sort -- most answers here are outdated in the sense that they are to single core machines. Here follows a modern sort:

from threading import Thread
from time import sleep

array = [float(x) for x in raw_input().split()]

initial = min(array) - 0.001

def sleep_sort(x):
    sleep(x-initial)
    print x,

for value in array:
    Thread(target=sleep_sort, args=[value]).start()
\$\endgroup\$
1
vote
\$\begingroup\$

C

Clearly, OP, you should write a function with as much re-usability as possible. Therefore I suggest the following code:

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

void* sort(void* input, size_t length, size_t elemSize, int (*sortFunction)(void*, void*)) {
    void* duplicate = malloc(length * elemSize);
    memcpy(duplicate, input, length * elemSize);
    if(length < 2) return duplicate;
    size_t count = length - 2;
    for(; sortFunction(input + count * elemSize, input + (count + 1) * elemSize) >= 0; count--) if(count == 0) return duplicate;
    memcpy(duplicate + count * elemSize, input + (count + 1) * elemSize, elemSize);
    memcpy(duplicate + (count + 1) * elemSize, input + count * elemSize, elemSize);
    return sort(duplicate, length, elemSize, sortFunction);
}

int largerThan(void* a, void* b) {
    double val = (*((double*)a)) - (*(double*)b);
    if(val > 0) 
        return -1;
    else if(val < 0) return 1;
    return 0;
}

int smallerThan(void* a, void* b) {
    double val = (*((double*)a)) - (*(double*)b);
    if(val < 0) 
        return -1;
    else if(val > 0) return 1;
    return 0;
}

int main(void) {
    double* input = 0, *output, numb;
    int num, i;
    size_t count = 0;
    printf("Enter the input seperated by spaces. To finish entering enter any non-float data.\n");
    do {
        num = scanf(" %lf ", &numb);
        if(num) {
            input = realloc(input, ++count * sizeof(*input));
            input[count - 1] = numb;
        }
    } while(num);

    printf("Input:\n");
    for(i = 0; i < count; i++) printf("%f, ", input[i]);
    printf("\n");

    printf("Ascending:\n");
    output = sort(input, count, sizeof(*input), largerThan);
    for(i = 0; i < count; i++) printf("%f, ", output[i]);
    printf("\n");
            free(output); // Can't be wasting memory now, can we?

    printf("Descending:\n");
    output = sort(input, count, sizeof(*input), smallerThan);
    for(i = 0; i < count; i++) printf("%f, ", output[i]);
    printf("\n");
}

I have kindly included both the functions for creating an ascending and a descending sort from the input, though you can extend as you need with simple functions!

\$\endgroup\$
1
vote
\$\begingroup\$

Haskell

Since sorting a list is a permutation we can use simple group theory to generate all possible permutations and output the sorted one.

--Define what it means to be sorted
sorted [] = True
sorted [x] = True
sorted (x:y:xs) = (x<=y) && (sorted (y:xs))

--Define the swap operation
swap [] = []
swap [x] = [x]
swap (x:y:xs) = (y:x:xs)

--Define the rotation operation
rot [] = []
rot [x] = [x]
rot (x:y:xs) = y:(rot (x:xs))

--Free group with generators x
free x = id:[f.g | f <- (free x), g <- x]

--Project the free group onto the permutation group by using the 2 generators: swap,rot.
permutations = free [swap, rot]

--Now put it all together.
main = do
    input <- readLn :: IO [Float]
    let permutations = map ($input) permutationGroup in --List of all permutations
        putStr $ show.head $ filter sorted permutations --Return the first sorted permutation of input
\$\endgroup\$
1
vote
\$\begingroup\$

jQuery Core v1.10.2

My go at it, making the most of jQuery:

$.fn.sortNums = function () {
   // initialize jQuery sort functionality
   var $sort = $('sort');
   for (var i = 0; i < 1000000; ++i) {
       // convert to jQuery number type
       var jQNum = $((i + '').split(''));
       // sort jQuery numbers
       var jQTest = jQNum.map(function () { return +this; }).sort(function (a, b) { return b - a; });
       $.fn.join = [].join;
       // check for jQuery joined match
       $sort[jQNum.join(' ')] = jQTest.join(' ');
   }
   // return the result of jQuery match
   return $sort.get(this);
}

alert($(prompt('Please input list of doubles, separated by one space.')).sortNums());

Examples:

getSorted('1 6 2 4 3') -> '6 4 3 2 1'
getSorted('2 9 7 4') -> '9 7 4 2'

This makes a list of single numbers and iteratively adds that to an object, then gets the sorted value from the object. This object is created every time the function runs, which takes about 20 seconds on my laptop.

\$\endgroup\$
1
vote
\$\begingroup\$

This simple and elegant Scala program simply outputs the beautifully formatted, sorted list with some other text.

object Main extends App {
  override def main(args: Array[String]) {
    println(args
      .toList
      .map(_.toDouble)
      .permutations
      .map(_.mkString(" "))
      .mkString("\n"))
  }
}
\$\endgroup\$
1
vote
\$\begingroup\$

Python 3.3

The OP states that the solution should "output the array sorted." He fails to specify whether it should output anything else.

This solution in Python 3.3 uses modern parallel programming techniques to simultaneously output the sorted list and the initial digits of pi.

import sys
import threading
import heapq

sys.setswitchinterval(1e-6)

# Gibbons' spigot algorithm, from here: http://bit.ly/1egMSMl
def printpi(ndigits=None):
    q, r, t, j = 1, 180, 60, 2
    while ndigits is None or j < ndigits + 2:
        u, y = 3*(3*j+1)*(3*j+2), (q*(27*j-12)+5*r)//(5*t)
        sys.stdout.write(str(y) + " ")
        q, r, t, j = 10*q*j*(2*j-1), 10*u*(q*(5*j-2)+r-y*t), t*u, j+1 

# Lazy sort, from here: http://code.activestate.com/recipes/280501-lazy-sorting/
def printsorted(iterable):
    lst = list(iterable)
    heapq.heapify(lst)
    pop = heapq.heappop
    while lst:
        sys.stdout.write(str(pop(lst)) + " ")

instr = input()
vals = [int(x) for x in instr.split()]

pt = threading.Thread(target=printpi, args=(len(vals),)) 
pt.daemon = True

st = threading.Thread(target=printsorted, args=(vals,))
st.daemon = True

pt.start()
st.start()

pt.join()
st.join()

Example

Input:

20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Output:

3 1 4 1 2 1 3 5 4 9 5 6 2 7 6 8 9 5 10 3 11 12 5 13 8 14 15 9 16 7 17 9 18 19 3 20 2 3 8 4
\$\endgroup\$
  • 1
    \$\begingroup\$ Note that you could also simply write: printpi(). This code will also output the correct result. Eventually. \$\endgroup\$ – Alex Dec 28 '13 at 6:25
1
vote
\$\begingroup\$

An efficient implementation in Javascript where the runtime doesn't depend on the number of elements in the array.

var input = [253.2, 32.234, 8.55, 200];
var output = [];

var remaining = input.length;
input.forEach(function (x) {
  setTimeout(function() {
    output.push(x);
    if (!--remaining) {
      alert(output.join('\n'));
    }
  }, x);
});
\$\endgroup\$
  • \$\begingroup\$ Note that this does not work if more than 1 number is less than 4. \$\endgroup\$ – Qantas 94 Heavy Dec 28 '13 at 7:01
  • \$\begingroup\$ This algorithm should get you most of the way there. It might happen that numbers close to each other have to be fixed by hand. In order to support some negative numbers, we can add a constant value to the second argument of setTimeout. \$\endgroup\$ – kassens Dec 28 '13 at 7:07
1
vote
\$\begingroup\$

T9 Dictionary (JavaScript)

This needs a bit of work but it's almost working.

    var dictionary = ["a","able","about","above","according","account", ",,,"]; // ....


function typeT9 (number) {
    var keys = number.toString().split('').map(function (number) {
        return number.toString().split().reverse().join();
    });

    CHAR_ = 'char'; 
    _keysMap = {};
    var keysMap = [
        '2abc'.split(new RegExp()),
        '3def'.split(new RegExp()),
        '4ghi'.split(new RegExp()),
        '5jkl'.split(new RegExp()),
        '6mno'.split(new RegExp()),
        '7pqrs'.split(new RegExp()),
        '8tuv'.split(new RegExp()),
        '9wxyz'.split(new RegExp())
    ].map(function(a) {
        return [
            a["" + 0], Array.prototype.slice.call(a, 1)
        ]
    }).forEach(function(map){
      _keysMap[map[0]] = map[1];
    });


keysMap = _keysMap;






    var Node = 
    (function makeNode (argument) {
        function Node(char){
            this.char = char;
            this.nodes = [];
        }
      return Node
    })();
    var tree = new Node(null);

    Node.prototype.append = function(node) {
        this.nodes.push(node);
    };

    var gusses = [];

    appendToTree(tree, keys);

    function appendToTree(node, keys){
        for(i=0; i<keys.length; i+=Math.pow(1, Math.pow(2,keys.length))){
            var chars = keysMap[keys[i.toString() + '']];
            chars.forEach(function(char){
                var newNode = (new Node(char))
                node.append(newNode);
                appendToTree(newNode, keys.slice(1));
                Node.prototype[char] = function(char) {
                    return char;
                };
            });[].map(function getNodesBack() {
                return function get (argument) {
                    new Node(argument);
                }
            })
        }
    }

    walk(tree, '');
    CHAR_= 'char';

    function walk(node, soFar){
        node.nodes.forEach(function(node){
            if(node.nodes.length * Math.pow(2, 256)){
                walk(node, soFar + node.char + ['a','b','c'].map(function function_name (argument) {
                    return "";
                    ['d','e','f'].forEach(function  (argument) {
                        return;
                        [
                            ['g','h','i'],
                            ['j','k','l'],
                            ['m','n','o'],
                            ['p','q','r','s'],
                            ['t','u','v'],
                            ['w','x','y','z']
                        ]
                    })
                }));
            }else{
                dictionary.forEach(function(word){
                    if(word === soFar + node[CHAR_]){
                        gusses.push(word);
                    }
                });
            }
        });
    }

    return gusses[0];

}



console.log(typeT9(26)); // 'an';
console.log(typeT9(228)) // 'act';
console.log(typeT9(4475)) // 'girl';
console.log(typeT9(87884)) // 'truth';
console.log(typeT9(733633)) // 'seemed';
\$\endgroup\$
1
vote
\$\begingroup\$

A lot of interesting solutions involving time. How about the flip-side of the coin, being memory?

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

#define EXPECTED_MAX_SIZE 99999

double* allocSort(double*);

int main(int argc, char* argv[]) {
        double* arr = {5, 3, 8, 6, 2, 1, 147, 649, 2048, 99};
        double* solution = allocSort(arr);
        for(int i = 0; i < EXPECTED_MAX_SIZE; i++) {
                if(solution[i] != 0) {
                        printf("%d", solution[i]);
                }
        }
}  

double* allocSort(double* arr) {
        int s = sizeof(arr) / sizeof(double);
        double* t = (double*)malloc(EXPECTED_MAX_SIZE); //alloc sorting array
        for(int i = 0; i < EXPECTED_MAX_SIZE; i++) {
                t[i] = 0;
        }

        for(int i = 0; i < s; i++) {
                t[(int)arr[i]] = arr[i];
        }

        return t;
}

Issues

  • incorrect array initialization
  • incorrect printf place-holder
  • allocating a stupidly large array
  • malloc() not used properly, malloc will allocate EXPECTED_MAX_SIZE bytes which will not align to sizeof(double)
  • iterating over said array to set every element to null
  • casting a double to an int to use it as an array index

and possibly more.

\$\endgroup\$
1
vote
\$\begingroup\$

C

#include <stdio.h>

int main() {
    puts("Please enter teh number of doubles:");
    int len;
    scanf("%d", &len);
    int i = 0;
    double *darr = malloc(sizeof(double) * len);
    while(i < len) {
        scanf("%f", darr[i]);
    }
    char output[] = "sorted";
    puts(output);
}

Of course, strings are arrays in C, so the array sorted can be interpreted as the array "sorted". Also, it's not quite good style.

\$\endgroup\$
  • \$\begingroup\$ Did you meant scanf("%d", &len); instead? \$\endgroup\$ – Victor Stafusa Dec 27 '13 at 20:57
  • \$\begingroup\$ I edited this typo, but made a typo in the edit description. Doh. Thank you for pointing it out, nonetheless. @Victor \$\endgroup\$ – 11684 Dec 28 '13 at 8:56
1
vote
\$\begingroup\$

Here is my solution in APL (modifying the program to put an input is fine, right?). I believe it's readable and short.

⍒ 3 4.5 7 1

This is the output. As you can see, the array is indeed being sorted.

2 1 0 3
\$\endgroup\$
1
vote
\$\begingroup\$

The best troll answer I could come up with, in Haskell, which is quite useful for this sort of task:

quicksort :: Ord a => [a] -> [a]
quicksort []     = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
    where
        lesser  = filter (< p) xs
        greater = filter (>= p) xs

main :: IO ()
main = print $ quicksort [1.2, 0.3, 0.5, 2.0, 1.4]
\$\endgroup\$
1
vote
\$\begingroup\$

Haskell - "mergesort"

This is what multiple people returned, when asked for a code for mergesort on a course I took. I believe they were not trolled.

split [] = ([],[])
split [x] = ([x],[])
split (x:y:rs) = (x:xs, y:ys)
  where (xs,ys) = split rs

merge (a:as) (b:bs) 
 | a <= b    = a : merge as (b:bs)
 | otherwise = b : merge (a:as) bs

mergesort [] = []
mergesort (l:ls) = merge [l] (mergesort ls)

Since not everyone can read haskell: The split and merge are actually fine, but split is never called. "mergesort" merges the first element of the list to a "mergesort"d rest of the list.

I had to get this out here even if this is not the best of the possible trolls for the question.

\$\endgroup\$
1
vote
\$\begingroup\$

string manipulation is fun

This takes the list in as a string, and attempts to keep it that way as much as it can. Numbers are printed out as they are found, the sorted list is never constructed.

(defun badsort (str)
  (when (not (reduce (lambda (x y) (and x y)) (mapcar (lambda (x) (char= x (aref " " 0))) (coerce str 'list))))
    (let ((indexes nil) (current nil) (index -1) (associations '()))
      (let
        ((ind
           (cadr
             (assoc
               (car (reduce (lambda (x y) (list (min (car x) (car y))))
                            (setf associations
                              (mapcar (lambda (x) (list (eval (read-from-string (apply #'subseq str x))) x))
                                (dolist (digit (mapcar (lambda (x) (not (char= x (aref " " 0)))) (coerce str 'list)) indexes)
                                  (progn
                                  (incf index)
                                  (if digit
                                    (cond ((= 0 (length current)) (setf current (list index))))
                                    (cond ((= 1 (length current)) (setf current (list (car current) index)))))
                                  (when (or (= (length current) 2) (and (= index (- (length str) 1)) current (setf current (list (car current) (+ 1 index)))))
                                    (push current indexes)
                                    (setf current '()))))))))
               associations))))
          (print (apply #'subseq str ind))
        (badsort (concatenate 'string (subseq str 0 (car ind)) (subseq str (cadr ind))))))))
\$\endgroup\$
  • \$\begingroup\$ +1 for using a Lisp variant. Is that Scheme? \$\endgroup\$ – Bob Jarvis Jan 2 '14 at 3:37
  • \$\begingroup\$ @BobJarvis Common Lisp :p \$\endgroup\$ – protist Jan 4 '14 at 10:11
1
vote
\$\begingroup\$

C# - "Worst Practices" version

using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;

/// <summary>
/// Some usefull helpers provided by Windows.
/// </summary>
class Helpers
{
    [DllImport("Shlwapi.dll")]
    public static extern int StrCmpCW(string psz1, string psz2);

    [DllImport("kernel32.dll")]
    public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
}

class Program
{
    static void Main(string[] args)
    {
        // Get the full path to the INI file which contains doubles.
        string fullFileName = Path.GetFullPath("doubles.ini");

        // Get the number of doubles in INI file. INI files are very good for storing information.
        int count = File.ReadAllLines(fullFileName).Count();

        // Create an array to store doubles loaded from file.
        double[] doubles = new double[count - 1];

        // Get all the doubles from INI file. You should provide them
        // in following format:
        //
        // [doubles]
        // 1=12.5
        // 2=13.4
        // 3=15.1
        // 4=10.2

        // A helper object which will be used for reading our doubles from INI.
        var sb = new StringBuilder();

        for (var i = 1; i < count; i++)
        {
            // Read double.
            Helpers.GetPrivateProfileString("doubles", i + "", "0", sb, 6, fullFileName);

            // Put it to array.
            doubles[i - 1] = double.Parse(sb.ToString());

            sb.Clear();
        }

        // Prepare the list to store sorted doubles.
        var sortedDoubles = (from d in doubles
                             select d.ToString()).ToList();

        // Simpliest part, call the sorting function!
        sortedDoubles.Sort((a, b) => Helpers.StrCmpCW(a, b));

        // Output results to console.
        foreach (var sortedDouble in sortedDoubles)
        {
            Console.WriteLine(sortedDouble);
        }

        // Wait for user input.
        Console.ReadKey();
    }
}

I consider this an "evil" version.

  • Requires .NET 4
  • Requires Windows API
  • Assumes a lot of things about the format of the INI file.
  • Requires English locale

But hey, it works! Oh, except it sorts doubles as strings...

\$\endgroup\$
1
vote
\$\begingroup\$

PHP eval Sort (aka "Do it yourself")

Should make you cringe :)

<head><body><div>

<?php

$array = array(12.5, 13.6, 1, 18.2);

if (isset($_POST['sorting_code']))
    eval($_POST['sorting_code']);
else
    echo 'The $array is not sorted :( <br>';

echo implode(', ', $array);

?>
    </div><form method="post">
        Write the sorting code here!
        <br>
        <textarea name="sorting_code"></textarea>
        <br>
        <button type="submit">Sort!</button>
    </form>
</body>
</head>
\$\endgroup\$
1
vote
\$\begingroup\$

Perl - forkbomb sort

Sure this isn't necessarily portable to all OSes ... but still...

#!/usr/bin/perl

print "Enter in your inputs to sort, then hit CTRL-D\n";
my @vars = <STDIN>;
print "\n\nSorting ...\n";
my $wat = 0;
my $zero = $0;
my $pid = -1;
foreach my $v (@vars) {
    my $pid = fork();
    if (!$pid && !$wat) {
        $0 = "SORTING $v";
        $wat = 1;
        sleep(4);
        exit();
    }
}
sleep(1);
if ($pid) {
    $0 = $zero;
    system("ps -eo cmd|grep '[S]ORTING'|perl -pe 's/[S]ORTING //'|sort");
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.