[英]Compact manner to check if array contains particular element
I currently have following code: 我目前有以下代码:
int[][] legalForBlack = {{0,1},{1,0},{2,3},{3,2}};
for (int x=0;x<boardSize;x++) {
for (int y=0;y<boardSize;y++) {
if (x,y) in legalForBlack
methodA()
else
methodB()
}
}
Of course this code won't compile. 当然,这些代码不会编译。 I am looking for a fancy and compact way to check when (x,y) are in the given list.
我正在寻找一种简便且紧凑的方法来检查(x,y)在给定列表中的时间。 I can do this with 4 if-statements or a loop, but this is not a proper way imo.
我可以使用4个if语句或循环来执行此操作,但这不是imo的正确方法。 I am looking for something that does this in constant time.
我正在寻找能够在恒定时间内做到这一点的东西。
EDIT: 编辑:
I think I found a way. 我想我找到了办法。 What do you think of this?
你觉得这怎么样?
int[][] legalForBlack = {{0,1},{1,0},{2,3},{3,2}}; // keep in order!
int cur = 0;
for (int x=0;x<boardSize;x++) {
for (int y=0;y<boardSize;y++) {
int[] buffer = legalForBlack[cur];
if (x==buffer[0] && y==buffer[1]) {
cur++;
methodA();
} else {
methodB();
}
}
}
Heres pseudocode for arrays: 这里是数组的伪代码:
input data in array
find x with for to match first column (legalForBlack[i][0])
if x matches legalForBlack[i][0] check if legalForBlack[i][1] matches y
if yes, count it
But there is a better way, when you just want to check if they are in array. 但是,当您只想检查它们是否在数组中时,有更好的方法。 Create object
Pair
with variable x
and y
, create equals()
and hashCode()
functions to have unique for each pair (like get hashCode
from string xy
), place all inputs in Set
and then check if given Pair(x,y)
is in Set
. 创建具有变量
x
和y
对象Pair
,创建equals()
和hashCode()
函数以使每个对具有唯一性(例如从string xy
获取hashCode
),将所有输入放入Set
,然后检查给定的Pair(x,y)
是否为在Set
。
boolean isLegal = false;
for(int[] coord: legalForBlack)
if(Arrays.equals(coord, someXYArray)) {
isLegal = true;
break; //Credit to Adnan Isajbegovic
}
if(isLegal)
methodA();
else
methodB();
I have an alternative solution for your question. 对于您的问题,我有替代的解决方案。 Judging from your code, I assume that you are writing something chess-related and your list of legalForBlack is a series of coordinates that the player is allowed to move to.
从您的代码来看,我假设您正在编写与国际象棋有关的东西,而legalForBlack列表是允许玩家移动的一系列坐标。 Best way IMO would be to code each square on the board with an index (0 to maximum 63) and store all of these in a Map of type <Integer, Coordinate>, where Coordinate has int x and int y.
IMO的最佳方法是在板上用索引(0到最大值63)编码每个正方形,并将所有这些正方形存储在<Integer,Coordinate>类型的Map中,其中Coordinate具有int x和int y。 If you don't have any particular use for the coordinates, you can also skip and convert your Map to a simple Array of allowed-squares.
如果坐标没有任何特殊用途,还可以跳过地图并将其转换为简单的允许正方形数组。 This would only require you to check whether a given value is in your allowed-square list.
这仅需要您检查给定值是否在允许的平方列表中。 I hope this gives you a better approach to your problem.
我希望这可以为您解决问题提供更好的方法。 Good luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.