如何根据另一个数组的顺序洗牌数组列表



我试图通过结合两种算法返回最佳路径来解决旅行推销员问题

第一个算法使用环境数组列表生成最佳路径

第二个算法将优化第一个算法获得的路径,但在这样做时,我需要创建一个新的ArrayList,它是环境ArrayList的洗牌,以匹配最佳路径数组

的顺序你能帮我做这个吗,因为我在洗牌环境时遇到了麻烦

是环境数组列表,其中每个节点由名称,x行,y行组成:

static ArrayList<Node> environment = new ArrayList<Node>(Arrays.asList(
new Node("1", 19, -121),
new Node("2", 343, -132),
new Node("3", 21, -132),
new Node("4", 47, -122),
new Node("5", 35, -139),
new Node("6", -54, 165),
new Node("7", -45, 21),
new Node("8", 89, -65),
new Node("9", 58, -72),
new Node("10", 21, -54)
));

最佳路径数组返回:[10, 4, 3, 7, 9, 2, 1, 5, 8, 6]

将数组列表设置为静态也会使它在洗牌时产生问题,因为来自python,它仍然相对较新。

谢谢你的帮助

因为您将ArrayList定义为静态的,一旦您有了最佳路径并对其应用shuffle,它将从最佳路径步骤中删除信息。

你可以克隆另一个数组一旦你得到数组排序和洗牌这个数组列表,这将保持信息在environmentshuffleenvironment的新拷贝


public class Program {

static ArrayList<Node> environment = new ArrayList<Node>(Arrays.asList(
new Node("1", 19, -121),
new Node("2", 343, -132),
new Node("3", 21, -132),
new Node("4", 47, -122),
new Node("5", 35, -139),
new Node("6", -54, 165),
new Node("7", -45, 21),
new Node("8", 89, -65),
new Node("9", 58, -72),
new Node("10", 21, -54)
));
static ArrayList<Node> shuffle;
public static void main(String[] args) {
// Once get best path
shuffle = environment.clone();
// continue your logic
}

}

您可以使用以下方法对ArrayList对象进行洗牌

Collections.shuffle(list);

将数组列表设置为静态也会使它在从python迁移时产生问题,它仍然相对较新。

不,static是表示class属性的关键字,对于该类的所有对象,它的值都是静态的。并且可以使用类引用访问,但是非静态属性只能通过类对象访问

class MyClass{
static List<String> staticList = List.of("HI", "Hello");
List<String> nonStaticList = new ArrayList<>();
}
public static void main(String[] args){
System.out.println(MyClass.staticList .get(1)); // no errors
//System.out.println(MyClass.list.get(5)); // error

Myclass myObject = new MyClass();
System.out.println(myObject.nonStaticList)  // no errors
System.out.println(myObject.staticList .get(1)); // no errors
}