在 Livecode 中生成唯一的随机数

Generate Unique Random Numbers in 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"

正确的做法是什么?


附加:有没有办法生成带有例外的随机数?

编程语言的随机函数(几乎)从来都不是真正随机的。创建随机数的一个好方法是将数字 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"

这是一种方法:

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