Create ArrayList from permutations Java - 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>.

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;
}
}

Find all possible string of length k with recursion

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;
}

How to print abc into zyx (mirror values in alpha) in java

how to print mirror value of alphabet in java?
public class Alphamirror {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2="";
char c;
int i;
for(i=0;i<s1.length();i++)
if(s1.charAt(i)<'m')
s2=s1.charAt(i)+
else if(||s1.charAt(i)>'z')
}
you can figure out index of mirror alphabet and print that. see the below code..
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
String s1=sc.next();
for(int i = 0; i < s1.length(); i++) {
int index = 'z' - s1.charAt(i);
System.out.print((char)('a' + index));
}
}
You could write a function that will mirror letters like the following:
static char alphaMirror(char c) {
int maxAdvance = 25;
int diff = c - ((c > 'Z') ? 'a' : 'A');
int advance = maxAdvance - 2 * diff;
return (char) (c + advance);
}
You can then call it, e.g, from main like:
public static void main(String[] args) {
String s = "abcdefghijklmnopqrstuvwxyz";
String s2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < s.length(); i++) {
System.out.println(i + ": " + alphaMirror(s.charAt(i)));
}
for (int i = 0; i < s.length(); i++) {
System.out.println(i + ": " + alphaMirror(s2.charAt(i)));
}
}
I would do it like this:
import java.util.HashMap;
import java.util.Map;
public class Temp {
public static Map<Character, Character> prepareMirrorMap() {
Map<Character, Character> charMap = new HashMap<>();
charMap.put(Character.valueOf('A'), Character.valueOf('Z'));
charMap.put(Character.valueOf('B'), Character.valueOf('Y'));
charMap.put(Character.valueOf('C'), Character.valueOf('X'));
charMap.put(Character.valueOf('D'), Character.valueOf('W'));
return charMap;
}
public static void main(String[] args) {
String temp = "ABCD";
System.out.println(ConvertToMirrorString.convertToMirror(temp));
}
}
class ConvertToMirrorString {
private static Map<Character, Character> charMap;
static {
charMap = Temp.prepareMirrorMap();
}
public static String convertToMirror(String inputString) {
StringBuilder temp = new StringBuilder();
for (Character c : inputString.toCharArray()) {
temp.append(charMap.get(c));
}
return temp.toString();
}
}
This is a working piece of code, however you need to add more data for map.

Storing an ArrayList inside a HashMap

I have the following code. What I want to do is to have an ArrayList filled using the permutation function, keep that Array in a HashMap, and start the process all over again (basically fill the HashMap with ArrayList for each key). I posted the code below however it does not work. I think this is because It's storing the same reference to the list I have declared instead of making a copy of it. I'm a C scrub and a Java newbie so any help is appreciated!
public class Anagrams
{
public static HashMap<String, ArrayList<String>> permutacii = new HashMap<String, ArrayList<String>>();
public static ArrayList<String> tempList = new ArrayList<String>();
private static void permutation(String prefix, String str)
{
int n = str.length();
if (n == 0)
tempList.add(prefix);
else
{
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i+1));
}
}
public static void main(String[] args) {
findAll(System.in);
}
public static void findAll(InputStream inputStream)
{
Scanner scanner = new Scanner(inputStream);
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
permutation("", line);
permutacii.put(line, tempList);
tempList.clear();
}
}
}
You only have one List of which you store multiple references in the HashMap. And you clear that List at the end of each iteration.
One possible way to fix your problem :
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
tempList = new ArrayList<String>();
permutation("", line);
permutacii.put(line, tempList);
}
Though I think the code would be more readable if you make tempList a local variable and pass it as an argument to the permutation method :
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
ArrayList<String> tempList = new ArrayList<String>();
permutation("", line, tempList);
permutacii.put(line, tempList);
}
and modify the permutation accordingly :
private static void permutation(String prefix, String str, ArrayList<String> tempList)
{
int n = str.length();
if (n == 0)
tempList.add(prefix);
else
{
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i+1),
tempList);
}
}

I want to split string without using split function?

I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

Categories

Resources