I am having trouble figuring out the programming logic.How do you get the array of strings to print asteriks at random indexes. Note that the 3 is the number of asterisk to be generated in the array.
so the output can be [a,b*,c*,d,e*,f,g,h] or [a*,b,c,d,e,f,g*,h*]
public class Generate
{
public static void main(String[] args)
{
String[] list = {"a","b","c","d","e","f","g","h"};
for(int i =0; i <list.length; i++)
{
System.out.print(" " + list[i]);
generateAsterisk(list);
}
System.out.println();
}
public static void generateAsterisk(String[] list)
{
for(int i = 0; i < 3; i++)
{
int index = (int)(Math.random()*i);
}
System.out.print("*");
}
}
You can do it like that:
import java.util.Random;
public class Generate {
public static void main(String[] args) {
String[] list = { "a", "b", "c", "d", "e", "f", "g", "h" };
//do it 3 times or change to as many times you want to add an asteriks
for (int i = 0; i < 3; i++) {
addRandomAsteriks(list);
}
//print the array
for (int i = 0; i < list.length; i++) {
System.out.print(" " + list[i]);
}
System.out.println();
}
public static void addRandomAsteriks(String[] list) {
Random rand = new Random();
int randomNumber = rand.nextInt(list.length - 1);
String string = list[randomNumber]; //get the string at the random index
if (!string.contains("*")) {
// add the asteriks
list[randomNumber] = string.concat("*");
}else {
//if it had already an asteriks go through the
//add-method again until you find one that has no asteriks yet.
addRandomAsteriks(list);
}
}
This is a more object oriented point of view than YassinHH's answer.
This solution works and has only arrays in use.
You can call the generateAsteriks method only once, with the number of asteriks you want:
String[] list = {"a","b","c","d","e","f","g","h"};
generateAsterisks(list, 3);
...
And change your generateAsteriks method to this:
public static void generateAsterisks(String[] list, int numAsteriks)
{
for(int i = 0; i < numAsteriks && i < list.length; i++)
{
int index = (int)(Math.random()*list.length);
//check if already added *
if(list[index].lastIndexOf('*') != list[index].length()-1) {
list[index] = list[index] + "*";
} else {
//don't count this loop iteration
i--;
}
}
}
Related
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String[] args) {
String s="aabcddkkbghff";
String[] cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String[] args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int[] count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String [] str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"\t"+count);
}
}
public static void main(String [] args) {
uniqueValue(input);
}
Step1: To find the unique characters in a string, I have first taken the string from user.
Step2: Converted the input string to charArray using built in function in java.
Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters.
Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times).
Step5 : Now set2 will have only unique characters. Hence, just print that set2.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
char arr[] = str.toCharArray();
HashSet<Character> set1=new HashSet<Character>();
HashSet<Character> set2=new HashSet<Character>();
for(char i:arr)
{
if(set1.contains(i))
{
set1.add(i);
set2.remove(i);
}
else
{
set1.add(i);
set2.add(i);
}
}
System.out.println(set2);
}
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char[] array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean[] uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
public class UniqueCharactersInString {
public static void main(String []args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int[] repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string. In the second line I am looking for characters repetitive once.
how about this :)
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
package extra;
public class TempClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
char[] myCharArray=abcString.toCharArray();
TempClass mClass=new TempClass();
mClass.countUnique(myCharArray);
mClass.countEach(myCharArray);
}
/**
* This is the program to find unique characters in array.
* #add This is nice.
* */
public void countUnique(char[] myCharArray) {
int arrayLength=myCharArray.length;
System.out.println("Array Length is: "+arrayLength);
char[] uniqueValues=new char[myCharArray.length];
int uniqueValueIndex=0;
int count=0;
for(int i=0;i<arrayLength;i++) {
for(int j=0;j<arrayLength;j++) {
if (myCharArray[i]==myCharArray[j] && i!=j) {
count=count+1;
}
}
if (count==0) {
uniqueValues[uniqueValueIndex]=myCharArray[i];
uniqueValueIndex=uniqueValueIndex+1;
count=0;
}
count=0;
}
for(char a:uniqueValues) {
System.out.println(a);
}
}
/**
* This is the program to find count each characters in array.
* #add This is nice.
* */
public void countEach(char[] myCharArray) {
}
}
Here str will be your string to find the unique characters.
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
for(let j= 0; j< str.length; j++) {
if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
uniqueChars += str[i];
}
}
}
return uniqueChars;
}
public static void main(String[] args) {
String s = "aaabcdd";
char a[] = s.toCharArray();
List duplicates = new ArrayList();
List uniqueElements = new ArrayList();
for (int i = 0; i < a.length; i++) {
uniqueElements.add(a[i]);
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
duplicates.add(a[i]);
break;
}
}
}
uniqueElements.removeAll(duplicates);
System.out.println(uniqueElements);
System.out.println("First Unique : "+uniqueElements.get(0));
}
Output :
[b, c]
First Unique : b
import java.util.*;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
for(int i=0;i<test.length();i++){
if(test.lastIndexOf(test.charAt(i))!=i)
test=test.replaceAll(String.valueOf(test.charAt(i)),"");
}
System.out.println(test);
}
}
public class Program02
{
public static void main(String[] args)
{
String inputString = "abhilasha";
for (int i = 0; i < inputString.length(); i++)
{
for (int j = i + 1; j < inputString.length(); j++)
{
if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
{
inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
}
}
}
System.out.println(inputString);
}
}
The error occurs at odd[count1] = value.
This program should basically print a 2d array with evens being less than odds and then both sorted from lowest to highest.
public static void main(String args[]) {
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
for (int i=0; i<even.length; i++) {
even[i] = Integer.MAX_VALUE;
}
for(int i=0; i<odd.length; i++) {
odd[i] = Integer.MAX_VALUE;
}
int count = 0;
int count1 = 0;
//try non for each - possibly causing problem
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
even[count] = value;
count++;
} else {
//odd.add(value); - adds it to the end and then concatinate
odd[count1] = value;
count1++;
}
}
}
//even bubble sort
for(int j=0; j<odd.length; j++) {
for(int i=0; i<odd.length-1; i++) {
if(odd[i]>odd[i+1]) {
int temp = odd[i];
int tempTwo = odd[i+1];
odd[i] = tempTwo;
odd[i+1] = temp;
}
}
}
//odd bubble sort
for(int j=0; j<even.length; j++) {
for(int i=0; i<even.length-1; i++) {
if(even[i]>even[i+1]) {
int temp = even[i];
int tempTwo = even[i+1];
even[i] = tempTwo;
even[i+1] = temp;
}
}
}
int e = 0;
int o = 0;
for(int j=0; j<thots.length; j++) {
for(int i=0; i<thots[0].length; i++) {
if(e<even.length) {
thots[j][i] = even[e];
e++;
} else {
thots[j][i] = odd[o];
o++;
}
}
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
The basic idea is that I am inputting a 2d array. Then breaking that array into an even and odd array. Then sorting both and putting them back together to print.
since in you code size of array even[] and odd[] is 7.it should be sufficient enough to hold all the values.when you assigh value 17 to odd[7] this will through ArrayIndexOutOfBoundException.
change code-
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
to-
int [] even = new int[thots.length * thots[0].length];
int [] odd = new int[thots.length * thots[0].length];
Use following code-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class BinarySearch{
public static void main(String args[]) {
//System.out.println(Integer.MAX_VALUE);
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
List<Integer> evenList=new ArrayList<Integer>();
List<Integer> oddList=new ArrayList<Integer>();
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
evenList.add(value);
} else {
oddList.add(value);
}
}
}
Collections.sort(evenList);
Collections.sort(oddList);
int i=0;
int j=0;
for(Integer even:evenList){
if(j==thots[0].length){
i++;
j=0;
}
thots[i][j]=even;
j++;
}
for(Integer odd:oddList){
if(j==thots[0].length){
i++;
j=0;
}
thots[i][j]=odd;
j++;
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
Write a method that returns a new array by eliminating the duplicate values in the array using this header:
public static int[] eliminateDuplicates (int[] list)
all I have so far is my main, but what I wanted to do for the other method was use a for loop to check values at each space in my array and print them if they did not equal any of the other entries. Working on it as we speak!
My output is this: The distinct numbers are: [I#4554617c
first of all this is 11 characters and at max I should be printing 10.
import java.util.Scanner;
public class EliminateDuplicates
{
public static void main(String [] Args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter ten whole numbers: ");
int[] tenNumbers = new int[10];
for (int i=0; i<10; i++)
{
tenNumbers[i] = input.nextInt();
}
System.out.println("The distinct numbers are: " + eliminateDuplicates(tenNumbers));
}
public static int[] eliminateDuplicates (int[] list)
{
int count = 0;
for (int i = 0; i > list.length; i++)
{
for (int j = i + 1; j < list.length; j++)
{
if(list[i] == list[j])
{
list[j] = -1;
}
}
}
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
count++;
}
}
int[] array2 = new int[count];
int newCount = 0;
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
array2[newCount] = list[i];
}
}
return array2;
}
}
import java.util.ArrayList;
public class EliminateDuplicates {
//This is called Generics, It'll be a little later in your studies
public static <E> ArrayList<E> eliminateDuplicates(ArrayList<E> list) {
ArrayList<E> newList = new ArrayList<>(list.size());
for (E aList : list) { // for (int i = 0; i <= list.lenght; i++){
if (!newList.contains(aList)) {
newList.add(aList);
}
}
return newList;
}
public static void main(String[] args) {
ArrayList<Integer> tenNumbers = new ArrayList<Integer>();
tenNumbers.add(14);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
ArrayList<Integer> newList = eliminateDuplicates(tenNumbers);
System.out.print("The distinct numbers are: " + newList);
}
}
import java.util.*;
public class Question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = {1,2,3,3,4,5,6,1};
int[] ne = new int[arr.length];
ArrayList<Integer> already= new ArrayList();
int i = 0;
while(i<arr.length){
if(!already.contains(arr[i]))
already.add(arr[i]);
i++;
}
System.out.println(already.toString());
}
}
I've made a 12 by 12 table that runs in the same program, but i'd like to make it OO so that i can put the "public static void main" in another "testfile" and it will still run properly..i'm having some problems with the OO approach and i really need help...This is what my code looks like:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class PlayingArea {
public static void main(String[] args) {
Random r = new Random();
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
int region = input.nextInt();
String letters = "";
while(letters.length() < 2) {
if (region == 4) {
letters= "EFGH";
}
if (region == 3) {
letters= "EFG";
} else if (region == 2) {
letters= "EF";
} else if (region < 2) {
System.out.println("You inputed a wrong value, try again...");
}
}
int N = letters.length();
char [][] letter = new char[12][12];
for (int j = 0; j < letter.length; j++) {
for(int i=0; i < letter.length; i++) {
letter[i][j] = letters.charAt(r.nextInt(N)) ;
}
}
for (char[] letterRow : letter)
System.out.println(Arrays.toString(letterRow));
}
}
if you're relatively new to java then you're doing quite well. Be aware there is an infinite loop in your program (fixed below) if you enter a number outside of 2-4.
Firstly, your class PlayingArea needs some member variables to represent state.
The first one is the String letters (EF or EFG or EFGH), which is initialized via a constructor in the code below.
The second one is the char[][] grid (renamed from letter in your code) which is assigned a value in the populate() method, which puts letters into the grid.
The other method, gridAsString() does just that.
The public static void main can easily now be moved to another class, if you like.
Have fun.
public class PlayingArea {
private String letters;
private char[][] grid;
public PlayingArea(String letters) {
this.letters = letters;
}
public void populate() {
int n = letters.length();
grid = new char[12][12];
Random r = new Random();
for (int j = 0; j < grid.length; j++) {
for (int i = 0; i < grid.length; i++) {
grid[i][j] = letters.charAt(r.nextInt(n));
}
}
}
public String gridAsString() {
StringBuilder sb = new StringBuilder();
for (char[] letterRow : grid) {
sb.append(Arrays.toString(letterRow)).append('\n');
}
return sb.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
String letters = "";
while (letters.length() < 2) {
int region = input.nextInt();
if (region == 4) {
letters = "EFGH";
} else if (region == 3) {
letters = "EFG";
} else if (region == 2) {
letters = "EF";
} else {
System.out.println("You inputed a wrong value, try again...");
}
}
PlayingArea playingArea = new PlayingArea(letters);
playingArea.populate();
System.out.println(playingArea.gridAsString());
}
}
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!!