In: Computer Science
Project:
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the i th position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example: Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output: "leetcode" Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
You need to do: Create a class called ShuffledStringApp. Keeping class StringOperation and IO in util package. In this project, you will need 3 methods:
1. Public static boolean validateInput(String s, int[] indices) --- inside ShuffledStringApp class, Check if the input string is not empty and the length of input array is the same length as the string, there are no duplicated numbers in the array, and the max number should not be greater than the length.
2. Public static String shuffle(String s, int[] indices) --- inside ShuffledStringApp class, process the string s.
3. Public static void main(string[] args) --- Prompt user to input a word and array. Call validateInput method for validation (If the input is not validate, repeat for user input) and shuffle method for shuffle the string. Print out the result.
Code:
import java.util.*;
public class ShuffledStringApp
{
public static boolean validateInput(String s,int[] indices){
//if Sting is empty or array length not equal to string length
return false
if(s.length() == 0 && s.length()!=indices.length){
return false;
}
else{
for(int i=0;i<s.length();i++)
{
boolean isPresent=false;
//check if every index from 0 to lengh-1 is present or not
for(int j=0;j<indices.length;j++)
{
if(indices[j]==i)
{
isPresent=true;
break;
}
}
if(isPresent==false)
return false;
}
}
return true;
}
public static String shuffle(String s,int[] indices){
char res[] = new char[indices.length];
String result="";
for(int i=0;i<indices.length;i++)
res[indices[i]]=s.charAt(i);
for(int i=0;i<indices.length;i++)
result = result + res[i];
return result;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
boolean validinput=false;
String s="";
int[] indices={0};
while(validinput==false)
{
System.out.println("\nEnter String:");
s=sc.next();
System.out.println("\nEnter indices values:");
indices=new int[s.length()];
for(int i=0;i<s.length();i++)
indices[i]=sc.nextInt();
validinput=validateInput(s,indices);
if(validinput==false)
System.out.println("\nInvalid input Enter again");
}
System.out.println("Shuffled String is "+
shuffle(s,indices));
}
}
Output: