I dont understand how to swap 2 random strings in LinkedList I know how to swap integers but strings are too diferent
`
import java.util.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LinkedList<String> ll = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("enter total count of elements -> ");
int num = Integer.parseInt(sc.next());
while(num>0) {
ll.add(sc.next());
num--;
}
sc.close();
System.out.println(ll);
}
}
`
CodePudding user response:
Just another way. Read comments in code:
LinkedList<String> ll = new LinkedList<>(Arrays.asList(
"Billy", "Tracey", "Fred", "Jack", "Joe", "Carlie"));
System.out.println("Original LinkedList contents:");
System.out.println(ll); // Display original List
System.out.println();
// Get a random index number
int swapFrom = new Random().nextInt(ll.size());
// Ensure the next random index number is different.
int swapTo = swapFrom;
while (swapTo == swapFrom) {
swapTo = new Random().nextInt(ll.size());
}
System.out.println("Swap content at index " swapFrom
" of LinkedList with content at index " swapTo ":");
String tmp = ll.get(swapTo); // Temporarily hold content at index swapTo.
ll.set(swapTo, ll.get(swapFrom)); // Place what is at index swapFrom and overwrite what is at index swapTo.
ll.set(swapFrom, tmp); // Overwrite what is at index swapfrom with what is in tmp.
System.out.println(ll); // Display List with swapped elements.
System.out.println();
CodePudding user response:
There's a chance that no swap will occur with this but this is a possibility:
public static <T> void swapTwo(List<T> list) {
int len = list.size();
int ixOne = (int)(Math.random() * len);
int ixTwo = (int)(Math.random() * len);
Collections.swap(list, ixOne, ixTwo);
}