challenge 重複無し乱数

整数nを渡すと1 ~ n までの整数を重複しないようランダムに出力する関数「bingo」を作ってください。

このお題はraynstardさんの投稿を元にしています。ご投稿ありがとうございました。 投稿の内容には表示のしかたも含まれていたのですが、 このお題では「重複しない1~nまでの乱数をどうやって作るか」という点に集中することにして、 結果の整形は続編としてこの後のお題で出すことにします。 サンプル入出力は下のようになります。

>>> bingo(10)
[10, 7, 8, 4, 5, 2, 3, 1, 6, 9]
>>> bingo(3)
[2, 3, 1]
>>> bingo(3)
[2, 3, 1]
>>> bingo(3)
[3, 1, 2]
>>> bingo(10)
[7, 3, 8, 6, 4, 10, 9, 2, 1, 5]

Posted feedbacks - Other

ビンゴ本体より、準備行のほうが多い気がする。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
implement Bingo;

include "sys.m";
	sys: Sys;
include "draw.m";
include "keyring.m";
include "security.m";
	random: Random;

argv0: string;

Bingo: module
{
	init: fn(nil: ref Draw->Context, argv: list of string);
};

usage()
{
	sys->fprint(sys->fildes(2), "usage: %s n\n", argv0);
	raise "fail:usage";
}

init(nil: ref Draw->Context, argv: list of string)
{
	sys = load Sys Sys->PATH;
	random = load Random Random->PATH;
	argv0 = hd argv;
	argv = tl argv;

	n := 10;
	if(argv != nil)
		n = int hd argv;

	a := array[n] of int;
	for(i := 0; i < n; i++)
		a[i] = i+1;

	while(n > 0){
		p := rand() % n;
		sys->print("%d\n", a[p]);
		a[p] = a[--n];
	}
}

rand(): int
{
	r := random->randomint(Random->ReallyRandom);
	if(r < 0)
		r = -r;
	return r;
}

Index

Feed

Other

Link

Pathtraq

loading...