I am trying to solve the travelling salesman problem by combining two algorithms to return the best path
The first algorithm uses the environment ArrayList to produce the best path
The second algorithm will optimize the route obtained by the first, but in doing so, I need to create a new ArrayList which is the environment ArrayList shuffled to match the order of the best path array
please can you help me to do this as I'm having trouble shuffling the environment ArrayList
here is the environment ArrayList where each node consists of name, x cords, y cords:
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)
));
Best path Array returned: [10, 4, 3, 7, 9, 2, 1, 5, 8, 6]
also does setting the Array-list as static make it an issue when shuffling as coming from python its still relatively new.
Thank your for your help
CodePudding user response:
you can use the following method to shuffle the ArrayList object
Collections.shuffle(list);
also does setting the Array-list as static make it an issue when shuffling as coming from python its still relatively new.
No, static
is a keyword to represent a property of a class
, and it's value is static for all objects of this class,
and can be accessed using the class refrence, but non static properties can accessed only via class objects
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
}
CodePudding user response:
Because you define the ArrayList as static once you have the best path and apply the shuffle on it will erase the information from the best path step.
You can clone another array once you get the array sorted and shuffle this array list, this will keep the information in environment
and shuffle
new copy from the environment
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
}
}