Reputation: 23
Original Array
Array[]={"Car","Truck","Boat"};
Shuffled Array
Array[]={"Truck","Boat","Car"};
Dont want it Semi-Shuffled
like
Array[]={"Truck","Car","Boat"};
where Car and Truck are swapped but not Boat.
I read this is called Derangement of an array but I cant find one that helps with Strings.
Upvotes: 1
Views: 112
Reputation: 174
String[] arr = { "Car", "Truck", "Boat" };
Arrays.sort(arr);
for (int i = 0; i <= arr.length - 1; i++) {
System.out.println(arr[i]);
}
Upvotes: 1
Reputation: 3807
Here's one solution to generate derangement of an array the with O(n)
time and O(1)
space complexity.
String[] strArray = { "Truck", "Car", "Boat" };
String temp = strArray[0];
for (int i = 0; i < strArray.length - 1; i++) {
strArray[i] = strArray[i + 1];
}
strArray[strArray.length - 1] = temp;
Arrays.stream(strArray).forEach((e) -> System.out.print(e + " "));
I just shifted every element to its left.
And here's the output:
Car Boat Truck
Upvotes: 1