H.imam1994
H.imam1994

Reputation: 23

Shuffle an array of strings so that the sting must be completely shuffled and not in its original index in Java

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

Answers (2)

Rohit Aggarwal
Rohit Aggarwal

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

Shanu Gupta
Shanu Gupta

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

Related Questions