[英]Are too many if , else-if statements wrong?
I have to do a program that's simulating the move of an ant in a 5x5 grid map,of cells.我必须做一个程序来模拟 ant 在单元格的 5x5 网格 map 中的移动。 Imagine an 5x5 array in which, in position (2,2) and (3,3) there is food for ants to collect.
想象一个 5x5 阵列,其中 position (2,2) 和 (3,3) 中有供蚂蚁收集的食物。 Every ant starts moving from its nest which is in a specific cell (1,4 or 4,1).
每个 ant 都从位于特定单元格(1,4 或 4,1)中的巢穴开始移动。 There is a method called move() that i have to write,which moves the ant one cell in each call.
我必须编写一个名为 move() 的方法,它在每次调用中将 ant 移动一个单元格。 The move can either be horizontal or vertical.
移动可以是水平的或垂直的。 Also the ant cant move to his last position (to avoid going back and forth).
ant 也不能移动到他的最后一个 position (以避免来回走动)。 Also each cell has 'smell points' and the ant prefers to go in the cell with the biggest points(so you compare its available options and pick the one with the biggest smell points,simple right?).
此外,每个单元格都有“气味点”,ant 更喜欢 go 单元格中的最大点(所以你比较它的可用选项并选择气味点最大的那个,简单吧?)。 Now, the problem.
现在,问题。 They want the ant to make completely random moves incase the cell has no smell points or the smell points of the available cells are equal.
他们希望 ant 进行完全随机的移动,以防单元格没有气味点或可用单元格的气味点相等。 So to sum it up:
所以总结一下:
// int pos[] = new int[2]; in the pos[0] is the position for the x, pos[1] for the y.
if(isAt(1,1))
{
if(wasAt(pos[0]+1,pos[1]))
{
previousX = pos[0];
previousY = pos[1];
pos[1] = pos[1] + 1;
}
else
{
previousX = pos[0];
previousY = pos[1];
pos[0] = pos[0] + 1;
}
}
This does sound like too many if
statements.这听起来确实像太多的
if
语句。 Here are some suggestions:以下是一些建议:
You should remember where the ant is in a variable.您应该记住 ant 在变量中的位置。 I don't think you need any if statements to check which cell the ant is in.
我认为您不需要任何 if 语句来检查 ant 所在的单元格。
You should remember where the ant was last in a different variable.您应该记住 ant 最后在不同变量中的位置。
You should make a list of the surrounding points and their smell points.您应该列出周围的点及其气味点。 Then remove from this list the ants previous location.
然后从此列表中删除蚂蚁以前的位置。
Using the above collection, you can loop through to pick the right one or if there is more than one choose one at random from the collection.使用上面的集合,您可以循环选择正确的一个,或者如果有多个从集合中随机选择一个。
When you move the ant, set the previous location to the current location and then update the current location.移动 ant 时,将之前的位置设置为当前位置,然后更新当前位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.