在动态代码中生成唯一的随机数

时间:2015-01-18 13:11:29

标签: random unique livecode

我在card1上创建了一个包含六个按钮(五个小按钮和一个大按钮)的新堆栈。每个按钮都有这样的数字。

button1 - 1
button2 - 2
button3 - 3
button4 - 4
button5 - 5

当我点击大按钮时,我想要随机地交换这些数字......

button1 - 4
button2 - 5
button3 - 1
button4 - 2
button5 - 3

再次点击按钮后......

button1 - 4
button2 - 3
button3 - 5
button4 - 2
button5 - 1

每当我一次又一次点击大按钮时,数字就会被交换。

我在大按钮上为onmouseup处理程序尝试了这个脚本,但这不是正确的方法,因为有时会导致进程延迟。

put random(5) into num1
put random(5) into num2
put random(5) into num3
put random(5) into num4
put random(5) into num5

repeat until num2 is not num1
   put random(5) into num2
end repeat

repeat until num3 is not num1 and num3 is not num2
   put random(5) into num3
end repeat


repeat until num4 is not num3 and num4 is not num2 and num4 is not num1
   put random(5) into num4
end repeat

repeat until num5 is not num4 and num5 is not num3 and num5 is not num2 and num5 is not num1
   put random(5) into num5
end repeat

put num1 to button "button1"
put num2 to button "button2"
put num3 to button "button3"
put num4 to button "button4"
put num5 to button "button5"

这样做的正确方法是什么?


附加:有没有办法生成包含异常的随机数?

2 个答案:

答案 0 :(得分:2)

这是一种方式:

put "1,2,3,4,5" into theList
sort items of theList by random(10000)
repeat with N = 1 to 5
   set label of button ("button" & N) to item N of theList
end repeat

答案 1 :(得分:0)

编程语言的随机函数(几乎)从不真正随机。创建随机数的一个好方法是在一张纸上写下1到99的数字,然后将纸放回碗中。现在绘制一个数字并将其写在列表中。放入纸张b继续,直到列表中有100个或1000个数字。现在你有100个完全随机的数字。

您的脚本现在可以使用此列表。从第一行的第一个数字开始,然后是第二个,等等,直到100(或1000)。请记住首选项文件中的行号,以便继续下一个会话。

如果您不需要真正的随机性,可以使用LiveCode的random()函数。您也可以使用any关键字。

这是N按钮的一般解决方案

repeat with n = 1 to N
  put n & comma after myList
end repeat
delete last char of myList
sort items of myList by random(N)
lock screen
repeat with n = 1 to N
  set the label of btn n to item n of myList
end repeat
unlock screen

该脚本首先创建一个数字列表,其中包含与按钮一样多的项目。 sort命令为每个项目分配一个随机数,然后按照分配的编号对项目进行排序。我们锁定屏幕以避免在每次设置标签后重新绘制,这加快了过程。最后一个重复循环将每个按钮的标签设置为列表中的相应项目。

我不喜欢你用于按钮的名字。它们容易出错,如果几年后再次阅读代码,您可能不记得按钮的用途。您可能希望为按钮指定更具描述性的名称,而不需要在脚本中使用此名称。相反,您可以将按钮分组并将此组称为“Randomly Numbered Buttons”。现在改变

set the label of btn n to item n of myList

进入

set the label of btn n of grp "Randomly Numbered Buttons" to item n of myList

如果你这样做,你也可以改变

repeat with n = 1 to N

repeat with n = 1 to the number of buttons of grp "Randomely Numbered Buttons"