Create, sort, and print a list of 100 random ints in the fewest chars of code
Asked Answered
A

63

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?

Antipasto answered 8/12, 2008 at 21:2 Comment(7)
Don't these questions always end up with someone defining a runtime environment that does exactly the right thing with 1 keypress?Henceforth
True. I wonder, how much can we affect the pre-requisites to our code?Mascot
- How should the ouput be formatted?Jacintojack
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?Glasgo
Sorry, next time I'll write more stringent requirements. call it 0 - maxint32. ok? jeez.... :)Antipasto
It seems that someone defined a runtime named J to implement exactly the right thing with 10 keypresses :PEttie
@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.Betook
R
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.

Remission answered 8/12, 2008 at 21:2 Comment(2)
thats hot. you win. wtf is JAntipasto
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. en.wikipedia.org/wiki/J_(programming_language)Remission
S
25

xkcd style in PHP:

for($i=0;$i<100;$i++) echo "4\n";
Sacrilege answered 8/12, 2008 at 21:2 Comment(1)
Take another +1 for xkcd referenceFerryman
T
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
Tamatamable answered 8/12, 2008 at 21:2 Comment(3)
Note that the line 'od -dAn -N200 /dev/urandom -w2|sort -n' is shorter, but the output is right aligned with the longest number.Dale
Try man /dev/random on MacOS X, much better than cat /dev/random. ;)Eddo
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.Aguish
D
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.

Deliberate answered 8/12, 2008 at 21:2 Comment(7)
I beat you by 4 characters (even after removing your superfluous System namespace refs: (new int[1000]).Select(i => r.Next()).OrderBy(i => i).ToList().ForEach(Console.WriteLine);Jacintojack
And I knocked 2 more chars off changing int to AAntipasto
...and a Sort extension method that was equivalent to OrderBy(i=>i).Deliberate
@Deliberate yeah, that ForEach not being on IEnumerable has puzzled me for a while.Antipasto
@Vilx since learning the linq lambda stuff - I'm hooked. I use it all over the place. Abusing the ToLIst()ForEach() is a nasty hack though. A foreach over the enumerable is far cleaner.Antipasto
ForEach kind of doesn't belong on the IEnumerable monad (Haskell / theoretical stuff), in the same sense that SelectMany and GroupBy do belong.Ettie
Accidentally deleted comment: see balabaster's answer for shorter.Deliberate
K
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
Krupp answered 8/12, 2008 at 21:2 Comment(5)
This is excellent, but should we be counting the code that makes up the shell?Henceforth
You don't even need the "cat -" part: just let sort read from stdin!Saltine
@Henceforth - do the other entries then have to count the code that makes up the run time libraries and the development environment? ;-)Krupp
@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?Saltine
+1 since this actually beats J if you get rid of the echo. I didn't think that was possible.Limnetic
C
7

Mathematica, 28 chars

Sort@RandomInteger[2^32, 100]

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

Cabob answered 8/12, 2008 at 21:2 Comment(0)
P
6

APL

13 chars:

a[⍋a←100?9e8]
Phocine answered 8/12, 2008 at 21:2 Comment(1)
And without any Greek! I'm impressed.Balkh
A
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)) #'<)
Abelmosk answered 8/12, 2008 at 21:2 Comment(2)
It's 47 characters with (random 9), by the wayUpturn
You can save 3 chars by removing spaces next to parens!Misogyny
D
5

Haskell:

import Random
import List
main=newStdGen>>=print.sort.(take 100).randomRs(0,2^32)
Diann answered 8/12, 2008 at 21:2 Comment(2)
Can be shortened (and in my opinion it is even nicer and easier to read :) ). Modules are the same - main=newStdGen>>=print.sort.take 100.randomRs(0::Int,9)Curley
I made it shorter (and changed the upper bound :-p)Pearman
B
5

F#

let r = new System.Random();;

[ for i in 0..100 -> r.Next()] |> List.sort (fun x y -> x-y);;
Beverlee answered 8/12, 2008 at 21:2 Comment(0)
N
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.

Nihility answered 8/12, 2008 at 21:2 Comment(0)
A
4

In BASH:

for i in `seq 100`; do echo $RANDOM; done | sort -n
Abelmosk answered 8/12, 2008 at 21:2 Comment(1)
<powershell user> And you call that elegant or concise? </powershell user>Minnich
F
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
Feudalize answered 8/12, 2008 at 21:2 Comment(0)
G
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();
Glasgo answered 8/12, 2008 at 21:2 Comment(5)
x=[];for(i=0;i<100;)x[i++]=(Math.random()+"").slice(-8);x.sort();Bough
for(x=[],i=100;i;)x[--i]=(Math.random()+"").slice(-8);x.sort()Bough
for(i=100,n=[];i;)n[--i]=(1+Math.random())*1e9<<0;n.sort()Bough
Trimmed one more: for(i=100,n=[];i;)n[--i]=(1+Math.random())*1e9|0;n.sort()Bough
why the "1+"? This looks fine to me: for(i=100,n=[];i;)n[--i]=Math.random()*1e9|0;n.sort();Jerboa
D
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.

Degauss answered 8/12, 2008 at 21:2 Comment(3)
ah, apl. how i havent missed you at all.Bradybradycardia
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 (catpad.net/michael/apl).Degauss
This is not giving a sorted list in my APL interpreter.Phocine
W
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.

Works answered 8/12, 2008 at 21:2 Comment(3)
I was going for brevity, but your post is constructive nonetheless.Saltine
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)])])Crabb
well, just depends on whether we're assuming it's supposed to be one per line; description just says "print 100 integers" :-)Works
B
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));;
Brouwer answered 8/12, 2008 at 21:2 Comment(0)
G
2

Clojure

(defn gen-rands []
(sort (take 100 (repeatedly #(rand-int Integer/MAX_VALUE)))))
Gossipy answered 8/12, 2008 at 21:2 Comment(2)
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.Liederkranz
(sort(for[x(range 100)][(rand-int Integer/MAX_VALUE)])) Something like that.Liederkranz
M
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
Misdemeanor answered 8/12, 2008 at 21:2 Comment(0)
D
2

groovy:

r=new Random()
List l=[]
100.times{ l << r.nextInt(1000) }
l.sort().each { println it }
Dorris answered 8/12, 2008 at 21:2 Comment(0)
C
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);
    }
}
Contestation answered 8/12, 2008 at 21:2 Comment(6)
I like this better than mine as it's a whole application (I cheated by just providing a method) and the meat of it is still more compact.Foreign
Does System.out.println(list); actually print out individual Integers? wow. I didn't know that.Roam
ArrayList's toString prints the entire list, yes.Contestation
Yeah, it does. I didn't use it in mine because IIRC it prints out like [1, 2, 3, ..., n], and I wanted a simple one-integer-per-line output like many other people were doing.Foreign
doesn't calling new Random() like that result in the same seed being used over and over within the same millisecond?Antipasto
I think so. Easily solved by running a few instances of Eclipse, though.Foreign
F
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"
Federicofedirko answered 8/12, 2008 at 21:2 Comment(1)
perl -wE"$,=' ';say sort map int rand 9, 1..100 is even shorterEunaeunice
D
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)
Diffract answered 8/12, 2008 at 21:2 Comment(0)
B
1

Golfscript - 15 chars

[100.{rand}+*]$
Bouncing answered 8/12, 2008 at 21:2 Comment(0)
L
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 :-)

Lanam answered 8/12, 2008 at 21:2 Comment(0)
R
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);
    }
}
Relucent answered 8/12, 2008 at 21:2 Comment(0)
U
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]);}
Urogenous answered 8/12, 2008 at 21:2 Comment(0)
C
1
#!perl

print join "\n", sort { $a <=> $b } map { int rand 0xFFFFFFFF } 1 .. 100;
Cathay answered 8/12, 2008 at 21:2 Comment(0)
O
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"));
}
Oconner answered 8/12, 2008 at 21:2 Comment(0)
B
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 );
        }
    }
}
Breakage answered 8/12, 2008 at 21:2 Comment(0)
D
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++]));
}
Devil answered 8/12, 2008 at 21:2 Comment(0)
J
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()));
    }
}
Jacintojack answered 8/12, 2008 at 21:2 Comment(5)
see linqish version above. it's shorter.Antipasto
I beat you by 4 characters - even after I removed your extra references to the System namespace ;) Beat that sucka :PJacintojack
No, we've still got you beat by 3 chars - assuming you add back in the NEEDED System namespace.Antipasto
Hahaha! I'll get you next time, Gadget!Jacintojack
Okay, I'm just going to mumble about how the fact that this outputs doubles somehow makes it wrong... :)Deliberate
C
1
mzscheme -e "(sort (build-list 100 (λ x (random 9))) <)"

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

Celestaceleste answered 8/12, 2008 at 21:2 Comment(0)
G
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);
Grader answered 8/12, 2008 at 21:2 Comment(0)
S
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)
Saltine answered 8/12, 2008 at 21:2 Comment(3)
Save 7 bytes: sorted([random.randint(0,9))for x in" "*9])Epithelium
recursive, it's a community wiki, you can edit posts yourself.Ungovernable
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 []Manifestative
D
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));
  }
}
Deliberate answered 8/12, 2008 at 21:2 Comment(5)
this c# answer can be FAR shorter. I'm on iPhone but will edit laterAntipasto
Clever way of bypassing the sort by making sure the next number is greater than the last...Jacintojack
see linqish version we've created above.Antipasto
The attempt 2 doesn't generate the same distribution of lists of random numbers. For example, one list your code isn't able to generate is [0,1,2,...,99,int.MaxValue] and this is a valid random list.Lanam
What? Did someone say something about distribution?Mascot
E
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
Eyas answered 8/12, 2008 at 21:2 Comment(0)
S
0

Windows command shell - 71 characters

cmd/v/c"for /L %i in (0,1,99)do @set r=     !random!&echo !r:~-5!"|sort
Shrive answered 8/12, 2008 at 21:2 Comment(0)
I
0

R:

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

Illona answered 8/12, 2008 at 21:2 Comment(0)
C
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]);
}
Cogitate answered 8/12, 2008 at 21:2 Comment(0)
L
0

Matlab:

arrayfun( @(x) display(x), sort( rand(1,100) ) )
Laverty answered 8/12, 2008 at 21:2 Comment(0)
C
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)

Cockburn answered 8/12, 2008 at 21:2 Comment(0)
J
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.

Joaniejoann answered 8/12, 2008 at 21:2 Comment(0)
O
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))
Oneida answered 8/12, 2008 at 21:2 Comment(1)
You can use List.iter (printfn "%d").Curley
A
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
Appellee answered 8/12, 2008 at 21:2 Comment(0)
T
0

Coldfusion:

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

<cfset ArraySort(a, "numeric")>

<cfdump var="#a#">
Transpontine answered 8/12, 2008 at 21:2 Comment(0)
L
0

python, 71 chars

import random
print sorted(random.randint(0,2**31)for i in range(100))
Lanam answered 8/12, 2008 at 21:2 Comment(0)
M
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.

Matrix answered 8/12, 2008 at 21:2 Comment(0)
M
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.
Merciful answered 8/12, 2008 at 21:2 Comment(0)
O
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
Orvil answered 8/12, 2008 at 21:2 Comment(0)
L
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.

Leonerd answered 8/12, 2008 at 21:2 Comment(0)
T
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);
    }
}
Telescope answered 8/12, 2008 at 21:2 Comment(0)
B
0

Pike

void main() {
  array a=({});
  while (sizeof(a)<100) a+=({random(1<<30)});
  sort(a);
  foreach (a, int b) write("%d\n",b);
}
Bough answered 8/12, 2008 at 21:2 Comment(0)
G
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
Guidebook answered 8/12, 2008 at 21:2 Comment(0)
B
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.

Bullpup answered 8/12, 2008 at 21:2 Comment(0)
C
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>")
Cayes answered 8/12, 2008 at 21:2 Comment(5)
var n=[]; while (n.length < 100) n.push(Math.random()*(1<<30)<<0); document.write(n.sort(function(a,b){return a<b?-1:a>b?1:0}).join("<br/>"));Bough
var i=0,n=[];for(;i<100;)n[i++]=Math.random()*(1<<30)<<0;document.write(n.sort(function(a,b){return a<b?-1:a>b?1:0}).join("<br/>"));Bough
for(i=100,n=[];i;)n[--i]=(1+Math.random())*1e9<<0;alert(n.sort()) // If the alertbox is too wide, use document.write insteadBough
<<0 for parseInt is a nice touch :)Remission
for(i=100,n=[];i;)n[--i]=(1+Math.random())*1e9|0;alert(n.sort())Bough
J
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
Jacintojack answered 8/12, 2008 at 21:2 Comment(1)
I'm not a VB.NET programmer (just VB6 occasionally). Could you lose p and just do addressof Console.writeline?Deliberate
F
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";'
Federicofedirko answered 8/12, 2008 at 21:2 Comment(0)
E
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.

Evalynevan answered 8/12, 2008 at 21:2 Comment(0)
F
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);
  }
Foreign answered 8/12, 2008 at 21:2 Comment(2)
@Adam: fixed: use 4 space indentation (or the code button), not pre&code tags, at least with < in the code.Evalynevan
Thank you! I would have caught that, except that it looked fine in the preview.Foreign
I
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.

Ingraft answered 8/12, 2008 at 21:2 Comment(2)
The sort for numerics needs sort { $a <=> $b } Your code only works for single digit numbers, which will sort properly because they are that way in the ASCII table.Dithyramb
You can save a few characters with print "$_\n"Ferryman
B
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?)

Betook answered 8/12, 2008 at 21:2 Comment(2)
Why not (princ (sort '(99 61 47) #'<)) ? No need to get imperative. Also, you forgot the predicate for sort.Upturn
30 characters with my modification, by the way.Upturn
C
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::.

Cholent answered 8/12, 2008 at 21:2 Comment(1)
you can use a set instead of a list for sorting, and output iterator for the output.Fairway

© 2022 - 2024 — McMap. All rights reserved.