21

What is the least amount of code you can write to create, sort (ascending), and print a list of 100 random positive integers? By least amount of code I mean characters contained in the entire source file, so get to minifying.

I'm interested in seeing the answers using any and all programming languages. Let's try to keep one answer per language, edit the previous to correct or simplify. If you can't edit, comment?

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
TheSoftwareJedi
  • 34,421
  • 21
  • 109
  • 151
  • 8
    Don't these questions always end up with someone defining a runtime environment that does exactly the right thing with 1 keypress? – Albert Dec 08 '08 at 21:20
  • True. I wonder, how much can we affect the pre-requisites to our code? – Vilx- Dec 08 '08 at 21:23
  • - How should the ouput be formatted? – BenAlabaster Dec 08 '08 at 21:41
  • positive integers = ??? any positive integers, e.g. random 0's and 1's? or does it have to be a uniform distribution from -(2^(K-1)) to (2^(K-1))-1, for K = 8 or 16 or 32? – Jason S Dec 09 '08 at 13:33
  • Sorry, next time I'll write more stringent requirements. call it 0 - maxint32. ok? jeez.... :) – TheSoftwareJedi Dec 09 '08 at 16:20
  • 3
    It seems that someone defined a runtime named J to implement exactly the right thing with 10 keypresses :P – yfeldblum Aug 03 '09 at 16:23
  • @Justice: No, there's a language called J, not a runtime, and it wasn't defined for this problem. Being based on APL, answers in it are likely to (a) win any similar code golf competition, and (b) be unintelligible to anybody who doesn't know the language. At least it uses regular printed characters, unlike APL which had its own character set. – David Thornley Jul 12 '10 at 17:56

63 Answers63

50

10 characters in J:

/:~100?9e9

explanation:

/:~ sorts an array (technically, applies a lists sorted permutation vector to itself)

x ? limit returns x random numbers less than limit

9e9 (9000000000) is a reasonable upper limit expressible in 3 characters. !9 (9 factorial) is smaller, but requires one less character.

James A. Rosen
  • 64,193
  • 61
  • 179
  • 261
Jimmy
  • 89,068
  • 17
  • 119
  • 137
  • thats hot. you win. wtf is J – TheSoftwareJedi Dec 09 '08 at 16:23
  • it's one of the APL-family languages. Guaranteed to win code-golf tournaments up until someone enters an entry in Golf. APL is probably slightly shorter than J, but the untypeable character set throws me off. http://en.wikipedia.org/wiki/J_(programming_language) – Jimmy Dec 09 '08 at 16:55
25

xkcd style in PHP:

for($i=0;$i<100;$i++) echo "4\n";
clawr
  • 7,877
  • 4
  • 22
  • 14
17

Linux, command line:

% od -dAn -N40 /dev/random | tr ' ' '\n' | sort -nu
4959
6754
8133
10985
11121
14413
17335
20754
21317
30008
30381
33494
34935
41210
41417
43054
48254
51279
54055
55306
adl
  • 15,627
  • 6
  • 51
  • 65
  • 1
    Note that the line 'od -dAn -N200 /dev/urandom -w2|sort -n' is shorter, but the output is right aligned with the longest number. – gnud Dec 09 '08 at 00:09
  • Try man /dev/random on MacOS X, much better than cat /dev/random. ;) – yogman Dec 23 '08 at 01:44
  • Discouraged from here: cat /dev/random actually consume hell lot of time to produce output because it insists on entropy to be gathered by the system. It will usually "freeze" until you type things or move the mouse around to keep producing numbers. – PypeBros Oct 11 '10 at 10:53
8

My entry:

echo enter a bunch of ints, hit control-D when done
cat - | sort -n

or, per Adam in the comments:

echo enter a bunch of ints, hit control-D when done
sort -n
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • This is excellent, but should we be counting the code that makes up the shell? – Albert Dec 08 '08 at 21:18
  • 3
    You don't even need the "cat -" part: just let sort read from stdin! – Adam Rosenfield Dec 08 '08 at 21:21
  • @Albert - do the other entries then have to count the code that makes up the run time libraries and the development environment? ;-) – Paul Tomblin Dec 08 '08 at 21:22
  • @Albert: if you're going to include the code that makes up the shell, then do you include the C runtime that it's built on? Do you include the OS that that's built on? Do you include the machine's microcoded instructions? Where does the madness end? – Adam Rosenfield Dec 08 '08 at 21:40
  • +1 since this actually beats J if you get rid of the echo. I didn't think that was possible. – Meredith L. Patterson Aug 05 '09 at 20:50
8

C#

using System;
using System.Linq;
class A {
    static void Main() {
        var r=new Random();
        new A[100].Select(i=>r.Next()).OrderBy(i=>i).ToList().ForEach(Console.WriteLine);
    }
}

EDIT: made complete program. assumes newlines and spaces could be removed, but left in for clarity :)

EDIT: made even shorter.... I dare someone to improve this one... I've tried for an hour.

EDIT: I think that's a bit shorter.

EDIT: I think that's even more shorter. Ugh, make me stop.

EDIT: One more line, one less character. Debatable...


Explanation

A[100] - an array of any old thing - in this case A's (it's a nice short name). The contents are completely ignored, it's the size of the array that counts.

.Select(i=>r.Next()) - generates an enumerable of 100 values of r.Next().

.OrderBy(i=>i) - sorts the previous in order.

.ToList() - convert the sorted enumerable of int to a List, so we can use ForEach.

ForEach(Console.WriteLine) - call Console.WriteLine 100 times, passing in each integer value in the list.

mackenir
  • 10,801
  • 16
  • 68
  • 100
7

Mathematica, 28 chars

Sort@RandomInteger[2^32, 100]

That gives 100 (sorted) random integers in {0,...,2^32}.

dreeves
  • 26,430
  • 45
  • 154
  • 229
6

APL

13 chars:

a[⍋a←100?9e8]
Fernando Martin
  • 512
  • 1
  • 6
  • 21
6

Common Lisp, int between 0 and 10000 (there is no upper bound for that, but you have to choose one).

(sort (loop repeat 100 collect (random 10000)) #'<)
Pål GD
  • 1,021
  • 8
  • 25
5

Haskell:

import Random
import List
main=newStdGen>>=print.sort.(take 100).randomRs(0,2^32)
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
hiena
  • 935
  • 1
  • 8
  • 9
5

An attempt in ruby:

p [].tap{|a|100.times{a<<rand(9e9)}}.sort

(With eight fewer characters, but requiring the tap kestrel of Ruby 1.9)

-for ruby 1.8:

p (0..?d).map{rand 1<<32}.sort

30 characters. (could trim by 2 by changing back to 9e9, but comment in question says range should be MaxInt32.

AShelly
  • 34,686
  • 15
  • 91
  • 152
georg
  • 2,199
  • 16
  • 11
5

F#

let r = new System.Random();;

[ for i in 0..100 -> r.Next()] |> List.sort (fun x y -> x-y);;
4

In BASH:

for i in `seq 100`; do echo $RANDOM; done | sort -n
gnud
  • 77,584
  • 5
  • 64
  • 78
Pål GD
  • 1,021
  • 8
  • 25
3

Powershell :

35 chars (with PowerShell Community Extensions, which replaces Get-Random):

0..99|%{[int]((random)*10000)}|sort

20 characters (plain PowerShell v2):

0..99|%{random}|sort
Joey
  • 344,408
  • 85
  • 689
  • 683
Raoul Supercopter
  • 5,076
  • 1
  • 34
  • 37
3

Python to print 100 random, sorted integers

import random,sys
print sorted(random.randint(1,sys.maxint)for x in range(100))

@Adam already beat me to it, but I thought using randint() and sys.maxint was sufficiently different to post anyway.

Community
  • 1
  • 1
Jay
  • 41,768
  • 14
  • 66
  • 83
  • I was going for brevity, but your post is constructive nonetheless. – Adam Rosenfield Dec 08 '08 at 21:38
  • nevermind the fact that your output is not what was requested import sys, random print '\n'.join([str(y) for y in sorted([random.randint(1,sys.maxint) for x in range(100)])]) – mjard Dec 09 '08 at 00:12
  • well, just depends on whether we're assuming it's supposed to be one per line; description just says "print 100 integers" :-) – Jay Dec 09 '08 at 00:27
3

APL (interactive):

If you want the numbers 0-99 (or 1-100, depending on whether you have the index origin in your workspace set to 0 or 1) to be unique, it takes 8 characters, like so:

↑100?100

If you don't care about uniqueness, do this (9 characters):

↑?100ρ100

Want larger numbers? Just substitute your upper limit, N, for the second 100 on each line, and your random numbers will be in the range 0 - N-1 (or 1-N if your index origin is set to 1).

If you want to guarantee that your numbers range from 0-99 (or 0 - N-1 if you're going for a larger upper limit) regardless of the index origin setting, just enclose either of the above lines in parentheses and add

-⎕IO

to the end (where ⎕ is APL's quad character). That's an additional 6 characters.

Phil H
  • 19,928
  • 7
  • 68
  • 105
RobH
  • 1,607
  • 2
  • 24
  • 44
  • ah, apl. how i havent missed you at all. – TrevorD Dec 09 '08 at 14:14
  • I've often heard APL being described as a write-only language. :-) With its different set of characters, it's easy to see why, especially when confronted with a complex one-liner such as the one for Conway's game of life shown here (http://catpad.net/michael/apl/). – RobH Dec 09 '08 at 18:27
  • This is not giving a sorted list in my APL interpreter. – Fernando Martin Jun 28 '09 at 02:51
3

Javascript: (via JSDB or Mozilla's Rhino used in shell mode)

x=[];for(i=0;i<100;i++){x.push((Math.random()+"").slice(-8));};x.sort();

Here's a full test run:

c:\>java org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 1 2008 03 06
js> x=[];for(i=0;i<100;i++){x.push((Math.random()+"").slice(-8));};x.sort();
01499626,02403545,02800791,03320788,05748566,07789074,08998522,09040705,09115996,09379424,10940262,11743066,13806434,14113139,14336231,14382956,15581655,16573104,20043435,21234726,21473566,22078813,22378284,22884394,24241003,25108788,25257883,26286262,28212011,29596596,32566749,33329346,33655759,34344559,34666071,35159796,35310143,37233867,37490513,37685305,37845078,38525696,38589046,40538689,41813718,43116428,43658007,43790468,43791145,43809742,44984312,45115129,47283875,47415222,47434661,54777726,55394134,55798732,55969764,56654976,58329996,59079425,59841404,60161896,60185483,60747905,63075065,69348186,69376617,69680882,70145733,70347987,72551703,73122949,73507129,73609605,73979604,75183751,82218859,83285119,85332552,85570024,85968046,86236137,86700519,86974075,87232105,87839338,88577428,90559652,90587374,90916279,90934951,94311632,94422663,94788023,96394742,97573323,98403455,99465016

edit: looks like I can shorten it a few chars by direct assignment rather than "push", and I don't need the {}s:

x=[];for(i=0;i<100;i++)x[i]=(Math.random()+"").slice(-8);x.sort();
Jason S
  • 184,598
  • 164
  • 608
  • 970
2

In OCaml:

List.sort compare (let rec r = function 0 -> [] | a -> (Random.int 9999)::(r (a-1)) in r 100);;

Edit: in OCaml typing that in the toplevel will print out the list, but if you want the list printed to stdout:

List.iter (fun x -> Printf.printf "%d\n" x) (List.sort compare (let rec r = function 0 -> [] | a -> (Random.int 9999)::(r (a-1)) in r 100));;
Niki Yoshiuchi
  • 16,883
  • 1
  • 35
  • 44
2

Perl, a full 8 bytes shorter than nrich's version, and runs under "use warnings;" :)

perl -wle "$,=' ';print sort map {int rand 100} 1..100"
2

Java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

class Rnd {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>(100);
        for (int i = 0; i < 100; i++) list.add(new Random().nextInt());
        Collections.sort(list);
        System.out.println(list);
    }
}
Pål GD
  • 1,021
  • 8
  • 25
2

groovy:

r=new Random()
List l=[]
100.times{ l << r.nextInt(1000) }
l.sort().each { println it }
Ray Tayek
  • 9,841
  • 8
  • 50
  • 90
2

Windows BATCH: 160. This adds a leading zero's to the numbers, but otherwise the sorting is a little messed up (because sort sorts by characters - it doesn't know anything about numbers).

@echo off
set n=%random%.tmp
call :a >%n%
type %n%|sort
del /Q %n%
exit /B 0
:a
for /L %%i in (1,1,100) do call :b
exit /B 0
:b
set i=00000%random%
echo %i:~-5%

As a one-liner and way shorter (72):

cmd/v/c"for /l %x in (0,1,99)do @(set x=0000!RANDOM!&echo !x:~-5!)"|sort
Joey
  • 344,408
  • 85
  • 689
  • 683
Paulius
  • 5,790
  • 7
  • 42
  • 47
2

Clojure

(defn gen-rands []
(sort (take 100 (repeatedly #(rand-int Integer/MAX_VALUE)))))
Chris Bunch
  • 87,773
  • 37
  • 126
  • 127
  • If you drop take and repeatedly, and replace them with 'for', you can shave 5 chars off. Without extraneous whitespace and a function def, you can get down to 54 chars. Even less if you hard code a max-value, like most others have done. – nilamo Sep 24 '09 at 16:51
  • (sort(for[x(range 100)][(rand-int Integer/MAX_VALUE)])) Something like that. – nilamo Sep 24 '09 at 16:52
1

plain old c-code in 167 chars:

main(){int i=100,x[i],n=i;while(i)x[--i]=rand();for(i=0;i<n;i++){int b=x[i],m=i,j=0;for(;j<n;j++)if(x[j]<x[m])m=j;x[i]=x[m];x[m]=b;}i=n;while(i)printf("%d ",x[--i]);}
Roman Glass
  • 784
  • 1
  • 13
  • 20
1

Java, again

import java.util.*;
class R
{
    public static void main(String[]a)
    {
        List x=new Stack();
        while(x.size()<100)x.add((int)(Math.random()*9e9));
        Collections.sort(x);
        System.out.print(x);
    }
}

i don't think it can be made shorter than this.. i also cut out unnecessary spaces.

LE: oh yes it can :) inspired by ding's post..

import java.util.*;
class R
{
    public static void main(String[]a)
    {
        Set x=new TreeSet();
        while(x.size()<100)x.add((int)(Math.random()*9e9));
        System.out.print(x);
    }
}
1

Prolog, 78 characters:

r([]).
r([H|T]):-random(0,1000000,H),r(T).
f(L):-length(R,100),r(R),sort(R,L).

usage in the REPL:

| ?- f(X).

X = [1251,4669,8789,8911,14984,23742,56213,57037,63537,91400,92620,108276,119079,142333,147308,151550,165893,166229,168975,174102,193298,205352,209594,225097,235321,266204,272888,275878,297271,301940,303985,345550,350280,352111,361328,364440,375854,377868,385223,392425,425140,445678,450775,457946,462066,468444,479858,484924,491882,504791,513519,517089,519866,531646,539337,563568,571166,572387,584991,587890,599029,601745,607147,607666,608947,611480,657287,663024,677185,691162,699737,710479,726470,726654,734985,743713,744415,746582,751525,779632,783294,802581,802856,808715,822814,837585,840118,843627,858917,862213,875946,895935,918762,925689,949127,955871,988494,989959,996765,999664]

yes

As some of my teachers would say, it's self explanatory :-)

fortran
  • 74,053
  • 25
  • 135
  • 175
1

Golfscript - 15 chars

[100.{rand}+*]$
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

xkcd-style Python answer - shorter than the current one!

print [4]*100

Real answer, 63 chars:

from random import*;print sorted(randrange(9e9)for i in[0]*100)
Claudiu
  • 224,032
  • 165
  • 485
  • 680
1

C#:

using System;
using System.Collections.Generic;

class App
{
  static void Main()
  {
    List<int> TheList = new List<int>();
    Random r = new Random();
    for ( int i = 0; i < 10; i++ )
      TheList.Add(r.Next());
    TheList.Sort();
    foreach ( int i in TheList )
      Console.WriteLine(i);
  }
}

If you're going for the raw character count you might be able to compress this a bit more. But basically this is it.

Edit: Attempt 2:

using System;

class App
{
  static void Main()
  {
    Random r= new Random();
    for ( int i = 0, j=0; i < 100; i++ )
      Console.WriteLine(j+=r.Next(int.MaxValue/100));
  }
}
mackenir
  • 10,801
  • 16
  • 68
  • 100
Vilx-
  • 104,512
  • 87
  • 279
  • 422
1

Python (interactive):

import random
[int(9*random.random())]

What? It creates a list of one random integer, sorts it (trivially), and prints it out.

Ok, here's a serious answer

import random
sorted([int(9*random.random()) for x in range(9)])

It generates 9 random integers in [0, 9), sorts them, and prints them (in an interactive shell).

And here's a shorter variant that actually produces the 100 required:

from random import*
sorted(randint(0,9)for x in' '*100)
Ponkadoodle
  • 5,777
  • 5
  • 38
  • 62
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • Save 7 bytes: sorted([random.randint(0,9))for x in" "*9]) – recursive Dec 23 '08 at 22:12
  • recursive, it's a community wiki, you can edit posts yourself. – badp Dec 08 '09 at 10:42
  • Recursive, I edited in your solution for you (and saved 3 characters off that). It works in Python 2.6, but can somebody test it in Python3? I don't know if Python 3 lets you go without the [] – Ponkadoodle Feb 25 '10 at 02:49
1

Tcl is dead.

Long live tcl.

Creates a RANDOM (0-99) length list and puts RANDOM (0-99) integers in it.

Also prints to the screen and can be run exactly as shown in a tcl file, or the tcl shell.

set l {}
proc r {} {expr { int(floor(rand()*99)) }}
for {set i 0} {$i<[r]} {incr i} {lappend l [r]}
puts [lsort -integer $l]

PHP is nice too.

confirms completely to exercise


<?
for($i=100;$i--;$l[]=rand());
sort($l);
print_r($l);
alexanderpas
  • 2,712
  • 2
  • 23
  • 33
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168
1
mzscheme -e "(sort (build-list 100 (λ x (random 9))) <)"

He said the least chars, not the least bytes. =)

Helen
  • 87,344
  • 17
  • 243
  • 314
Henk
  • 3,193
  • 2
  • 17
  • 12
1

C#

If you're okay with imposing a limit on the array size then:

Array.ForEach(Guid.NewGuid().ToByteArray().OrderBy(c => c).ToArray(), c => Console.WriteLine(c));

Otherwise, a less restrictive (but slightly more verbose) angle could be taken:

var r = new Random();
(new int[100]).Select(i => r.Next()).OrderBy(i => i).ToList().ForEach(Console.WriteLine);

Okay, I think this is the last time I'm coming back to this one...

116 chars:

using System;
class A
{
    static void Main()
    {
        var r=new Random();
        var n=1D;
        for(int i=0;i<100;i++,Console.WriteLine(n+=r.Next()));
    }
}
BenAlabaster
  • 39,070
  • 21
  • 110
  • 151
1

C++ is not the right tool for this job, but here goes:

#include <algorithm>
#include <stdio.h>

#define each(x) n=0; while(n<100) x

int main()
{
     int v[100], n;
     srand(time(0));
     each(v[n++]=rand());
     std::sort(v, v+100);
     each(printf("%d\n",v[n++]));
}
csl
  • 10,937
  • 5
  • 57
  • 89
1

mackenir: an improvement by 7 characters:

namespace System.Linq {
    class A {
        static void Main() {
            var r = new Random();
            new A[100].Select( i => r.Next() ).OrderBy( i => i ).ToList().ForEach( Console.WriteLine );
        }
    }
}
samael
  • 256
  • 2
  • 4
1

C++ with boost. Too bad that #include's are already half of all the text :)

#include <boost/bind.hpp>
#include <algorithm>
#include <vector>
#include <iterator>
#include <cstdlib>
int main() {
    using namespace std;
    vector<int> a(100);
    transform(a.begin(), a.end(), a.begin(), boost::bind(&rand));
    sort(a.begin(), a.end());
    copy(a.begin(), a.end(), ostream_iterator<int>(cout, "\n"));
}
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
1
#!perl

print join "\n", sort { $a <=> $b } map { int rand 0xFFFFFFFF } 1 .. 100;
PypeBros
  • 2,607
  • 24
  • 37
brian d foy
  • 129,424
  • 31
  • 207
  • 592
0

python, 71 chars

import random
print sorted(random.randint(0,2**31)for i in range(100))
fortran
  • 74,053
  • 25
  • 135
  • 175
0

Coldfusion:

<cfloop index="i" to="100" from="1">
    <cfset a[i] = randrange(1,10000)>
</cfloop>

<cfset ArraySort(a, "numeric")>

<cfdump var="#a#">
dhorn
  • 687
  • 1
  • 5
  • 13
0

Qt4 version (c++), 116 chars.

#include <QtCore>
int main(){QList<int>l;int i=101;while(--i)l<<qrand()%101;qSort(l);foreach(i,l)printf("%d\n",i);}

-> wc -c main.cpp
116 main.cpp
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
0

C#

var sequence = Enumerable.Range(1, 100)
                         .OrderBy(n => n * n * (new Random()).Next());

foreach (var el in sequence.OrderBy(n => n))
    Console.Out.WriteLine(el);

F#

let rnd = System.Random(System.DateTime.Now.Millisecond)

List.init 100 (fun _ -> rnd.Next(100)) 
|> List.sort 
|> List.iter (fun (x: int) -> System.Console.Out.WriteLine(x))
Ray
  • 1,585
  • 9
  • 10
0

C without allocating an array (basically keeps adding a random integer to the last value printed, which implicitly sorts):

#include <stdlib.h>

int main(int argc, char **argv) {
    int i;
    unsigned long baseline = 0;
    srand(atoi(argv[1]));
    for ( i = 0 ; i < 100 ; i++ ) {
        baseline += rand();
        printf("%ld\n", baseline);
    }

}

which, with the usual obfuscation+removal of newlines, goes down to 136 chars.

ps: run with $RANDOM on the command line, obviously.

lorenzog
  • 3,483
  • 4
  • 29
  • 50
0

C#

var r=new Random();
var l=from i in new C[100] let n=r.Next() orderby n select n;

81 characters (including newlines)

0

Matlab:

arrayfun( @(x) display(x), sort( rand(1,100) ) )
mvaz
  • 308
  • 1
  • 4
  • 10
0

Using C - 152 chars

main(){int a=100,b,t,x[a];while(a--)x[a]=rand();a=100;while(b=a--)while(b--)if(x[a]>x[b]){t=x[a];x[a]=x[b];x[b]=t;}a=100;while(a--)printf("%d\n",x[a]);}

or expanded

#include <stdio.h>
int main()
{
    int a=100,b,t,x[a];

    while(a--)x[a]=rand();
    a=100;

    while(b=a--)
        while(b--)
            if(x[a]>x[b])
            {
                t=x[a];
                x[a]=x[b];
                x[b]=t;
            }

    a=100;
    while(a--)
        printf("%d\n",x[a]);
}
jme
  • 311
  • 4
  • 19
0

R:

sort(round(runif(100)*99+1))

Joe Cheng
  • 8,001
  • 42
  • 37
0

Windows command shell - 71 characters

cmd/v/c"for /L %i in (0,1,99)do @set r=     !random!&echo !r:~-5!"|sort
Carlos Gutiérrez
  • 13,972
  • 5
  • 37
  • 47
0

Scala: (61 characters)

1 to 100 map {_ ⇒ Random.nextInt} sortBy identity foreach println

EDIT:

Could be compressed even more (56 characters) by defining identity inline.

1 to 100 map {_ ⇒ Random.nextInt} sortBy {i ⇒ i} foreach println
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
0

prints random 100 random numbers in the range [0,100] sorted in C++

srand((unsigned int)time(NULL)); list<int> r;
for (int i=0;i<100;i++) r.push_back((int)((100)*rand()/(float)RAND_MAX));
r.sort();
for (list<int>::iterator j=r.begin();j!=r.end();j++) cout << *j << endl;

If you don't care about parity then replace r.push_back((int)((100)*rand()/(float)RAND_MAX)) with r.push_back(rand()%(101))

--

Here's a complete program in 200 characters:

#include <algorithm>
#include <iostream>
#include <random>
using namespace std;int main(){int a[100];generate_n(a,100,tr1::mt19937());sort(a,a+100);for(int i=0;i<100;++i){cout<<a[i]<<endl;}return 0;}

Array notation was shorter than any standard container I could find. tr1::mt19937 was the shortest random number generator I could find. using namespace std; was shorter than several instances of std::.

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
mepcotterell
  • 2,670
  • 2
  • 21
  • 28
  • you can use a set instead of a list for sorting, and output iterator for the output. – Raz Jan 04 '09 at 08:15
0

Common Lisp (as I remember it, might have a few details wrong):

(setf a '(99 61 47))
(setf a (sort a))
(princ a)

The numbers are of course random; I chose them right now by dice roll.

(Maybe we could tighten up the definition a little?)

Helen
  • 87,344
  • 17
  • 243
  • 314
David Thornley
  • 56,304
  • 9
  • 91
  • 158
0

Perl command line:

perl -e 'print $_, "\n" foreach sort map {int rand 10} (1..10)'

Prints 10 integers between 0 and 9 and sorts them.

nrich
  • 406
  • 3
  • 7
0

Java:

  public void randList()
  {
  final int NUM_INTS = 100;
  Random r = new Random();
  List<Integer> s = new ArrayList<Integer>();

  for(int i = 0; i < NUM_INTS; i++)
    s.add(r.nextInt());

  Collections.sort(s);

  for(Integer i : s)
    System.out.println(i);
  }

Could be shorter, but the above is pretty clear and mostly-best-practices-compliant. This will generate warnings (raw types) and has bad variable names but is a little shorter.

  void rl()
  {
  Random r = new Random();
  List s = new ArrayList();

  for(int i = 0; i < 100; i++)
    s.add(r.nextInt());

  for(Object i : s)
    System.out.println((Integer) i);
  }
Adam Jaskiewicz
  • 10,934
  • 3
  • 34
  • 37
0

I wouldn't accept that as program spec, too imprecise! :-)

Lua version:

t=table;l={}for i=1,20 do l[#l+1]=math.random(99)end;t.sort(l)print(t.concat(l,' '))

Might be slightly shortened, there might be smarter code too.

PhiLho
  • 40,535
  • 6
  • 96
  • 134
0

A command line PHP one-liner (yes, the trailing semicolon is required...)

php -r 'while (++$i % 101) $j[] = rand(0, 99); sort($j); echo implode(" ", $j)."\n";'
0

VB - 151 chars:

Not quite as elegant as C# sadly...

Sub Main()
    Dim r = New Random
    Enumerable.Range(1, 100) _
      .Select(Function(i) r.Next) _
      .OrderBy(Function(i) i) _
      .ToList _
      .ForEach(AddressOf Console.WriteLine)
End Sub
BenAlabaster
  • 39,070
  • 21
  • 110
  • 151
  • I'm not a VB.NET programmer (just VB6 occasionally). Could you lose p and just do addressof Console.writeline? – mackenir Dec 09 '08 at 15:40
0

This is not a joke. It's the best I can do at the moment. :)

JavaScript:

a=[];for(i=0;i<100;i++){b=Math.round(Math.random()*100);a[i]=b;}c=0;
while(c==0){c=1;for(j=0;j<99;j++){if(a[j]>a[j+1]){d=a[j];a[j]=a[j+1];a[j+1]=d;c=0;}}}
for(k=0;k<100;k++)document.write(a[k],"<br>")
  • var n=[]; while (n.length < 100) n.push(Math.random()*(1<<30)<<0); document.write(n.sort(function(a,b){return ab?1:0}).join("
    "));
    – some Dec 09 '08 at 14:38
  • var i=0,n=[];for(;i<100;)n[i++]=Math.random()*(1<<30)<<0;document.write(n.sort(function(a,b){return ab?1:0}).join("
    "));
    – some Dec 09 '08 at 15:25
  • for(i=100,n=[];i;)n[--i]=(1+Math.random())*1e9<<0;alert(n.sort()) // If the alertbox is too wide, use document.write instead – some Dec 09 '08 at 21:34
  • 1
    <<0 for parseInt is a nice touch :) – Jimmy Dec 09 '08 at 22:58
  • for(i=100,n=[];i;)n[--i]=(1+Math.random())*1e9|0;alert(n.sort()) – some Dec 14 '08 at 04:20
0

Here's the best I can do with a Delphi 2007 Win32 console app (aside from removing some line breaks and indents):

{$APPTYPE CONSOLE}
var a:array[0..99] of integer; i,j,k:integer;
begin
  FOR i:=0 to 99 DO a[i]:=random(maxint)+1;
  FOR i:=0 to 98 DO
    FOR j:=i+1 to 99 DO
      IF a[j]<a[i] THEN begin
        k:=a[i]; a[i]:=a[j]; a[j]:=k
      end;
  FOR i:=0 to 99 DO writeln(a[i])
end.

AFAIK, none of the standard units contain a sorting routine, so I had to write the shortest one I know. Also, since I haven't called Randomize, it produces the same result every time it's run.

Edit: I took "positive integers" to mean every positive (non-zero) number in the range of the integer type, hence the use of maxint (a system constant) and "+1" to ensure it's not zero.

Scott Leis
  • 2,810
  • 6
  • 28
  • 42
0

Plain old C, not so minimal as to be obfuscated:

#include <stdio.h>
#include <stdlib.h>
static int cmp(const void *a, const void *b)
{
    return *(const int *) a > *(const int *) b;
}
int main(void)
{
    int x[100], i;
    for(i = 0; i < 100; i++)
            x[i] = rand();
    qsort(x, 100, sizeof *x, cmp);
    for(i = 0; i < 100; i++)
            printf("%d\n", x[i]);
    return 0;
}

This builds without warnings using gcc 4.1.2 in Linux. In real code, I would of course:

  • Return EXIT_SUCCESS rather than 0
  • Only write the 100 once, and use sizeof x for the remaining references
unwind
  • 391,730
  • 64
  • 469
  • 606
0

Pike

void main() {
  array a=({});
  while (sizeof(a)<100) a+=({random(1<<30)});
  sort(a);
  foreach (a, int b) write("%d\n",b);
}
some
  • 48,070
  • 14
  • 77
  • 93
0

I can't edit or comment, so here's Java v3 (the previous 2 had negative numbers):

import java.util.TreeSet;

class Test {

    public static void main(String[] args) {
        Collection<Double> s = new TreeSet<Double>();
        while (s.size() < 100) s.add(Math.random());
        System.out.println(s);
    }
}
Helen
  • 87,344
  • 17
  • 243
  • 314
0

Erlang, 157 chars

-module (intpr).
-export ([q/0]).
q() ->
    lists:foldl(
    fun(X,A)->io:format("~p,",[X]),A end, 
    n, 
    lists:sort( 
        lists:map(fun(_)->random:uniform(100) end, lists:seq(1,100)) 
    )
    ).

Sure it's not the best erlang solution, basically it creates a list from 1 to 100 (only because I didn't found a better/shorter way to initialize the list) and map every item with a random integer (<100), then the resulting list is sorted. Finally the list is "folded", used just as a way to get through all the items and print them.

cheng81
  • 2,434
  • 2
  • 21
  • 18
0

You would think SQL would be good at this sort of thing:-

SELECT * FROM
(SELECT TRUNC(dbms_random.value(1,100)) r
FROM user_objects
WHERE rownum < 101)
ORDER BY r

That's an Oracle version in 108 characters. Someone might do better in a different variant using a TOP 100 syntax.

Edit, in 82 characters:

select trunc(dbms_random.value(1,100))
from dual 
connect by level < 101
order by 1
tuinstoel
  • 7,248
  • 27
  • 27
WW.
  • 23,793
  • 13
  • 94
  • 121
0

Delphi... alphabetically sorted version

program PrintRandomSorted;

{$APPTYPE CONSOLE}
uses SysUtils,Classes;

var I:Byte;
begin
  with TStringList.Create do
  begin
    for I in [0..99] do
      Add(IntToStr(Random(MaxInt)));
    Sort; Write(Text); Free;
  end;
end.

Properly sorted, using generics..

program PrintRandomSorted;
{$APPTYPE CONSOLE}
uses SysUtils, generics.collections;
var I:Byte;S:String;
begin
  with TList<Integer>.Create do
  begin
    for I in [0..99] do Add(Random(MaxInt));
    Sort;
    for I in [0..99] do WriteLn(Items[I]);
    Free;
  end;
end.
Wouter van Nifterick
  • 23,603
  • 7
  • 78
  • 122
0

Notice that nobody gave an answer in C or C++ ?

Once they were called high-level languages (compared to assembler). Well I guess now they are the low-level.

Eden
  • 1,110
  • 1
  • 12
  • 18