배열의 스칼라를 랜덤 화


14

0-n포함 부터 모든 숫자로 배열을 채워야 합니다. 숫자는 반복해서는 안됩니다. 그러나 무작위 순서 여야합니다.

규칙

모든 표준 규칙 및 표준 허점은 금지되어 있습니다.

배열은 의사 랜덤으로 생성되어야합니다. 가능한 모든 순열은 같은 확률을 가져야합니다.

입력

n 메타에 대한 I / O 포스트에 어떤 식 으로든 허용됩니다.

산출

0-n포괄적 인 숫자의 배열입니다 .


줄 바꿈으로 출력을 분리 할 수 ​​있습니까?
DrnglVrgs

@Riley opps 죄송합니다.
Christopher

@DrnglVrgs 그렇습니다
Christopher

"숫자"라는 말은 "정수"를 의미한다고 가정합니까?
Zacharý

1
@KevinCruijssen IMO 목록 = 배열이지만 검색 지원. 따라서 목록을 사용하십시오
Christopher

답변:


9

펄 6 , 14 바이트

{pick *,0..$_}

시도 해봐

넓히는:

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

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


8

Pyth, 3 바이트

.Sh

데모

.S셔플입니다. 입력 정수 n를 암시 적으로 범위로 캐스트합니다 [0, 1, ..., n-1]. his +1이며 입력은 암시 적으로 수행됩니다.




5

파이썬 2 , 51 바이트

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

온라인으로 사용해보십시오!

random.shuffle()있지만 그것을 반환하는 대신 장소에서 인수를 수정 ...


당신은 할 수 있습니다 사용random.shuffle
coinheringaahing 케어 드

@cairdcoinheringaahing 그래,하지만 작동하지 않습니다. 예를 들어 lambda n:shuffle(range(n+1))출력을 어디에도 쓰지 않습니다.
완전히 인간적인






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"포괄적 인"부분을 발견 할 때까지 충분 하다고 생각했습니다 . (당신은 xbtw를 거의 다른 것으로 바꿀 수 있습니다 )
ETHproductions

@ETHproductions, 저도 처음 생각했습니다.
Shaggy

3

C #, 76 바이트

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

이것은 IOrderedEnumerable을 반환합니다. 괜찮기를 바랍니다. 그렇지 않으면 .ToArray ()에 몇 바이트가 더 필요합니다.



3

자바 (8), 114 (111) 97 바이트

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

@ OlivierGrégoire 덕분에 -3 바이트 및 버그 수정 . @Jakob
덕분에 -4 바이트 . 를 제거하여 -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
버그 : 포함하지 않습니다 n. 수정 및 골프 : for(n++;--n>=0;l.add(n));. 또한 배열을 반환 할 필요가 없다고 말합니다. 배열과 목록은 대부분의 언어에서 동일하므로 목록을 반환하십시오.
Olivier Grégoire

@ OlivierGrégoire Woops .. 제대로 확인하지 않고 게시 만하면 얻을 수 있습니다. 버그 수정 (및 프로세스에 저장된 4 바이트)에 감사드립니다.
Kevin Cruijssen

1
내가 다시 편집 때문에 음, 세 가지 사실은, 자신있는 것은 또 다른 버그를 소개 : >이어야한다 >=.
Olivier Grégoire

1
-4 바이트 : Stack대신 a 를 사용하고 Vector루프를로 변경하십시오 for(;n>=0;l.add(n--));. 그리고 a를 돌려주는 java.util.List것은 확실히 좋습니다.
Jakob


2

피 이스, 4 바이트

.S}0

여기 사용해보십시오!


3 바이트로 골프를 타실 수 있습니다. .S정수 인수와 동일 .SU하고, [0..n]같은 코딩 할 수 있습니다 Uh당신이 사용할 수 있도록, .SUh다음이되는, .Sh.
Outgolfer Erik

@EriktheOutgolfer는 힌트를 주셔서 감사하지만 누군가가 이미 솔루션을 게시 했으므로 이것을 이것으로 남겨 두겠습니다.
KarlKastor

글쎄, 그것은 별도의 대답이어야했는지 아닌지 경계선이지만, 그것이 속임수로 간주된다고 생각하므로 허용되는 경우에도 내장 된 대체물이라고 생각합니다. 그래서 게시하고 싶지 않았습니다. 별거이지만 isaacg는 그랬습니다.
Outgolfer Erik 14

2

C, 75 바이트

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

도중에 배열의 끝에서 초기화하고 나가기 전에 임의의 요소로 교체하는 재귀 함수.


만약에 n > 98?
LegionMammal978

물론 실패하지만 입력 범위가 문제에 지정되지 않았습니다. 나를 malloc으로 만들지 마라 :)
Computronium

a더 규칙에 맞게 파라로 변경 ?
l4m2


2

, 33 바이트

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

온라인으로 사용해보십시오! 링크는 자세한 버전의 코드입니다.

분명히 Charcoal의 목록에서 요소를 제거하는 데 17 바이트가 걸립니다.

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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.