我会尽力解释我的问题。我正在尝试在 PHP 中创建一个国际象棋引擎(只是为了好玩 :-))代码中的整数只是返回有效的移动(为简单起见 - 在实际代码中它是对象和移动模式取决于它是关于哪一块的)
我正在寻找一种有效搜索数组的方法。有效地我的意思是尽可能快。看看我在下面代码中的评论“是否可以在不遍历所有 1000 个值的情况下跳出循环?” 我希望评论能解释我想要达到的目标。我只是在寻找优化以下代码的想法,而不是完整的代码:-)
//This is for demonstrating
//1000 values to go through
$moves_maybe_valid = range(1,1000);
shuffle($moves_maybe_valid);
//Go through possible values
$move_checked = [];
$nr=0;
foreach($moves_maybe_valid as $mmv) {
$move_is_valid = check_move($mmv);
//Check if not in checked array
if ($move_is_valid === false && !in_array($mmv, $move_checked)) {
//Add to checked move array
$move_checked[] = $mmv;
}
//IS it possible to break out of loop without
//going through all 1000 values?
//When all valid moves are true I want to break here
//but I don't know when that is.
}
//for demonstration purpose only
//numbers (5,6) that returns true are unknown until an
//an actual check is done in this function
function check_move($nr) {
if ($nr == 5 || $nr == 6) {
return true;
}
return false;
}
如果我说我会从一开始就生成有效的移动(基于下面的评论)
$valid_moves = [5,6];
跳出循环的最佳方法是什么?
慕雪6442864