Permutations of a string - java

public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String text = bufReader.readLine();
shuffle("",text);
}
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
input = input.substring(i,1) + input.substring(0,i) + input.substring(i+1);
shuffle(dummy+input.substring(0,1),input.substring(1));
}
}
}
}
Am trying to print all the permutations of a string entered. And I really cannot guess where am going wrong because on paper I find that this executing. Where exactly am going wrong.

Try change your shuffle:
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
shuffle(dummy+input.charAt(i), input.substring(0, i) + input.substring(i+1, input.length()));
}
}
}

public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String text = bufReader.readLine();
shuffle("",text);
}
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
input = input.substring(i,i+1) + input.substring(0,i) + input.substring(i+1);
shuffle(dummy+input.substring(0,1),input.substring(1));
}
}
}
}
It should be input.substring(i,i+1) instead of input.substring(i,1). Because each time I need only 1 character to be constant, which is at the beginning of the string and others have to be jumbled.
The bug was I presumed the functionality of substring to be substring(beginIndex, length). But it is substring(beginIndex,endIndex).
#Oli: Thank you for the help.

Since this seems like a homework assignment I once did I will help you out here. You will need two loops, one inside the other.
for(int i;i<something;i++)
for(int j;j<somethingElse;j++)
This will enable you to generate the permutations that are required.

Replace two lines in the for loop with following:
String partString = input.substring(0, i) + input.substring(i + 1);
shuffle(dummy + input.charAt(i), partString);
Since this looks like your homework I will let you figure out. If not, will post explanation after a bit ( got to get back to my day job ;) )

Related

Way too long words

This is my solution to the "way too long words" problem on codeforces.
Even though I am getting correct output, but still it has been reported as the wrong answer to a question by codeforces.
https://codeforces.com/problemset/problem/71/A
(link to the question)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//charAt() is an inbuilt method which can read a string letter by letter
Scanner input=new Scanner(System.in);
int n;
//System.out.println("how many words do you wish to enter?");
n=input.nextInt();
String[] words=new String[n+1];
for(int i=0;i<n+1;i++)
{
words[i]=input.nextLine();
}
for(int j=0;j<n+1;j++)
{
if(words[j].length()<10)
{
System.out.print(words[j]);
}
else
{
System.out.print(words[j].charAt(0));
System.out.print(words[j].length()-2);
System.out.print(words[j].charAt(words[j].length()-1));
}
System.out.print("\n");
}
}
}
Problem is with the condition, you are only skipping words below the length of 10 but not considering the words with exact of 10 length.
if(words[j].length()<=10)
{
System.out.print(words[j]);
}
Change the condition it should work.
Inside the for loop for int j do something like this -
if(words[j].length()<=10) //boundary check
{
System.out.print(words[j]);
}
else
{
System.out.println(words[j].charAt(0).toString() + words[j].length()-2 + words[j].charAt(words[j].length()-1).toString());
}
Because where r you entering string in your program. Once you run, you will get to know.
Btw this is the solution of actual problem.
public static void main(String[] args){
String str=null;
int count=0;
Scanner scanner= new Scanner(System.in);
System.out.println("enter string :");
str=scanner.nextLine();
for(int i=0; i<str.length(); i++) {
count ++;
}
char first=str.charAt(0);
char last=str.charAt(count-1);
int num=count-2;
System.out.println("abbreviation is :" +first+num+last);
}
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
string change_abb(string str)
{
string result;
if(str.length()>10)
{
int k=str.length()-2;
stringstream ss;
ss<<k;
string s;
ss>>s;
result+=str[0];
result+=s;
result+=str[str.length()-1];
}
else
{
result=str;
}
return result;
}
int main()
{
string in_str;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>in_str;
cout<<change_abb(in_str)<<endl;
}
}
Here is my answer in Python 3 (Answer accepted by Codeforces)
n = int(input())
p=""
for i in range(n):
s = input()
if len(s)>10:
p = s[0]+str((len(s)-2))+s[len(s)-1]
else:
p=s
print(p)

String index out of range error in Java (String index out of bounds exception )

everyone so I'm writing a code that should take "aabbcc" and output "abc" so deleting the repeated characters using recursion. Hope you could help me out.
import java.util.*;
public class StringReverser
{
public static String getReverser(String i)
{
if (i==(" "))
return "";
if (i.charAt(0)==i.charAt(1))
return i.substring(1) + getReverser(i.substring(2));
else
return getReverser(i.substring(1));
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String in = sc.nextLine();
System.out.println(getReverser(in));
}
}
And when I run my code i get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 1
at java.lang.String.charAt(String.java:646)
at StringReverser.getReverser(StringReverser.java:9)
at StringReverser.getReverser(StringReverser.java:12)
at StringReverser.getReverser(StringReverser.java:10)
at StringReverser.main(StringReverser.java:20)
Maybe use split? This is easier to use.
Here is a working solution. You were close!
You want to keep returning the word if it's only one character (otherwise you'll get an out of bounds exception).
If the characters next to one another are the same, then return a new word that only keeps the rightmost character (skipping a duplicate).
public static String getReverser(String word) {
System.out.println(word);
if (word.length() == 1) {
return word;
}
if (word.charAt(0) == word.charAt(1)) {
return getReverser(word.substring(1));
} else {
return word.substring(0, 1) + getReverser(word.substring(1));
}
}
Output:
Enter a String:
aabbccccaa
aabbccccaa
abbccccaa
bbccccaa
bccccaa
ccccaa
cccaa
ccaa
caa
aa
a
abca
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
StringBuilder builder = new StringBuilder();
char[] charArray = sc.nextLine().toCharArray();
for(char chr : charArray){
if(builder.indexOf(String.valueOf(chr))==-1){
builder.append(chr);
}
}
System.out.println(builder);
}

How can i make the code print backwards recursively?

Here's my code.
I am trying to make the String entered print out backwards, but every time I run it the code doesn't print out anything when it's called to print in reverse.
package Pali;
import java.util.Scanner;
/**
* Created by alexa on 11/4/2016.
*/
public class Palindromes {
public static void main(String[] args)
{
String msg;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
msg = scan.nextLine();
System.out.print("\nThe string backwards: ");
printBackwards(msg);
System.out.println();
}
public static String printBackwards(String s)
{
if (s.length() == 0)
return s;
return printBackwards(s.substring(1)) + s.charAt(0);
}
}
printBackwards actually just returns a String, but does nothing else. To print that returned String you would have pass it to the println method.
public static void main(String[] args)
{
String msg;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
msg = scan.nextLine();
System.out.print("\nThe string backwards: ");
String reversed = printBackwards(msg);
System.out.println(reversed);
}
Alternatively, you can let printBackwards print the String and leave the main method as it was:
public static String printBackwards(String s)
{
if (s.length() == 0)
{
System.out.println(s);
return s;
}
return printBackwards(s.substring(1)) + s.charAt(0);
}
Well you forgot to print letters
public static void printBackwards(String s)
{
if (s.length() == 0) return ;
printBackwards(s.substring(1));
System.out.print(s.charAt(0));
}
DEMO
Iteratively:
static String printBackwards(String s) {
StringBuilder sb = new StringBuilder();
for(int i = s.length() - 1; i >= 0; --i)
sb.append(s.charAt(i));
return sb.toString();
}
Recursively:
static String printBackwards(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
}
Your code calls printBackwards, but immediately discards the output.
Try changing line 6 of main() to System.out.print(printBackwards(msg));
Given that, I would also think about changing the method name to something like reverseString(String).

To Reduce a String

I was solving a problem to reduce the form to it's non-reducible form. This was the question.
Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!
If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0:
Shil can perform the following sequence of operations to get the final string:
Thus, we print .
Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
aaabccddd -> abccddd
abccddd -> abddd
abddd -> abd
Thus we print abd
Sample case 1:
baab -> bb
bb -> Empty String.
And what I have done till now is try to solve it through StringBuilder in Java.But some of testcases pass while other's don't and I can't find out what's the error?
Here is the code that I have tried so far.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
for(int i = 0; i < sb.length()-1; i++)
{
if(sb.charAt(i) == sb.charAt(i+1))
sb.delete(i,i+2);
i = 0;
}
if(sb.length() == 0)
System.out.println("Empty String");
else
System.out.println(sb.toString());
}
}
Inputs like aaabccddd
and aa pass.But when the input is baab it fails.
You have to use a while loop. Problem with your code is that it just iterate through the code just one time. In first iteration though your input "baab" becomes "bb", then it checks 2nd b and try to find a "b" in i+1 (which does not exist). change your for loop to a while loop as below.
import java.util.Scanner;
public class Solution{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
int c=0;
while(c< sb.length()-1){
if(sb.charAt(c) == sb.charAt(c+1)){
sb.delete(c,c+2);
c=0;
}
else{
c+=1;
}
}
if(sb.length() == 0)
System.out.println("Empty String");
else
System.out.println(sb.toString());
}
}
The problem is you just run loop through the string for one time.
For example:
String "baab", you just delete "aa" and finish the loop.
Solution: use recursion with a flag isNonReducible, loop until it give empty string or flag isNonReducible = true;
public class Solution {
public static StringBuilder checkReducible(StringBuilder sb) {
boolean isNonReducible = true;
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
isNonReducible = false;
sb.delete(i, i + 2);
}
}
if (sb.length() == 0) {
return new StringBuilder("Empty String");
}
else {
if(!isNonReducible) {
sb = checkReducible(sb);
}
return sb;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
System.out.println(checkReducible(sb));
scan.close();
}
}
you can do with the help of lable try this,
public static void main(String[] args) {
boolean canReduce = true;
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
startPoint: while (sb.length() > 0 && canReduce) {
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.delete(i, i + 2);
canReduce=true;
continue startPoint;
}else{
canReduce=false;
}
}
}
if (sb.length() == 0) {
System.out.println("Empty String");
} else {
System.out.println(sb.toString());
}
}
Try this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder sb =new StringBuilder(in.nextLine());
for (int i=0; i<sb.length()-1; i++){
if(sb.charAt(i)==sb.charAt(i+1)){
sb.delete(i, i+2);
i=-1;
}
}
if(sb.length()==0){
System.out.println("Empty String");
}else{
System.out.println(sb);
}
}

Split a string and join the parts with a random order in Java

Hi guys and ty for reading my question. I want to write a program which must read a String and split its words and join them by a random order again.I wrote this so far :
package read.java;
import java.io.*;
public class ReadJava {
public static int count;
public static String[] stringsplit(String S)
{
count=0;
String[] strings=new String[10];
if (S.isEmpty())
return strings;
char start=0;
while(true)
{
if(S.charAt(start)!=' ')
{
strings[count]+=S.charAt(start);
}
else
{
if(S.charAt(start)==' '&&S.charAt(start-1)!=' ')
{
count++;
}
if(start==S.length())
{
count++;
break;
}
}
start++;
}
return strings;
}
public static String stringjoin(String[] words)
{
int [] wordnum= new int [count];
for(int i=0;i<count;i++)
{
wordnum[i]=i;
}
String newS = new String();
while (count!=0)
{
int randnum;
randnum = (int)Math.random()%count;
newS+=words[randnum];
for(int i=randnum;i<count-2;i++)
{
wordnum[i]=wordnum[i+1];
}
count--;
}
return newS;
}
public static void main(String[] args) throws IOException {
BufferedReader bfreader =new BufferedReader(new InputStreamReader(System.in));
String S = new String();
S=bfreader.readLine();
String[] strings=new String[10];
strings=stringsplit(S);
S=stringjoin(strings);
System.out.println(S);
}
}
But when I'm compiling and input any sentences it throws an exception :
StringIndexOutOfBoundsException in this line :
S.charAt(start)!=' '
I'm new to Java and I don't have any ideas about the error.
That Error fixed by your helps but its still wrong. I fixed my while in stringsplit to this :
while(start < S.length())
but its printing "nullThisnullisnullanulltest" for "This is a test"
Is my stringjoin method wrong ?!
You should change your while condition:
while (start < S.length())
Because the maximum index of the string you can reach is (length of string - 1, zero-based index)
P.S. you can delete the following from your split function, it will never be reached:
if(start==S.length())
{
count++;
break;
}
P.P.S. You are getting "null"s at the output, because you init your array with "null" values. To resolve that, add the following after your array init Arrays.fill(strings,""). So, the correct code at the start of your stringsplit function will be like that:
count=0;
String[] strings=new String[S.length()]; //we don't know the number of words we get, but this number definitely no more that length of incoming string
Arrays.fill(strings, "");
if (S.isEmpty()){
....
The out-of-bounds exception is because you're attempting to access an index of the string outside of its range (since String is essentially a character array).
On another note, might I recommend:
String orig = "Some string with spaces";
String[] split = orig.split(" ");
start ends up being equal to the length of the string, but you have to keep in mind that the length of the string is 1 greater than the end element (because the String is a zero-based array).
Make the condition in the while loop something along the line of while(start < S.length)

Categories

Resources