String permutation using for loops - java

I have to print all the possible permutations of the given input string.
Using the code below I get aaaa bbb ccc now in next iteration I want to print aaa aab aac. aba aca and so on. Please guide me about it.
String s = "abc";
char ch;
ArrayList<Character> input = new ArrayList<Character>();
public static void main (String [] args)
{
String s= "abc";
int count ;
char ch;
ArrayList<Character> input = new ArrayList<Character>();
for (int i=0; i < s.length(); i++)
{
ch = s.charAt(i);
input.add(ch);
}
for (int i=0; i <= input.size(); i++)
{
for(int j=0; j < input.size(); j++)
{
System.out.print(input.get(i));
}
System.out.println();
}
}

You can use recursive function. Example
private static String text = "abcd";
public static void main(String[] args) {
loopPattern(text, 0, "");
}
private static void loopPattern(String source, int index, String res) {
if (source == null || source.length() == 0) {
return;
}
if (index == source.length()) {
System.out.println(res);
return;
}
for (int i = 0; i < source.length(); i++) {
loopPattern(source, index + 1, res + source.charAt(i));
}
}

In current implementation, you should use:
for (int i=0; i <= input.size(); i++) {
for(int j=0; j < input.size(); j++) {
for(int k=0; k < input.size(); k++) {
System.out.print(input.get(i));
System.out.print(input.get(j));
System.out.print(input.get(k));
System.out.println();
}
}
}
But IMHO it is better to use s.charAt(i) instead of input.get(i).

A recursive version which is not dependent of the number of characters:
class Test
{
public static void main(String[] args)
{
if(args.length != 1)
{
System.out.println("Usage: java Test <string>");
System.exit(1);
}
String input = args[0];
iterate(input, "", input.length());
}
public static void iterate(String input, String current, int level)
{
if(level == 0)
{
System.out.println(current);
return;
}
for(int i=0; i < input.length(); i++)
{
iterate(input, current + input.charAt(i), level-1);
}
}

Related

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index out of bounds

I was getting this error while running the following code. I couldn't find out what was wrong with the code.
As far as I can see, there's some issue with my second character array. But couldn't find out what was wrong. First tried running the last loop before temp_count. Then also tried temp_count±1. Yet, I failed. I have also tried taking different array size. still no luck
import java.util.Scanner;
public class oop2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str=sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[temp_count];
//Converting uppercase to lower case for convenience
for(int i=0; i<str.length(); i++)
{
if (Character.isUpperCase(c[i]))
{
c[i]=(char) (c[i]+32);
}
}
//verifying whether the alphabet exists
for(char x = 'a'; x<='z'; x++)
{
int count=0;
for(int i=0; c[i]!='\0'; i++)
{
if (c[i]==x)
{
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count==0)
{
temp[temp_count]=x;
temp_count++;
}
}
//Verifying whether it's a pangram or not
if (temp_count==0)
{
System.out.println("Pangram");
}
else
{
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for(int i=0; i<temp_count-1; i++)
{
System.out.print(temp[i]+", ");
}
}
sc.close();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str = sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[0];
//Converting uppercase to lower case for convenience
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(c[i])) {
c[i] = (char)(c[i] + 32);
}
}
//verifying whether the alphabet exists
for (char x = 'a'; x <= 'z'; x++) {
int count = 0;
for (int i = 0; c[i] != '\0'; i++) {
if (c[i] == x) {
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count == 0) {
char [] copy = new char[temp.length+1];
for (int i = 0; i < temp.length; i++) {
copy[i]=temp[i];
}
copy[copy.length-1] = x;
temp=copy;
}
}
//Verifying whether it's a pangram or not
if (temp_count == 0) {
System.out.println("Pangram");
} else {
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for (int i = 0; i < temp_count - 1; i++) {
System.out.print(temp[i] + ", ");
}
}
sc.close();
}
}
Blockquote

How to move each "i" in a string to the next position in java

I want to shift each i in a given string one index to the right. How can I do that? For example:
"Chit Nyein Oo is nothing.";
becomes
"Chti Nyeni Oo si nothnig.";
If i occurs in the last index, it need not change its position.
Use string.replaceAll
string.replaceAll("i(.)", "$1i");
DEMO
EDIT: NOW it works for all conditions. Last letter in the String is 'i' or not, it works.
public class t4 {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothing.";
char o = 'i';
int indexes = 0;
if(input.charAt(input.length()-1) != 'i'){ //Test if last letter is not 'i'
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
System.out.println(input);
System.out.println(swappedString);
} else { //so last letter is i
char t = input.charAt(input.length()-1);
String ha = input.substring(0, input.length()-1);
input = ha;
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
swappedString = swappedString + Character.toString(t);
System.out.println(input);
System.out.println(swappedString);
}
}
}
You can do this using a StringBuilder.
class Test {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothingi";
int len = input.length();
StringBuilder sb = new StringBuilder();
// System.out.println(sb);
for(int i=0; i<len; i++) {
char charAti = input.charAt(i);
if(charAti == 'i' && i<len-1) {
sb.append(input.charAt(i+1));
sb.append(charAti);
i++;
}
else {
sb.append(charAti);
}
}
System.out.println(sb);
}
}

My sort method and find/count method are messing up and I have no idea what's wrong?

I have to write a program that sorts names alphabetically while removing duplicates and counting the amount of times the names appear and capitalizes all of it. My partner and I have been working on this and have found no way to have the sorting method work properly and have the program find and count the times the names appear. We have to use certain methods to do this...which I linked the pdf down at the bottom. I really want to understand what's wrong and why the output is not coming out right.
public class Names {
/**
* #param args the command line arguments
*/
static ArrayList<String> fnArray = new ArrayList<String>();
static ArrayList<String> lnArray = new ArrayList<String>();
public static void main(String[] args) throws IOException {
// TODO code application logic here
getNames(fnArray, lnArray);
sort(lnArray);
find(fnArray,1);
capitalize(fnArray,lnArray);
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What file would you like to read from ?: ");
String n = kb.next();
File inputFile = new File(n);
Scanner in = new Scanner(inputFile);
while (in.hasNext()) {
String firstName = in.next();
fn.add(firstName);
String lastName = in.next();
ln.add(lastName);
}
for (int i = 0; i < fnArray.size(); i++) {
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}
public static void capitalize(ArrayList<String> fnArray, ArrayList<String> lnArray) {
String capfn = " ";
String capln = " ";
int i = 0;
int j = 0;
System.out.println("****************Names***************");
while (i < fnArray.size() && j < lnArray.size()) {
capfn = fnArray.get(i);
capln = lnArray.get(j);
String capFname = capfn.substring(0, 1).toUpperCase() + capfn.substring(1).toLowerCase();
String capLname = capln.substring(0, 1).toUpperCase() + capln.substring(1).toLowerCase();
fnArray.set(i, capFname);
lnArray.set(i, capLname);
System.out.println(lnArray.get(j) + ", " + fnArray.get(i));
i++;
j++;
}
}
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
int count = 0;
for (String str : a) {
if (str.equalsIgnoreCase(s))
count++;
}
return count; }
public static void removeDuplicates(ArrayList<String> s) {
for (int j = 0; j < s.size(); j++) {
int i = -1;
while ((i = find(s, j)) >= 0) {
s.remove(i);
}
}
}
public static void backwards(ArrayList<String> names) {
for (int i = names.size() - 1; i > 0; i--) {
names.get(i);
for (int j = 0; j < names.size(); i++) {
if ((names.get(i).equals(names.get(j)))) {
names.remove(i);
}
}
}
}
public static void sort(ArrayList<String> array) {
for (int i = 1; i < array.size(); i++) {
// find the index of the ith smallest value
int s = i - 1;
for (int j = i; j < array.size(); j++) {
if (array.get(j).compareTo(array.get(s)) < 0) {
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array.get(i - 1);
array.set(i - 1, array.get(s));
array.set(s, temp);
}
}
public static void showUnique(ArrayList<String> names){
System.out.println("Unique name list contains:");
for(int i=0 ;i< names.size() ;i++){
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}}
You can use the Collections.sort() method to sort an array list; once it is sorted, you will have entries like this:
ArrayList = { "Alpha", "Beta", "Beta", "Gamma", "Theta", "Theta" ... }
The important point to note, however, is that the duplicates will be next to each other in the sorted array.
Finally, if you want to remove duplicates, you can put all the elements of the ArrayList into a Set: set is a data-structure which removes duplicates.
Example:
Set<String> foo = new HashSet<String>( yourArrayList );
EDIT: Use this approach which is both: easy and simple-to-comprehend.
for( int i = 0; i < array.size() - 1; i++ )
{
for( int j = i + 1; j < array.size(); j++ )
{
if( array[i] > array[j] )
{
// Swap the contents of array[i] and array[j].
}
}
}

Look for repeated characters in a string

I know this question was asked many times, but I didn't find any of the answers helpful in my case. I have a method that receives a String. I want to check if any of the characters in the string are repeated. If so the method will return an empty String. If not it will return the String back.
The method is looking for any repeated character in the String.
private String visit(String word) {
int count = 0;
if(word == ""){
return "<empty>";
}
//alphabet is an array that holds all characters that could be used in the String
for(int i = 0; i < alphabet.length; i++){
for(int j = 0; j < word.length(); j++){
if(alphabet[i] == word.charAt(j)){
count++;
}
if(count == 2){
return "";
}
}
count = 0;
}
return word;
}
Ok, I publish my solution to this:
package main;
import java.util.Arrays;
public class main {
public static void main(String[] args) {
System.out.println(hasDups("abc"));
System.out.println(hasDups("abcb"));
}
public static String hasDups(String arg) {
String[] ar = arg.split("");
Arrays.sort(ar);
boolean noDups = true;
for (int i = 1; i < ar.length && noDups; i++) {
if (ar[i].equals(ar[i-1])) noDups = false;
}
if (noDups) return arg; else return "";
}
}
This might not be the best way of doing what you want, but you can use two for loops to check each character against all the other characters to see if it is repeated.
public static String hasRepeated(String word) {
if (word.isEmpty()) return "<empty>";
char[] charArray = word.toCharArray();
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray.length; j++) {
if (i == j) {
} else if (Character.toString(charArray[i]).
equalsIgnoreCase(Character.toString(charArray[j]))) {
return "";
}
}
}
return word;
}
Note: This code assumes that the case of the character doesn't matter, it just checks if it is repeated.
/**
* Returns the index of the first character repeated, or -1 if no repeats
*/
public static int firstRepeated( String s ) {
if ( s != null ) {
int n = s.length();
for (int i = 0; i < (n - 1); i++) {
int indx = s.indexOf( s.charAt( i ), i + 1 );
if ( indx > 0 ) {
return i;
}
}
}
return -1;
}
This works!!
public static String checkDuplicate(String str)
{
int count = 0;
char[] charArray = str.toCharArray();
for(int i=0;i<charArray.length;i++)
{
count = 0;
for(int j=0;j<charArray.length;j++)
{
if(charArray[i]==charArray[j])
{
count++;
if(count==2) break;
}
}
if(count==2) break;
}
if(count==2)
return "";
else
return str;
}
}

Removing a comma at the end of String

I am trying to convert an HashSet into comma seperated delimited String
But the problem is that , i am getting an extra comma at the end of the String also as shown .
Please tell me how can i remove that extra comma at the end of the String .
import java.util.HashSet;
import java.util.Set;
public class Test {
private static Set<String> symbolsSet = new HashSet<String>();
static {
symbolsSet.add("Q1!GO1");
symbolsSet.add("Q2!GO2");
symbolsSet.add("Q3!GO3");
}
public static void main(String args[]) {
String[] a = symbolsSet.toArray(new String[0]);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a.length; i++) {
sb.append(a[i] + ",");
}
System.out.println(sb.toString());
}
}
Output :
Q3!GOO3,Q2!GO2,Q1!GO1,
Do like this
for (int i = 0; i < a.length - 1; i++) {
sb.append(a[i] + ",");
}
sb.append(a[a.length - 1]);
Try with:
for (int i = 0; i < a.length; i++) {
if ( i > 0 ) {
sb.append(",");
}
sb.append(a[i]);
}
There are many ways you can do this, below is a regex solution using String#replaceAll()
String s= "abc,";
s = s.replaceAll(",$", "");
StringBuffer sb = new StringBuffer();
String separator = "";
for (int i = 0; i < a.length; i++) {
sb.append(separator).append(a[i]);
separator = ",";
}
In your given scenario String.lastIndexOf method is pretty useful.
String withComma= sb.toString();
String strWithoutLastComma = withComma.substring(0,withComma.lastIndexOf(","));
System.out.println(strWithoutLastComma);
String str = sb.toString().substring(0, sb.toString().length()-1);
or append only if not last element
for (int i = 0; i < a.length; i++) {
if ( i > 0 ) {
sb.append(",");
}
sb.append(a[i]);
}
public static void main(String args[]) {
String[] a = symbolsSet.toArray(new String[0]);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a.length-1; i++) {
//append until the last with comma
sb.append(a[i] + ",");
}
//append the last without comma
sb.append(a[a.length-1]);
System.out.println(sb.toString());
}
Try this :
for (int i = 0; i < a.length; i++) {
if(i == a.length - 1) {
sb.append(a[i]); // Last element. Dont append comma to it
} else {
sb.append(a[i] + ","); // Append comma to it. Not a last element
}
}
System.out.println(sb.toString());
Try this,
for (int i = 0; i < a.length-1; i++) {
if(a.length-1!=i)
sb.append(a[i] + ",");
else
{
sb.append(a[i]);
break;
}
}
public static void main(String args[])
{
String[] a = symbolsSet.toArray(new String[0]);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a.length; i++)
{
sb.append(a[i] + ",");
}
System.out.println(sb.toString().substring(0, sb.toString().length - 1));
}
OR
public static void main(String args[])
{
String[] a = symbolsSet.toArray(new String[0]);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a.length; i++)
{
sb.append(a[i]);
if(a != a.length - 1)
{
sb.append(",");
}
}
System.out.println(sb.toString());
}
You could grow your own Separator class:
public class SimpleSeparator<T> {
private final String sepString;
boolean first = true;
public SimpleSeparator(final String sep) {
this.sepString = sep;
}
public String sep() {
// Return empty string first and then the separator on every subsequent invocation.
if (first) {
first = false;
return "";
}
return sepString;
}
public static void main(String[] args) {
SimpleSeparator sep = new SimpleSeparator(",");
System.out.print("[");
for ( int i = 0; i < 10; i++ ) {
System.out.print(sep.sep()+i);
}
System.out.print("]");
}
}
There's loads more you can do with this class with static methods that separate arrays, collections, iterators, iterables etc.
Try with this
for (int i = 0; i < a.length; i++) {
if(i == a.length - 1 )
{
sb.append(a[i]);
} else {
sb.append(a[i] + ",");
}
}

Categories