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

▼魔方 西西 提交于 2019-12-31 09:00:07

问题


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?


回答1:


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.




回答2:


xkcd style in PHP:

for($i=0;$i<100;$i++) echo "4\n";



回答3:


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



回答4:


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



回答5:


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.




回答6:


Mathematica, 28 chars

Sort@RandomInteger[2^32, 100]

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




回答7:


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)) #'<)



回答8:


APL

13 chars:

a[⍋a←100?9e8]



回答9:


F#

let r = new System.Random();;

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



回答10:


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.




回答11:


Haskell:

import Random
import List
main=newStdGen>>=print.sort.(take 100).randomRs(0,2^32)



回答12:


In BASH:

for i in `seq 100`; do echo $RANDOM; done | sort -n



回答13:


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();



回答14:


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.




回答15:


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.




回答16:


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



回答17:


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"



回答18:


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);
    }
}



回答19:


groovy:

r=new Random()
List l=[]
100.times{ l << r.nextInt(1000) }
l.sort().each { println it }



回答20:


Clojure

(defn gen-rands []
(sort (take 100 (repeatedly #(rand-int Integer/MAX_VALUE)))))



回答21:


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));;



回答22:


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



回答23:


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++]));
}



回答24:


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 );
        }
    }
}



回答25:


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"));
}



回答26:


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()));
    }
}



回答27:


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]);}



回答28:


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);
    }
}



回答29:


mzscheme -e "(sort (build-list 100 (λ x (random 9))) <)"

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




回答30:


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);


来源:https://stackoverflow.com/questions/350885/create-sort-and-print-a-list-of-100-random-ints-in-the-fewest-chars-of-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!