Sorting array of names alphabetically using compareTo() - java

I am trying to sort an array of names alphabetically by using compareTo() and a method String addSort(String name) but I get an error when compiling at the line "return name", saying that my "variable "name" may not be initialized" when it already is.
I've made the method and the code for sorting alphabetically which I think should be correct when using compareTo() as a way of sorting the array. (The array "moreFriends" is a new array which doubles the size of the original array "friends" when it gets full) (Note this is not all of the code)
public class SimpleDataStructure{
private String [] friends;
private String [] moreFriends;
private int counter;
public SimpleDataStructure()
{
friends= new String[5];
counter=0;
}
public String addSort(){
String name;
for(int i = 0; i < moreFriends.length; i++){
for(int j = i + 1; j < moreFriends.length; j++){
if(moreFriends[i].compareTo(moreFriends[j]) > 0){
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
System.out.println("Names in sorted order:");
for(int i = 0; i < moreFriends.length -1; i++){
System.out.println(moreFriends[i]);
}
return name;
}
public static void main( String [] arg){
SimpleDataStructure sortedfriends = new SimpleDataStructure();
System.out.println(sortedfriends.addSort(name));
}
This is the error message I get when i try to compile the program:
SimpleDataStructure.java:85: error: variable name might not have been initialized
return name;
^
1 error
When I expect the output to eventually be:
(unsorted)
Kalle
Bob
Carl
Alice
Lewis
(sorted)
Alice
Bob
Carl
Kalle
Lewis

You need declare youre function like this:
public String addSort(String name){
and delete the string declaration:
String name;
and you don't put value for name.
You can solved your problem using this:
String [] a="a","v","b";
Arrays.sort(a);

The reason that you are getting the compile error is because you never set a value to the String name before trying to use it.
You should be passing in the value like you have in your description addSort(String name). This will remove that error.
I do not see a reason why you are returning the String in your function.
This function does not appear to add the passed in name either.

Hope this helps!
import java.util.*;
class SimpleDataStructure {
public String[] addSort(String moreFriends []) {
for (int i = 0; i < moreFriends.length; i++) {
for (int j = i + 1; j < moreFriends.length; j++) {
if (moreFriends[i].compareTo(moreFriends[j]) > 0) {
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
return moreFriends;
}
public static void main(String[] arg) {
Scanner input=new Scanner(System.in);
SimpleDataStructure sortedFriends = new SimpleDataStructure();
String [] name =new String[5];
System.out.println("Enter name(s): ");
for (int i = 0; i < name.length; i++) {
name[i]=input.nextLine();
}
System.out.println("Unsorted:");
System.out.println(Arrays.toString(name));
System.out.println("Sorted:");
System.out.println(Arrays.toString(sortedFriends.addSort(name)));
}
}
And if you want the names to print out line by line, just create a for loop instead of Arrays.toString
Or you could even use Arrays.sort , which is much simpler
import java.util.Arrays;
class SimpleDataStructure {
public String[] addSort(String moreFriends []) {
for (int i = 0; i < moreFriends.length; i++)
Arrays.sort(moreFriends);
return moreFriends;
}
public static void main(String[] arg) {
SimpleDataStructure sortedFriends = new SimpleDataStructure();
String [] name ={"Kalle", "Bob","Carl","Alice", "Lewis"};
System.out.println("Unsorted:");
System.out.println(Arrays.toString(name));
System.out.println("Sorted:");
System.out.println(Arrays.toString(sortedFriends.addSort(name)));
}
}

I changed my arrays "friends" and "moreFriends" to static in my class.
Now my code looks something like this when im calling my method in my main:
SimpleDataStructure sorted = new SimpleDataStructure();
System.out.println("Sorted:");
System.out.println(Arrays.toString(sorted.addSort()));
And this is my method:
public String[] addSort() {
for (int i = 0; i < moreFriends.length; i++) {
for (int j = i + 1; j < moreFriends.length; j++) {
if (moreFriends[i].compareTo(moreFriends[j]) > 0) {
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
return moreFriends;
}
However i get this error message now:
Unsorted:
Kalle Bob Carl Alice Lewis
Sorted:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at SimpleDataStructure.addSort(SimpleDataStructure.java:75)
at SimpleDataStructure.main(SimpleDataStructure.java:108)

You need to include your variable name, that holds the names, inside addSort
SimpleDataStructure sorted = new SimpleDataStructure();
System.out.println("Sorted:");
System.out.println(Arrays.toString(sorted.addSort(**HERE**)));

Related

Java - Problem at sorting array list using bubblesort

I have a problem at the moment I have a college assignment and we need to list a file that contain books and should be sorted A to Z,
My sort algorithm is a bubble sort and at the moment is not sorting alphabetically but don't give errors, I cant see where I should change to make it work as the coding seems correct to me.
We are not allowed to use collections so that is the reason I am not using sort().
package Book;
public class AlphabeticalOrderTitle{
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
public static void main(String[] args)
{
ArrayList<Book> books = BubbleSort();
System.out.println(linearSearch(books));
}
public static ArrayList<Book> loadData() {
//Creating an array list;
ArrayList<Book> books = new ArrayList<>();
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.txt"));
//This header string will allow to skip the header so does not mismatch with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
return books;
}
public static int linearSearch(ArrayList<Book> array){
//Variables for holding values
int n;
String temp;
// Going one by one the elements in the array
for(int g = 0; g < array.size(); g++){
//Getting the array size from the file and giving the array name a size
n = array.size();
String names[] = new String[n];
//Load all the names
for(int i = 0; i < n; i++) {
names[i] = array.get(g).getBookTitle();
}
//Bubble sort starts
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
//Print sorted
System.out.println(names[n-1]);
}
return -1;
}
}
Outpout:
Captains
Romeo
Don
-1
and what I am aiming is Captains, Don, Romeo.
My book.txt contains is like this:
book
Any suggestion for me to fix it ? Thank you very much.
Bubble Sort Example
I linked a bubble sort example. You can click on Java to see a version in Java. And you can see there are differences between yours and theirs, even though they are very similar.
What I would do is do it manually. That is, grab some paper, write down what your array looks like then actually pretend you're the computer and see what you end up with. It will be a good exercise for you, and you'll probably figure out what you're doing wrong.
First of all, BubbleSort() is not an appropriate name for this method as all it does is reading the file and storing the content inside the list.
If this course is not an upper-level algorithms class, you could probably use java libraries to sort your list instead.
Something like this should work and produce the needed result:
Collections.sort(books);
Also, I usually just do the following:
List books = new ArrayList<>();
In case you have to implement bubble sort, please use the following link which shows how to use bubble sort to sort string arrays: https://www.geeksforgeeks.org/sorting-strings-using-bubble-sort-2/
For array A of 'n' elements A[n], then the first loop in bubble sort always ends with n-1.
The idea of bubble sort is to compare the adjacent elements and then swap if the are not in order (increasing / decreasing depending on the use case).
So, when i=n-1, as you mentioned in your first for loop=>j=n-1. We are basically comparing A[i=n-1] to A[j=n-1].
//Bubble sort starts
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
you can try a quick dry-run whenever you are stuck in such problems by substituting with small numbers and writing the loop content on paper. Helps a lot to learn and to build logic. :)
So after a couple days working on it I have come with a working solution thanks to everyone.
public class Alphabetical_Order {
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
//Creating an array list;
public static ArrayList<Book> books = new ArrayList<>();
public static void main(String[] args)
{
loadData();
int n = 0;
String temp;
//Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
//get size of arraylist
for (int g = 0; g < books.size(); g ++) {
n = books.size();
}
String names[] = new String[n];
//Names to be get from user
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = books.get(i).getAuthorName();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
public static void loadData() {
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.csv"));
//This header string will allow to store the header so does not mistach with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
}}

Java - Need help in finding the shortest string of an array, i'm close from what i see but i'm getting an error,

Here is the code:
class big
{
public static int findSum(String[] args)
{
int i = 0;
int sumArgs = 0;
for (i = 0; i <= args.length - 1; i++) {
System.out.println(args[i] + " " + args[i].length());
sumArgs = sumArgs + args[i].length();
}
return sumArgs;
}
public static void main(String[] args)
{
int[] coolArray = makeInputCopy(args);
int smallest = findShortest(coolArray);
int largest = findLargest(coolArray);
int sumArgs = findSum(args);
System.out.println(sumArgs);
System.out.println("Smallest Number present: " + smallest);
System.out.println("Largest Number present: " + largest);
}
public static String findShortest(String[] array) {
String shortestSeen = "";
for (int i = 0; i < array.length; i++) {
if(array[i].length() < shortestSeen.length()) {
shortestSeen = array[i];
}
}
return shortestSeen;
}
public static int findLargest(int[] array) {
int largestSeen = 0;
for (int i = 0; i > array.length; i++) {
if(array[i] > largestSeen) {
largestSeen = array[i];
}
}
return largestSeen;
}
public static int[] makeInputCopy(String[] input) {
int[] output = new int[input.length];
for (int i = 0; i < output.length; i++) {
}
return output;
}
}
The program was originally intended to scan an input array for strings, list the amount of characters in each word then add the sum of all characters, I'm trying to find the shortest and longest out of this array.
However, when I invoke the method findShortest(coolArray) I'm receiving an error in regards to converting a int to string incapability, i can't wrap my head around why.
If this could be explained I'd greatly appreciate it.
int smallest = findShortest(coolArray);
public static String findShortest(String[] array) {
...
You're assigning a String (result of findShortest) to an int (smallest). This can't compile.
You would probably be gettting
Main.java:21: error: incompatible types: int[] cannot be converted to String[]
int smallest = findShortest(coolArray);
^
This is due to int smallest = findShortest(coolArray);You are assigning string to int which is incompatible.
int[] coolArray = makeInputCopy(args);
int smallest = findShortest(coolArray);
// ...
public static String findShortest(String[] array) {
// ...
Two problems with the above:
coolArray is of type int[], but findShortest expects a String[]
smallest is of type int, but findShortest returns a String
The fix seems easy enough:
String smallest = findShortest(args);
However, findShortest also has a bug:
public static String findShortest(String[] array) {
String shortestSeen = "";
for (int i = 0; i < array.length; i++) {
if (array[i].length() < shortestSeen.length()) {
shortestSeen = array[i];
}
}
return shortestSeen;
}
Nothing will ever be shorter than an empty string. So this will always return an empty string.
To fix that, you could either set shortestSeen to something obscenely long, or you could track the shortest length in a separate variable, initialized to something very large, like this:
public static String findShortest(String[] array) {
String shortestSeen = "";
int shortestLength = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if(array[i].length() < shortestLength) {
shortestSeen = array[i];
shortestLength = shortestSeen.length();
}
}
return shortestSeen;
}
Your definition of findShortest() calls for an array of Strings; however, you're passing in an array of integers. This is causing your problem.
Well, from the above answers it seems to be a pretty easy fix . However I did a quick and dirty write of a snippet for finding the shortest in an Array of Strings as well, here's the code :
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Shortest {
public static void main(String[] args) {
String[] shortest = { "asd", "abc", "defdfdf", "cy" };
Map<Integer, String> lengthToString = new HashMap();
for (String s : shortest) {
lengthToString.put(s.length(), s);
}
System.out.println(lengthToString.get(Collections.min(lengthToString.keySet())));
}
}
This could be of some use since I've tried to use Utility class methods instead of trying to reinvent the wheel. If there are two strings with the same length however, it will only print one of them.
public static String findShortest(String[] array) {
String shortestSeen = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i].length() < array[0].length()) {
shortestSeen = array[i];
}
}
return shortestSeen;
}
you have to initialize shortestseen with array[0] and you have to make this test array[i].length() < array[0].length() i see another error in findLargest in for loop : array[i] > largestSeen

Adding 3 string into 3 variable

My Account class have 3 variable to store name, id and password
and my method addAcount() get 3 parameter and pass all into the 3 variable.
The problem is i cant pass the 3 parameter item into the 3 variable.
my 3 variable declaration :
private String[] id = new String[100];
private String[] pass = new String[100];
private String[] name = new String[100];
here's my method:
public void addAccount(String id, String pass, String name){
for(int i=0; i < this.id.length;i++){
if(this.id[i]==null){
this.id[i]=id;
for(int a = 0; a <this.pass.length;a++){
if(this.pass[a]==null){
this.pass[a]=pass;
for(int b=0;b<this.name.length;b++){
if(this.name[b]==null){
this.name[b]=name;
break;
}
}
}
}
}
}
Any Help will be Appreciated
To access all elements
Your method header shoud be :-
public void addAccount(String[] id, String[] pass, String[] name){
//your code here
// By looping over array you can get the strings in it
for(int i = 0 ; i < id.length ; i++){
String str_id = id[i];
}
}
And to call it :-
addAccount(id,pass,name);
To access specific string at specific position :-
String str_pass = pass[5];//by his you will get the 6th element(zero base indexing )
But be aware if you direct access the array if the index you use greater than array.length you will get array out of boundary exception
In this situation you can use this:
public void addAccount(String id, String pass, String name)
{
//These for loops look up the first empty spot in the array and
//insert the chosen parameter in that spot once
//Add ID to array
for (int i = 0; i < this.id.length; i++)
{
if (this.id[i] == null)
{
this.id[i] = id;
i = this.id.length;
}
}
//Add Pass to array
for (int a = 0; a < this.pass.length; a++)
{
if (this.pass[a] == null)
{
this.pass[a] = pass;
a = this.pass.length;
}
}
// Add name to array
for (int b = 0; b < this.name.length; b++)
{
if (this.name[b] == null)
{
this.name[b] = name;
b = this.name.length;
}
}
}
Edit: changed the code so the array length won't matter

How to print the string without duplicate?

I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two

Smart way to generate permutation and combination of String

String database[] = {'a', 'b', 'c'};
I would like to generate the following strings sequence, based on given database.
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
...
I can only think of a pretty "dummy" solution.
public class JavaApplication21 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
String query = "a";
StringBuilder query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
query = query_sb.toString();
System.out.println(query);
}
query = "aa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
query = query_sb.toString();
System.out.println(query);
}
}
query = "aaa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
for (int c = 0; c < database.length; c++) {
query_sb.setCharAt(2, database[c]);
query = query_sb.toString();
System.out.println(query);
}
}
}
}
}
The solution is pretty dumb. It is not scale-able in the sense that
What if I increase the size of database?
What if my final targeted print String length need to be N?
Is there any smart code, which can generate scale-able permutation and combination string in a really smart way?
You should check this answer: Getting every possible permutation of a string or combination including repeated characters in Java
To get this code:
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else {
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++){
for(int j = 0; j < allSublists.length; j++){
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}
public static void main(String[] args){
String[] database = {"a","b","c"};
for(int i=1; i<=database.length; i++){
String[] result = getAllLists(database, i);
for(int j=0; j<result.length; j++){
System.out.println(result[j]);
}
}
}
Although further improvement in memory could be made, since this solution generates all solution to memory first (the array), before we can print it. But the idea is the same, which is to use recursive algorithm.
This smells like counting in binary:
001
010
011
100
101
...
My first instinct would be to use a binary counter as a "bitmap" of characters to generate those the possible values. However, there are several wonderful answer to related questions here that suggest using recursion. See
How do I make this combinations/permutations method recursive?
Find out all combinations and permutations - Java
java string permutations and combinations lookup
http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/
Java implementation of your permutation generator:-
public class Permutations {
public static void permGen(char[] s,int i,int k,char[] buff) {
if(i<k) {
for(int j=0;j<s.length;j++) {
buff[i] = s[j];
permGen(s,i+1,k,buff);
}
}
else {
System.out.println(String.valueOf(buff));
}
}
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
char[] buff = new char[database.length];
int k = database.length;
for(int i=1;i<=k;i++) {
permGen(database,0,i,buff);
}
}
}
Ok, so the best solution to permutations is recursion. Say you had n different letters in the string. That would produce n sub problems, one for each set of permutations starting with each unique letter. Create a method permutationsWithPrefix(String thePrefix, String theString) which will solve these individual problems. Create another method listPermutations(String theString) a implementation would be something like
void permutationsWithPrefix(String thePrefix, String theString) {
if ( !theString.length ) println(thePrefix + theString);
for(int i = 0; i < theString.length; i ++ ) {
char c = theString.charAt(i);
String workingOn = theString.subString(0, i) + theString.subString(i+1);
permutationsWithPrefix(prefix + c, workingOn);
}
}
void listPermutations(String theString) {
permutationsWithPrefix("", theString);
}
i came across this question as one of the interview question. Following is the solution that i have implemented for this problem using recursion.
public class PasswordCracker {
private List<String> doComputations(String inputString) {
List<String> totalList = new ArrayList<String>();
for (int i = 1; i <= inputString.length(); i++) {
totalList.addAll(getCombinationsPerLength(inputString, i));
}
return totalList;
}
private ArrayList<String> getCombinationsPerLength(
String inputString, int i) {
ArrayList<String> combinations = new ArrayList<String>();
if (i == 1) {
char [] charArray = inputString.toCharArray();
for (int j = 0; j < charArray.length; j++) {
combinations.add(((Character)charArray[j]).toString());
}
return combinations;
}
for (int j = 0; j < inputString.length(); j++) {
ArrayList<String> combs = getCombinationsPerLength(inputString, i-1);
for (String string : combs) {
combinations.add(inputString.charAt(j) + string);
}
}
return combinations;
}
public static void main(String args[]) {
String testString = "abc";
PasswordCracker crackerTest = new PasswordCracker();
System.out.println(crackerTest.doComputations(testString));
}
}
For anyone looking for non-recursive options, here is a sample for numeric permutations (can easily be adapted to char. numberOfAgents is the number of columns and the set of numbers is 0 to numberOfActions:
int numberOfAgents=5;
int numberOfActions = 8;
byte[][]combinations = new byte[(int)Math.pow(numberOfActions,numberOfAgents)][numberOfAgents];
// do each column separately
for (byte j = 0; j < numberOfAgents; j++) {
// for this column, repeat each option in the set 'reps' times
int reps = (int) Math.pow(numberOfActions, j);
// for each column, repeat the whole set of options until we reach the end
int counter=0;
while(counter<combinations.length) {
// for each option
for (byte i = 0; i < numberOfActions; i++) {
// save each option 'reps' times
for (int k = 0; k < reps; k++)
combinations[counter + i * reps + k][j] = i;
}
// increase counter by 'reps' times amount of actions
counter+=reps*numberOfActions;
}
}
// print
for(byte[] setOfActions : combinations) {
for (byte b : setOfActions)
System.out.print(b);
System.out.println();
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
import java.util.*;
public class Permutation {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("ENTER A STRING");
Set<String> se=find(in.nextLine());
System.out.println((se));
}
public static Set<String> find(String s)
{
Set<String> ss=new HashSet<String>();
if(s==null)
{
return null;
}
if(s.length()==0)
{
ss.add("");
}
else
{
char c=s.charAt(0);
String st=s.substring(1);
Set<String> qq=find(st);
for(String str:qq)
{
for(int i=0;i<=str.length();i++)
{
ss.add(comb(str,c,i));
}
}
}
return ss;
}
public static String comb(String s,char c,int i)
{
String start=s.substring(0,i);
String end=s.substring(i);
return start+c+end;
}
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!

Categories

Resources