Randomize the scalars of an array

14

2

You must fill an array with every number from 0-n inclusive. No numbers should repeat. However they must be in a random order.

Rules

All standard rules and standard loopholes are banned

The array must be generated pseudo-randomly. Every possible permutation should have a equal probability.

Input

n in any way allowed in the I/O post on meta.

Output

The array of numbers scrambled from 0-n inclusive.

Christopher

Posted 2017-05-30T20:20:14.073

Reputation: 3 428

the output can be separated by newlines? – DrnglVrgs – 2017-05-30T20:48:35.517

@Riley opps that was meant to be gone sorry. – Christopher – 2017-05-31T00:48:08.410

@DrnglVrgs yes it can – Christopher – 2017-05-31T00:48:24.547

By "numbers" I assume you mean "integers"? – Zacharý – 2017-08-10T01:12:50.137

Does it have to be an array, or is a list also acceptable? – Kevin Cruijssen – 2017-08-10T07:53:23.203

@KevinCruijssen if a array is not possible (ahem python) then lists are fine. They are basically the same :P – Christopher – 2017-08-10T16:51:21.350

@2EZ4RTZ And if an array is possible, but longer than using a List? ;) – Kevin Cruijssen – 2017-08-11T06:37:59.203

1@KevinCruijssen IMO lists = array but with searching support. So sure use a list – Christopher – 2017-08-11T14:59:54.273

Answers

9

Perl 6, 14 bytes

{pick *,0..$_}

Try it

Expanded:

{           # bare block lambda with implicit parameter 「$_」

  pick      # choose randomly without repeats
    *,      # Whatever (all)
    0 .. $_ # Range from 0, to the input (inclusive)
}

Brad Gilbert b2gills

Posted 2017-05-30T20:20:14.073

Reputation: 12 713

8

05AB1E, 3 bytes

Ý.r

Try it online!

Ý   # Make a list from 0 to input
 .r # Shuffle it randomly

Riley

Posted 2017-05-30T20:20:14.073

Reputation: 11 345

8

Pyth, 3 bytes

.Sh

Demonstration

.S is shuffle. It implicitly casts an input integer n to the range [0, 1, ..., n-1]. h is +1, and the input is taken implicitly.

isaacg

Posted 2017-05-30T20:20:14.073

Reputation: 39 268

7

R, 16 bytes

sample(0:scan())

reads from stdin. sample randomly samples from the input vector, returning a (pseudo)random sequence.

Try it online!

Giuseppe

Posted 2017-05-30T20:20:14.073

Reputation: 21 077

6

Jelly, 3 bytes

0rẊ

Try it online!

Explanaion:

0rẊ 
0r  Inclusive range 0 to input.
  Ẋ Shuffle.
    Implicit print.

Alternate solution, 3 bytes

‘ḶẊ

Explanation:

‘ḶẊ
‘   Input +1
 Ḷ  Range 0 to argument.
  Ẋ Shuffle.

Try it online!

Comrade SparklePony

Posted 2017-05-30T20:20:14.073

Reputation: 5 784

5

Python 2, 51 bytes

lambda n:sample(range(n+1),n+1)
from random import*

Try it online!

There is random.shuffle() but it modifies the argument in place instead of returning it...

totallyhuman

Posted 2017-05-30T20:20:14.073

Reputation: 15 378

You can use random.shuffle

– caird coinheringaahing – 2018-04-09T17:01:40.263

@cairdcoinheringaahing Yeah, but that wouldn't work. For example, lambda n:shuffle(range(n+1)) wouldn't write the output anywhere. – totallyhuman – 2018-04-09T19:18:39.650

5

PHP, 42 Bytes

$r=range(0,$argn);shuffle($r);print_r($r);

Try it online!

Jörg Hülsermann

Posted 2017-05-30T20:20:14.073

Reputation: 13 026

4

Bash, 18 11 bytes

shuf -i0-$1

Try it online!

DrnglVrgs

Posted 2017-05-30T20:20:14.073

Reputation: 145

If newlines are allowed we can forget the echo part – DrnglVrgs – 2017-05-30T20:53:22.877

3

Japt, 4 bytes

ò öx

Try it online


    :Implicit input of integer U
ò   :Generate array of 0 to U.
öx  :Generate random permutation of array.
    :Implicit output of result.

Shaggy

Posted 2017-05-30T20:20:14.073

Reputation: 24 623

Gosh darn it, I thought öx would be enough until I noticed the "inclusive" part. (You could replace the x with almost anything else, btw) – ETHproductions – 2017-05-30T20:38:05.753

@ETHproductions, that was my first thought too. – Shaggy – 2017-05-30T20:55:14.943

3

MATL, 4 bytes

QZ@q

Try it online!

Explanation

Q     % Implicitly input n. Add 1
Z@    % Random permutation of [1 2 ... n+1]
q     % Subtract 1, element-wise. Implicitly display

Luis Mendo

Posted 2017-05-30T20:20:14.073

Reputation: 87 464

3

CJam, 7 6 bytes

1 byte removed thanks to Erik the Outgolfer.

{),mr}

This is an anonymous block (function) that takes an integer from the stack and replaces it with the result. Try it online!

Explanation

{     e# Begin block
)     e# Increment: n+1
,     e# Range: [0 1 ... n]
mr    e# Shuffle
}     e# End block

Luis Mendo

Posted 2017-05-30T20:20:14.073

Reputation: 87 464

Isn't {),mr} 1 byte shorter? – Erik the Outgolfer – 2017-05-31T18:43:22.760

@EriktheOutgolfer Indeed! Thanks – Luis Mendo – 2017-05-31T21:19:31.253

3

Mathematica, 24 bytes

RandomSample@Range[0,#]&

J42161217

Posted 2017-05-30T20:20:14.073

Reputation: 15 931

3

Brachylog, 2 bytes

⟦ṣ

Try it online!

Explanation

⟦     Range from 0 to Input
 ṣ    Shuffle

Fatalize

Posted 2017-05-30T20:20:14.073

Reputation: 32 976

3

C#, 76 bytes

using System.Linq;i=>new int[i+1].Select(x=>i--).OrderBy(x=>Guid.NewGuid());

This returns an IOrderedEnumerable, I hope that's okay, or else I need a few more bytes for a .ToArray()

LiefdeWen

Posted 2017-05-30T20:20:14.073

Reputation: 3 381

3

Java 8, 114 111 97 bytes

import java.util.*;n->{List l=new Stack();for(;n>=0;l.add(n--));Collections.shuffle(l);return l;}

-3 bytes and bug-fixed thanks to @OlivierGrégoire.
-4 bytes thanks to @Jakob.
-10 bytes by removing .toArray().

Explanation:

Try it here.

import java.util.*;        // Required import for List, Stack and Collections
n->{                       // Method with integer parameter and Object-array return-type
  List l=new Stack();      //  Initialize a List
  for(;n>=0;l.add(n--));   //  Loop to fill the list with 0 through `n`
  Collections.shuffle(l);  //  Randomly shuffle the List
  return l;                //  Convert the List to an Object-array and return it
}                          // End of method

Kevin Cruijssen

Posted 2017-05-30T20:20:14.073

Reputation: 67 575

1Bug: doesn't include n. Fix and golf: for(n++;--n>=0;l.add(n));. Also, I say you don't need to return an array. Array and list are the same in most language, so just return the list. – Olivier Grégoire – 2017-08-10T13:23:59.143

@OlivierGrégoire Woops.. That's what you get for not checking properly and just posting.. Thanks for the bug-fix (and 4 bytes saved in the process). – Kevin Cruijssen – 2017-08-10T13:27:03.990

1Well, three actually, because I edited again, having myself introduced another bug: > should be >=. – Olivier Grégoire – 2017-08-10T13:28:42.837

1-4 bytes: use a Stack instead of a Vector and change your loop to for(;n>=0;l.add(n--));. And returning a java.util.List is definitely fine. – Jakob – 2017-08-10T14:10:45.003

2

Ohm, 2 bytes

#╟

Try it online!

Nick Clifford

Posted 2017-05-30T20:20:14.073

Reputation: 1 184

This is a better link. – Erik the Outgolfer – 2017-05-31T10:20:04.870

2

Pyth, 4 Bytes

.S}0

Try it here!

KarlKastor

Posted 2017-05-30T20:20:14.073

Reputation: 2 352

You can golf to 3 bytes. .S with an integer argument is the same as .SU, and [0..n] can be coded as Uh, so you can use .SUh, which then becomes .Sh. – Erik the Outgolfer – 2017-05-31T18:46:02.280

@EriktheOutgolfer thanks for the hint, but as someone has alread posted the solution you propose I will leave this as this. – KarlKastor – 2017-05-31T21:32:11.007

Well, it's borderline whether that should've been a separate answer or not, but I believe it counts as a dupe, so even it being allowed, I'd consider it just builtin substitution, so nah, I didn't want to post separate, but isaacg did. – Erik the Outgolfer – 2017-06-01T09:30:14.307

2

C, 75 bytes

a[99],z,y;f(n){if(n){a[n]=--n;f(n);z=a[n];a[n]=a[y=rand()%(n+1)];a[y]=z;}}

Recursive function that initializes from the array's end on the way in, and swaps with a random element before it on the way out.

Computronium

Posted 2017-05-30T20:20:14.073

Reputation: 151

What if n > 98? – LegionMammal978 – 2017-05-31T15:11:38.683

It would fail, of course, but input range wasn't specified in the problem. Please don't make me malloc :) – Computronium – 2017-05-31T15:40:01.097

change a into a para to fit the rule more? – l4m2 – 2018-04-09T16:00:53.493

67 bytes – ceilingcat – 2019-04-01T03:57:58.573

2

Charcoal, 33 bytes

A…·⁰NβFβ«AβδA‽δθPIθ↓A⟦⟧βFδ¿⁻θκ⊞βκ

Try it online! Link is to verbose version of code.

Apparently it takes 17 bytes to remove an element from a list in Charcoal.

Edit: These days it only takes three bytes, assuming you want to remove all occurrences of the item from the list. This plus other Charcoal changes cut the answer down to 21 bytes: Try it online!

Neil

Posted 2017-05-30T20:20:14.073

Reputation: 95 035

Yikes that is a lot – Christopher – 2017-06-01T01:16:25.453

2

APL (Dyalog), 5 bytes

?⍨1+⊢

Try it online!

Assumes ⎕IO←0, which is default on many machines.

Explanation

the right argument

1+ add 1 to it

?⍨ generate numbers 0 .. 1+⊢-1 and randomly deal them in an array so that no two numbers repeat

user41805

Posted 2017-05-30T20:20:14.073

Reputation: 16 320

2

q/kdb+, 11 bytes

Solution:

{(0-x)?1+x}

Example:

q){(0-x)?1+x}10
5 9 7 1 2 4 8 0 3 10
q){(0-x)?1+x}10
6 10 2 8 4 5 9 0 7 3
q){(0-x)?1+x}10
9 6 4 1 10 8 2 7 0 5

Explanation:

Use the ? operator with a negative input to give the full list of 0->n without duplicates:

{(0-x)?1+x} / solution
{         } / lambda expression
         x  / implicit input
       1+   / add one
      ?     / rand
 (0-x)      / negate x, 'dont put item back in the bag'

streetster

Posted 2017-05-30T20:20:14.073

Reputation: 3 635

2

TI-83 BASIC, 5 bytes (boring)

randIntNoRep(0,Ans

Yep, a builtin. randIntNoRep( is a two-byte token, and Ans is one byte.

More fun, 34 bytes:

Ans→N
seq(X,X,0,N→L₁
rand(N+1→L₂
SortA(L₂,L₁
L₁

Straight from tibasicdev. Probably golfable, but I haven't found anything yet.

What this does: Sorts a random array, moving elements of the second arg (L₁ here) in the same way as their corresponding elements.

Khuldraeseth na'Barya

Posted 2017-05-30T20:20:14.073

Reputation: 2 608

1

JavaScript (ES6), 51 bytes

n=>[...Array(n+1).keys()].sort(_=>.5-Math.random())

Shaggy

Posted 2017-05-30T20:20:14.073

Reputation: 24 623

2I don't think this is uniform; I've tried f(5) 10 times and 5 has been one of the last two items every time. – ETHproductions – 2017-05-30T21:47:58.617

Just ran it again a couple of times myself and got 1,5,4,0,2,3 & 1,0,2,5,3,4. EDIT: And a few more https://prnt.sc/fe0goe

– Shaggy – 2017-05-30T22:27:53.877

3

Just ran a quick test which runs f(5) 1e5 times and finds the average position of each number in the results. The resulting array was [ 1.42791, 1.43701, 2.00557, 2.6979, 3.3993, 4.03231 ], so I don't think it's uniform. (code)

– ETHproductions – 2017-05-30T22:35:39.000

I think I have a 93 byte solution that could work. n=>(a=[...Array(n).keys(),n++]).reduce((a,v,i)=>([a[i],a[j]]=[a[j=n*Math.random()|0],v],a),a)? – kamoroso94 – 2017-05-31T07:39:30.327

Sorting on the result of random() isn't uniform. See (for example) https://en.wikipedia.org/wiki/BrowserChoice.eu#Criticism

– Neil – 2017-05-31T09:07:17.417

@kamoroso94 Strictly speaking, shuffling using n* isn't uniform either, you need to use i* for a truly random shuffle. – Neil – 2017-05-31T09:10:58.680

1

Aceto, 15 14 16 bytes

@lXp
Y!`n
zi&
0r

Push zero on the stack, read an integer, construct a range and shuffle it:

Y
zi
0r

Set a catch mark, test length for 0, and (in that case) exit:

@lX
 !`

Else print the value, a newline, and jump back to the length test:

   p
   n
  &

(I had to change the code because I realized I misread the question and had constructed a range from 1-n, not 0-n.)

L3viathan

Posted 2017-05-30T20:20:14.073

Reputation: 3 151

1

Go, 92 bytes

Mostly losing to the need to seed the PRNG.

import(."fmt";."math/rand";."time")
func f(n int){Seed(Now().UnixNano());Println(Perm(n+1))}

Try it online!

totallyhuman

Posted 2017-05-30T20:20:14.073

Reputation: 15 378

1

Ruby, 20 bytes

->n{[*0..n].shuffle}

canhascodez

Posted 2017-05-30T20:20:14.073

Reputation: 201

1

8th, 42 36 34 bytes

Code

>r [] ' a:push 0 r> loop a:shuffle

SED (Stack Effect Diagram) is n -- a

Usage and example

ok> 5 >r [] ' a:push 0 r> loop a:shuffle .
[2,5,0,3,1,4]

Chaos Manor

Posted 2017-05-30T20:20:14.073

Reputation: 521

1

Javascript (ES6), 68 bytes

n=>[...Array(n+1)].map((n,i)=>[Math.random(),i]).sort().map(n=>n[1])

Creates an array of form

[[Math.random(), 0],
 [Math.random(), 1],
 [Math.random(), 2],...]

Then sorts it and returns the last elements in the new order

Oki

Posted 2017-05-30T20:20:14.073

Reputation: 311

1

Tcl, 90 bytes

proc R n {lsort -c {try expr\ rand()>.5 on 9} [if [incr n -1]+2 {concat [R $n] [incr n]}]}

Try it online!

Tcl, 96 bytes

proc R n {proc f a\ b {expr rand()>.5}
set i -1
while \$i<$n {lappend L [incr i]}
lsort -c f $L}

Try it online!

sergiol

Posted 2017-05-30T20:20:14.073

Reputation: 3 055

1

J, 11 Bytes

(?@!A.i.)>:

Explanation:

         >:   | Increment
(?@!A.i.)     | Fork, (f g h) n is evaluated as (f n) g (h n)
      i.      | Integers in range [0,n) inclusive
 ?@!          | Random integer in the range [0, n!)
    A.        | Permute right argument according to left

Examples:

    0 A. i.>:5
0 1 2 3 4 5
    1 A. i.>:5
0 1 2 3 5 4
    (?@!A.i.)>: 5
2 3 5 1 0 4
    (?@!A.i.)>: 5
0 3 5 1 2 4

Bolce Bussiere

Posted 2017-05-30T20:20:14.073

Reputation: 970

0

JavaScript ES6, 60 bytes, uniform distribute

f=n=>n?(z=f(n-1),z[n]=z[y=Math.random()*-~n|0],z[y]=n,z):[0]

s={};
for(i=0; i<1000; i++) k=f(2), s[k]=-~s[k];
for(i in s) console.log(i, s[i]);

l4m2

Posted 2017-05-30T20:20:14.073

Reputation: 5 985

0

AWK, 82 bytes

{srand();for(n=$1+1;j++<n;$j=j-1);for(;n;n--){t=$(i=int(n*rand()+1));$i=$n;$n=t}}1

Try it online!

AWK doesn't have a built-in shuffle, so this is the best I could come up with.

Robert Benson

Posted 2017-05-30T20:20:14.073

Reputation: 1 339