gpt4 book ai didi

java - 确定变量中保存的值是否唯一

转载 作者:行者123 更新时间:2023-11-30 17:33:17 26 4
gpt4 key购买 nike

我正在尝试“暴力破解”一个数字谜题,其标准之一是计算仅使用 0-9 中的每个数字一次。我首先提取一堆变量的每个可能答案的各个数字(但将其更改为数组不会有什么大问题),但是确定它们是否唯一是一个麻烦事 - 看起来可能有很多 if语句条件: if a!=b && b!=c && a!=c;这会因为 10 个变量而变得冗长!

我错过了一个明显的技巧吗?我碰巧使用的是 C,但也可以使用 Java;绝不是这两方面的专家。

最佳答案

在 C 语言中,这是一种实现方法:

// use an array, not a bunch of separate variables
int the_numbers[NUM_NUMBERS];

// here we assume you have filled in the numbers and validated
// that they are all in the range 0-9

bool duplicate_found = false;

bool seen[10] = { 0 };

for (int ii = 0; ii < NUM_NUMBERS; ++ii)
if ( seen[ the_numbers[ii] ]++ )
{
duplicate_found = true;
break;
}

后缀-++是一种快捷的书写方式,如果它已经设置了,我们就想打破它;如果尚未设置,我们希望增加它(并且我们不关心在已经设置时是否也增加它。

关于java - 确定变量中保存的值是否唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com