随机化数组的标量


14

您必须使用每个数字(0-n含)来填充数组。没有数字应该重复。但是,它们必须是随机顺序的。

规则

禁止所有标准规则和标准漏洞

该数组必须是伪随机生成的。每个可能的排列都应具有相等的概率。

输入值

n 以meta的I / O帖子中允许的任何方式。

输出量

数字数组从0-n包容性开始逐渐增加。


输出可以用换行符分隔吗?
DrnglVrgs

@Riley opps本该抱歉。
Christopher

@ DrnglVrgs是的,它可以
克里斯托弗

通过“数字”,我假设您是指“整数”?
扎卡里

1
@KevinCruijssen IMO列表=数组,但具有搜索支持。因此,确保使用列表
克里斯托弗

Answers:




8

Pyth,3个字节

.Sh

示范

.S洗牌。它隐式地将输入整数强制转换n为range [0, 1, ..., n-1]h+1,并且输入是隐式的。


7

R,16个字节

sample(0:scan())

从读取stdinsample从输入向量中随机采样,返回一个(伪)随机序列。

在线尝试!









3

Japt,4个字节

ò öx

在线尝试


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

天哪,öx除非我注意到“包容性”部分,否则我认为就足够了。(你可以取代x几乎别的,BTW)
ETHproductions

@ETHproductions,那也是我的第一个想法。
毛茸茸的

3

C#,76个字节

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

这将返回一个IOrderedEnumerable,我希望可以,否则我需要更多字节用于.ToArray()



3

Java 8,114 111 97字节

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

-3个字节,并通过@OlivierGrégoire修复了错误。
-4个字节,感谢@Jakob
删除-10个字节.toArray()

说明:

在这里尝试。

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

1
Bug: 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

@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

1
Well, three actually, because I edited again, having myself introduced another bug: > should be >=.
Olivier Grégoire

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


2

Pyth, 4 Bytes

.S}0

Try it here!


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

@EriktheOutgolfer thanks for the hint, but as someone has alread posted the solution you propose I will leave this as this.
KarlKastor

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

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.


What if n > 98?
LegionMammal978

It would fail, of course, but input range wasn't specified in the problem. Please don't make me malloc :)
Computronium

change a into a para to fit the rule more?
l4m2


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!


Yikes that is a lot
Christopher

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


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'

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.


1

JavaScript (ES6), 51 bytes

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

2
I 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

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 prnt.sc/fe0goe
Shaggy

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

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

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

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


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!



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]

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


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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.