Find all possible string of length k with recursion - java

For string s = "abcd" ,k=3 then answer should be:
abc
abd
acd
bcd
code by java with recursion(k=3) :
public class SubString {
static ArrayList<String> al = new ArrayList<>();
public static void main(String[] args) {
String s = "abcd";
findsubsequences(s, ""); // Calling a function
for (String subString : al) {
if (subString.length() == 3) {
System.out.println(subString);
}
}
}
public static void findsubsequences(String s, String ans) {
if (s.length() == 0) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0));
findsubsequences(s.substring(1), ans);
}
}
I want to Find all possible substring of length k in fastest way by recursion and without foreach in arraylist

Solution using backtracking logic (can be generalized to solve any permutation / subsets / combination problems) -
public static void main(String[] args) {
ans = new ArrayList<>();
String s = "abcd";
int k = 3;
generatePermutation(new StringBuilder(""), 0, s.toCharArray(), k);
System.out.println(ans);
}
private static List<String> ans;
private static void generatePermutation(StringBuilder temp, int st, char[] str, int k){
if(temp.length() == k){
// base result
String br = temp.toString();
ans.add(br);
return;
}
for(int i = st; i < str.length; i++){
temp.append(str[i]);
generatePermutation(temp, i + 1, str, k);
temp.setLength(temp.length() - 1);
}
}
Output :
[abc, abd, acd, bcd]

The faster / cleaner solution is to stop iterating when you reached the maximum length. And you should only add elements if the length is correct:
public static void findsubsequences(String s, String ans, int maxLength) {
if (s.length() == 0) {
return;
}
if (ans.length() == maxLength) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0), maxLength);
findsubsequences(s.substring(1), ans, maxLength);
}
Additionally you could get rid of the static result list ans instead return the results:
public static void main(String[] args) {
String s = "abcdefgh";
List<String> results = findSubsequences(s, "", 3);
for (String subString : results) {
System.out.println(subString);
}
}
public static List<String> findSubsequences(String s, String ans, int maxLength) {
if (s.length() == 0) {
return new ArrayList<>();
}
if (ans.length() == maxLength) {
return Collections.singletonList(ans);
}
List<String> list = new ArrayList<>(findSubsequences(s.substring(1), ans + s.charAt(0), maxLength));
list.addAll(findSubsequences(s.substring(1), ans, maxLength));
return list;
}

Related

Find possible subsequences in java

Given a string S, find all the possible subsequences of the String in lexicographically-sorted order. I implemented in java but I am getting incorrect output. Please help
class Solution
{
public void helpr(String s,int ind,int n,StringBuilder curr,List<String> res){
if(ind==n){
res.add(curr.toString());
return;
}
helpr(s,ind+1,n,curr.append(s.charAt(ind)),res);
helpr(s,ind+1,n,curr,res);
}
public List<String> AllPossibleStrings(String s)
{
StringBuilder curr = new StringBuilder("");
List<String> res = new ArrayList<String>();
helpr(s,0,s.length(),curr,res);
Collections.sort(res);
res.remove(0);
return res;
}
}
for input - abc
actual op: abc abcc abcc abccbc abccbc abccbcc abccbcc
required op: a ab abc ac b bc c
import java.util.*;
class SubSequences {
static void get_sequence(String str, String ans, int i) {
// Base condition
if (i == str.length()) {
System.out.println("'" + ans + "'");
return;
}
// Before character gets added to final
get_sequence(str, ans, i + 1);
// after character gets added to ans
get_sequence(str, ans + str.charAt(i), i + 1);
}
public static void main(String arg[]) {
Scanner sc = new Scanner(System.in);
String str;
System.out.println("Enter the string");
str = sc.nextLine();
System.out.println("All possible subsequences are:");
get_sequence(str, "", 0);
}
}
Changed StringBuilder to String and its working now.
class Solution
{
public void helpr(String s,int ind,int n,String curr,List<String> res){
if(ind==n){
res.add(curr);
return;
}
helpr(s,ind+1,n,curr+s.charAt(ind),res);
helpr(s,ind+1,n,curr,res);
}
public List<String> AllPossibleStrings(String s)
{
String curr ="" ;
List<String> res = new ArrayList<String>();
helpr(s,0,s.length(),curr,res);
Collections.sort(res);
res.remove(0);
return res;
}
}

Return (not print) all permutations of a string Java

There are dozens of questions on "find the permutations of a string" but all of their answers are printing the permutations. I want to create a method that takes an input string and returns a List containing all the permutations.
Here is my code:
public static List<String> allPerms(String str){
List<String> results = new ArrayList<>();
while(!allPerms("", str).equals("")) {
results.add(allPerms("", str));
}
return results;
}
private static String allPerms(String perm, String word) {
if(word.length() == 0)
return perm;
for(int i = 0; i < word.length(); i++) {
String small = allPerms(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1));
return small;
}
}
But this gives me an error saying that the for loop of my private method is dead code. Can someone tell me what I'm doing wrong here?
There are some issues with your code, let's walk through them one by one. The function allPerms(String perm, String word) contains two issues: a missing return statement and the i++ dead code:
private static String allPerms(String perm, String word) {
if(word.length() == 0)
return perm;
for(int i = 0; i < word.length(); i++) {
String small = allPerms(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1));
return small; // <- if you return here the loop will only iterate once, so i++ is dead code.
}
// <- missing a return statement here
}
We can fix it like in the following:
public static String allPerms(String perm, String word) {
if(word.length() == 0)
return perm;
String small = "";
for(int i = 0; i < word.length(); i++) {
small = allPerms(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1));
}
return small;
}
Now there are no compilation errors but the result is not correct. In fact, if you run it you will get an infinite loop. The reason is because the method allPerms(String str) exits the while-loop only if the allPerms("", str) method returns and empty string which is never true! (unless you call allPerms(""))
public static List<String> allPerms(String str){
List<String> results = new ArrayList<>();
while(!allPerms("", str).equals("")) { // <- infinite loop because never true
results.add(allPerms("", str));
}
return results;
}
So you need the following changes to get the list of permutations:
public class Main {
public static List<String> allPerms(String str) {
return allPerms("", str);
}
public static List<String> allPerms(String perm, String word) {
if (word.length() == 0) {
return Arrays.asList(perm);
}
List<String> small = new ArrayList<>();
for (int i = 0; i < word.length(); i++) {
small.addAll(allPerms(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1)));
}
return small;
}
public static void main(String[] args) {
System.out.println(allPerms("abc")); // Prints: [abc, acb, bac, bca, cab, cba]
}
}

how to reverse a number using array in java?

I am writing a code to reverse a number entered by a user using java. I am using an array for this purpose. The problem that I am facing is in returning the array when I call my method in the main function.
I understand that you want to reverse an array... so, for that you can use ArrayUtils.reverse
ArrayUtils.reverse(int[] array)
For example, you can do:
public static void main(String[] arg){
int[] arr = { 1,2,3,4,5,6};
ArrayUtils.reverse(arr);
System.out.println(Arrays.toString(arr));
// Prints: [6, 5, 4, 3, 2, 1]
}
However, if you want to code the reverse by yourself, if you check the source code of ArrayUtils.reverse, you can find how Apache guys did it. Here the implementation:
public static void reverse(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
There are many ways of doing it. Depends if you want to use Java Builtin methods or not. Here is my part:
Reverse a int array using ListIterator:
public class ReverseAListWithoutInbuiltMethods {
public static void main(String[] args) {
int[] arr={12, 4, 34, 7, 78,33, 20};
display(arr);
int[] rev=reverse(arr);
display(rev);
}
private static void display(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(" "+arr[i]);
}
System.out.println("");
}
private static int[] reverse(int[] arr){
List<Integer> list=new ArrayList<Integer>();
for(int a:arr){
list.add(a);
}
int[] rev=new int[arr.length];
int j=0;
ListIterator<Integer> listI=list.listIterator(arr.length);
while(listI.hasPrevious()){
rev[j]=listI.previous();
j++;
}
return rev;
}
}
Reverse by for loop only:
public static void main(String[] args) {
/* create a new string */
StringBuilder s = new StringBuilder("GeeksQuiz");
System.out.println(" ************* REVERSED STRING IS **************");
char[] c2=reverseForLoop(s);
for (int i = 0; i < c2.length; i++) {
System.out.print(c2[i]);
}
}
private static char[] reverseForLoop(StringBuilder sb) {
char[] str = sb.toString().toCharArray();
int n = str.length;
char[] charNew = new char[n];
int j = 0;
for (int i = n - 1; i >= 0; i--) {
charNew[j] = str[i];
j++;
}
return charNew;
}
Reverse using swap method:
private static char[] reverse2(StringBuffer sb) {
char[] str=sb.toString().toCharArray();
int n = str.length;
for (int i = 0; i < n / 2; i++) {
swap(str, i, n - 1 - i);
}
return str;
}
private static void swap(char[] charA, int a, int b) {
char temp = charA[a];
charA[a] = charA[b];
charA[b] = temp;
}
Reverse String using Stack implementation:
public class StackForStringReverse {
public static void main(String[] args) {
/*create a new string */
StringBuffer s= new StringBuffer("GeeksQuiz");
/*call reverse method*/
reverse(s);
/*print the reversed string*/
System.out.println("Reversed string is " + s);
}
private static void reverse(StringBuffer str) {
int n=str.length();
MyStack obj=new MyStack(n);
// Push all characters of string
// to stack
int i;
for (i = 0; i < n; i++)
obj.push(str.charAt(i));
// Pop all characters of string and put them back to str
for (i = 0; i < n; i++)
{
char ch = obj.pop();
str.setCharAt(i,ch);
}
}
}
class MyStack{
int size;
char[] a;
int top;
public MyStack(int n) {
top=-1;
size=n;
a=new char[size];//{'1','f','f','f'};
}
public boolean isEmpty() {
return top<0;
}
/**
* Insert data into Stack if it's not full*/
public void push(char c) throws IllegalArgumentException{
if(top>=size) {
throw new IllegalArgumentException("Stack overflow.");
}
a[++top]=c;
}
public char pop() {
if(top<0) {
throw new IllegalArgumentException("Stack underflow.");
}
char x=a[top--];
return x;
}
public void clear() {
while(top>0) {
top--;
size=top;
}
}
/**
* Display the data inserted */
public void display() {
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]);
}
System.out.println("");
}
}
You can do that using StringBuilder :
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(getReverse(s.nextInt()));
}
public static int getReverse(int a){
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(a));
sb = sb.reverse();
return Integer.parseInt(sb.reverse().toString());
}
}
StringBuilder can do reversals.
String reverseNumber(Number n) {
String numStr = n.toString();
StringBuilder reverser = new StringBuilder(numStr);
reverser.reverse();
return reverser.toString();
}
Obviously there are some gaps here for particular cases (e.g. negative numbers) but I'll leave that for you to solve. This should serve as a good starting point.
Java is powerful, but complicated.
Here is a oneliner for it.
public static void main(String[] args) {
int n = 123;
int reversed_n = (int) Integer.valueOf( // 5.) cast back to an int.
new StringBuilder(
Integer.toString(n) // 1.) Make the integer a String.
) // 2.) load that string to a String builder.
.reverse() // 3.) reverse the string.
.toString())); // 4.) go back to a string.
}
Tried my hand at a relatively well-documented, external library and array-free solution. Hope it helps!
int reverseNumber(int inputNum)
{
String numString = Integer.toString(inputNum);
int numLength = numString.length();
int finalReversedNumber = 0;
/*
* Goes through the input number backwards, and adds the digit (with it's new value) to the final number.
* This is accomplished by multiplying the current number by 10 to the power of the index i, which corresponds
* to the current digit value of the number.
* i the index counter, goes from the length of the input number (not inclusive) to 0 (inclusive)
*/
for(int i=numLength-1; i>=0; i--)
{
int currentNum = Integer.parseInt(String.valueOf(numString.charAt(i)));
int valueInFinalNum = currentNum * (int)Math.pow(10, i); // i.e. a 5 in the thousands digit is actually 5000
finalReversedNumber += valueInFinalNum;
}
return finalReversedNumber;
}

Repeating a string

I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""
Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:
public static String repeat(String str, int n)
As a further note, an easier function might be
public static String repeat(String str, int n)
{
if (n == 0) return "";
String return_str = "";
for (int i = 0; i < n; i++)
{
return_str += str;
}
return return_str;
}
public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}
2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)
You are not passing correct arguments while you calling the desired method.
Call as repeat (str,k) k - should be an integer

Create ArrayList from permutations Java

I hope this isn't a stupid question but I took the code below from another post. It just generates all permutations of a string. What I'd like to do is just modify it so all the permutations are added to an arraylist but I'm having some trouble finding what is hopefully the simple obvious solution. Can someone give this a quick look and explain what I'm doing wrong? I just want to take the permutations of a string and create an array list, that's all.
public class UserInput {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word: ");
List<String> inputList = new ArrayList<String>();
String input = scan.next();
permutation(input);
//Error occurs here
inputList.addAll(permutation(input));
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
Permutation has no return type, it is a void method, you are putting it in a list which only accepts objects of type String. You can modify it so once the recursion reaches the lowest level it adds itself to the list like so:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word: ");
List<String> inputList = new ArrayList<String>();
String input = scan.next();
permutation(input, inputList);
System.out.println(inputList);
}
public static void permutation(String str, List<String> result) {
permutation("", str, result);
}
private static void permutation(String prefix, String str,
List<String> container) {
int n = str.length();
if (n == 0) {
container.add(prefix);
} else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, n),
container);
}
}
For "Hei"
[Hei, Hie, eHi, eiH, iHe, ieH]
Instead of printing the permutation out, you can add it to the list.
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class UserInput {
private static List<String> inputList;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word: ");
inputList = new ArrayList<>();
String input = scan.next();
permutation(input);
System.out.println(inputList.toString());
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) inputList.add(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
permutation(input) returns void, while inputList.addAll() expects Collection<String>.

Categories

Resources