Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m currently working on a Travelling salesman problem and i\'m having trouble

ID: 3727526 • Letter: I

Question

I'm currently working on a Travelling salesman problem and i'm having trouble generating random paths with the same start and end value

This is my current path(path of cities visited)

0 1 2 3 4 5 6 7 8 9 10 11 12 13 38 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 14 39 40 41 42 43 44 45 46 47 48 49 50 51 0

See how the last node arrives back at 0(TSP logic)

Now i'm trying to shuffle this array randomly because random start points generate better results then others However I know how to shuffle the array using Collections but that would shuffle every value randomly

TYPE JAVA CODE TO create a method to shuffle an array randomly WITH THE EXCEPTION THE START and END VALUES must be the same and every number must be distinct 0-51

Explanation / Answer

// Java Program to shuffle a given array
import java.util.Random;
import java.util.Arrays;
public class ShuffleRand
{
// A Function to generate a random permutation of arr[]
static void randomize( int arr[], int n)
{
// Creating a object for Random class
Random r = new Random();
System.out.println("%d",arr[0]);

// Start from the last element and swap one by one. We don't
// need to run for the first element that's why i > 0
for (int i = n-2; i > 1; i--) {

// Pick a random index from 1 to i
int j = r.nextInt(i);

// Swap arr[i] with the element at random index
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Prints the random array
System.out.println(Arrays.toString(arr));
System.out.println("%d",arr[n-1]);
}

// Driver Program to test above function
public static void main(String[] args)
{

int[] arr ={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,0};
int n = arr.length;
randomize (arr, n);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote