In: Computer Science
Using java, create a class called MyString that has one String
called word as its attribute and the following methods:
Constructor that accepts a String argument and sets the
attribute.
Method permute that returns a permuted version of word. For this method, exchange random pairs of letters in the String. To get a good permutation, if the length of the String is n, then perform 2n swaps.
Use this in an application called Jumble that prompts the user
for a word and the required number of jumbled versions and prints
the jumbled words. For example,
Enter the word: mixed
Enter the number of jumbled versions required: 10
xdmei eidmx miexd emdxi idexm demix xdemi ixdme eximd xemdi xdeim
Notes:
1. It is tricky to swap two characters in a String. One way to
accomplish this is to convert your String into an array of
characters, swapping the characters in the array, converting it
back to a String and returning it.
char[] chars = word.toCharArray(); will convert a String word to a
char array chars.
String result = new String(chars); converts a char array chars into
a String.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
//MyString.java class
public class MyString {
// word
private String word;
// constructor accepting a word
public MyString(String word) {
this.word = word;
}
// method that returns a random permutation
public String permute() {
// converting word to array
char arr[] = word.toCharArray();
// looping for arr.length/2 number of times
for (int i = 0; i < arr.length / 2; i++) {
// generating two random indices between 0 and arr.length-1
int randIndex1 = (int) (Math.random() * arr.length);
int randIndex2 = (int) (Math.random() * arr.length);
// swapping elements at these indices
char c = arr[randIndex1];
arr[randIndex1] = arr[randIndex2];
arr[randIndex2] = c;
}
//converting array back to String and returning it
return new String(arr);
}
}
//Jumble.java file
import java.util.Scanner;
public class Jumble {
public static void main(String[] args) {
// setting up a Scanner
Scanner scanner = new Scanner(System.in);
// asking and reading word
System.out.print("Enter the word: ");
String word = scanner.next();
// creating a MyString object using word
MyString myString = new MyString(word);
// asking and reading an integer
System.out.print("Enter the number of jumbled versions required: ");
int n = scanner.nextInt();
// looping for n times
for (int i = 0; i < n; i++) {
// finding a permutation and printing it
System.out.println(myString.permute());
}
}
}
/*OUTPUT*/
Enter the word: amazing
Enter the number of jumbled versions required: 10
mganiza
amziagn
amiznag
ngazaim
anazigm
gmaznai
imanagz
azanimg
aiazmng
zmagani