我正在尝试在picaxe上制作一个yahtzee得分器,除了有这么多不同的组合之外,一切都是可以的。我在想,是否有一种方法可以测试我的5个变量中是否有4个是相同的(不多也不少),而不必经历所有不同的组合,例如:如果b1=b2和b1=b3,b1=b4和b1!=b5,那么……如果b1=b2和b1=b3以及b1=b5和b1!=b4,那么...
总而言之,有没有一种方法可以让我看到5个变量中只有4个是相同的。
发布于 2018-02-02 06:06:45
因为您已经告诉我们这是针对Yahtzee得分者的,所以我假设我们需要比较的五个变量表示掷五个骰子,因此它们的值将只在1到6之间。
在这种情况下,函数解决方案是计算多少个变量等于测试值,并对1到6之间的测试值重复此操作:
; define symbols for the two variables we will use
symbol same_test = b6
symbol same_count = b7
b1 = 3: b2 = 3: b3 = 3: b4 = 3: b5 = 1 ; test data
gosub test4same
if same_count = 4 then found_4_same ; do something
; else program flow continues here
end
found_4_same:
sertxd("found 4 the same")
end
test4same: ; test if any four of the variables are equal
same_count = 0
for same_test = 1 to 6
if b1 = same_test then gosub found_one
if b2 = same_test then gosub found_one
if b3 = same_test then gosub found_one
if b4 = same_test then gosub found_one
if b5 = same_test then gosub found_one
if same_count = 4 then exit ; 4 variables were equal to same_test
same_count = 0
next
return
found_one:
inc same_count
return对于1到6之间的数字,gosub test4same将检查五个变量b1到b5中是否有四个变量等于相同的数字。如果是,变量same_count将为4,四个变量等于的数字将以same_test表示。
在将same_count重置为零之前使用if ... then exit结构是我能想到的最有效的方式来判断我们是否发现了四个相同的值。
在两个symbol语句之后和标签test4same之前的代码只是为了演示它的工作;将其替换为您的实际程序。
原则上,您可以在任何范围的值上使用相同的技术,但显然,如果您需要测试一个byte变量的所有256个可能值,它会变得有点慢。
https://stackoverflow.com/questions/48410355
复制相似问题