需要从我的硬代码中创建一个循环

Need to make a loop out of my hard-code

本文关键字:循环 一个 创建 我的 代码      更新时间:2023-10-16

我正在编写一个迷宫算法代码,现在我已经硬编码了其中的一部分,但我需要将其更改为循环以实现可扩展性。有人可以帮我如何将它变成一个循环吗?

movement(x_3_vector.at(1),y_3_vector.at(1),x_4_vector.at(1),y_4_vector.at(1),"3");
movement(x_3_vector.at(2),y_3_vector.at(2),x_4_vector.at(2),y_4_vector.at(2),"3");
movement(x_3_vector.at(3),y_3_vector.at(3),x_4_vector.at(3),y_4_vector.at(3),"3");

 movement(x_3_vector.at(4),y_3_vector.at(4),x_4_vector.at(4),y_4_vector.at(4),"4");
 movement(x_3_vector.at(5),y_3_vector.at(5),x_4_vector.at(5),y_4_vector.at(5),"4");
 movement(x_3_vector.at(6),y_3_vector.at(6),x_4_vector.at(6),y_4_vector.at(6),"4");
 movement(x_3_vector.at(7),y_3_vector.at(7),x_4_vector.at(7),y_4_vector.at(7),"4");
 movement(x_3_vector.at(8),y_3_vector.at(8),x_4_vector.at(8),y_4_vector.at(8),"4");
 movement(x_3_vector.at(9),y_3_vector.at(9),x_4_vector.at(9),y_4_vector.at(9),"4");

 movement(x_3_vector.at(10),y_3_vector.at(10),x_4_vector.at(10),y_4_vector.at(10),"5");
 movement(x_3_vector.at(11),y_3_vector.at(11),x_4_vector.at(11),y_4_vector.at(11),"5");
 movement(x_3_vector.at(12),y_3_vector.at(12),x_4_vector.at(12),y_4_vector.at(12),"5");
 movement(x_3_vector.at(13),y_3_vector.at(13),x_4_vector.at(13),y_4_vector.at(13),"5");
 movement(x_3_vector.at(14),y_3_vector.at(14),x_4_vector.at(14),y_4_vector.at(14),"5");
 movement(x_3_vector.at(15),y_3_vector.at(15),x_4_vector.at(15),y_4_vector.at(15),"5");
 movement(x_3_vector.at(16),y_3_vector.at(16),x_4_vector.at(16),y_4_vector.at(16),"6");
 movement(x_3_vector.at(17),y_3_vector.at(17),x_4_vector.at(17),y_4_vector.at(17),"6");
 movement(x_3_vector.at(18),y_3_vector.at(18),x_4_vector.at(18),y_4_vector.at(18),"6");
 movement(x_3_vector.at(19),y_3_vector.at(19),x_4_vector.at(19),y_4_vector.at(19),"6");
 movement(x_3_vector.at(20),y_3_vector.at(20),x_4_vector.at(20),y_4_vector.at(20),"6");

问题是我需要根据我占据迷宫中的单元格数量来调用"移动"函数,所以有时我需要用字符串"3"调用运动函数 3 次,有时我需要用字符串"4"调用它 6 次......等等...

谢谢!

您当前带有循环的代码:

const char* s[20] = {
    "3", "3", "3",
    "4", "4", "4", "4", "4", "4",
    "5", "5", "5", "5", "5", "5",
    "6", "6", "6", "6", "6"
    };
for (int i = 0; i != 20; ++i) {
    movement(x_3_vector.at(1 + i),
             y_3_vector.at(1 + i),
             x_4_vector.at(1 + i),
             y_4_vector.at(1 + i),
             s[i]);
}
for (int i=1; i<=20; i++) {
     movement(x_3_vector.at(i),y_3_vector.at(i),x_4_vector.at(i),y_4_vector.at(i), getParam(i));
}
// TODO: improve this function in order to reflect what the string value must be at any time
string getParam(int index) {
    // TODO: make sure it's between 1-20 or whatever your constraints are
    if (index >= 16) return "6";
    else if (index >= 10) return "5";
    else if (index >= 4) return "4";
    else return "3";
}