I have a string that has no spaces and I wanted to create an array that consists of the substrings of the word. For instance, let the string is stackoverflow The array should be like:
[sta, cko, ver, flo, w]
The code that I use is below and that does give me only the first item. Any help will be appreciated.
public static ArrayList<String> getWords(String s){
ArrayList<String> words = new ArrayList<String>();
for(int i=0;i<s.length(); i=i+3){
words.add(s.substring(i, 3));
}
return words;
}
There are two issues with your code. First, the "3" in
s.substring(i, 3)
means the 3rd index from the beginning of the string, not the 3rd index from i, so you'd want
s.substring(i, i + 3)
Second, if the string is shorter than i + 3, you'll get an exception. To solve this, you can use Math.min. It would look something like this:
public static ArrayList<String> getWords(String s){
ArrayList<String> words = new ArrayList<String>();
for(int i=0;i<s.length(); i=i+3){
words.add(s.substring(i, Math.min(i + 3, i.length())));
}
return words;
}
You need to pass i + 3 as the second parameter of the substring call (it takes begin and end indexes). Also, I would prefer to program to the List interface. You might use += instead of i = i + 3. And you need an else clause for when there aren't three letters in the String. Like,
public static List<String> getWords(String s) {
List<String> words = new ArrayList<>();
for (int i = 0; i < s.length(); i += 3) {
if (i + 3 < s.length()) {
words.add(s.substring(i, i + 3));
} else {
words.add(s.substring(i));
}
}
return words;
}
Then, for completeness, I tested it with a basic main method like
public static void main(String[] args) {
System.out.println(getWords("stackoverflow"));
}
Which outputs (as requested)
[sta, cko, ver, flo, w]
You are on the right track, but your substring should be (i, i+3) as the following:
public static ArrayList<String> getWords(String s){
ArrayList<String> words = new ArrayList<String>();
for(int i=0;i<s.length(); i+=3){
if (i+3 >= s.length())
words.add(s.substring(i));
else
words.add(s.substring(i, i+3));
}
return words;
You can ease it significantly by using guava's Splitter:
String f = "stackoverflow";
List<String> p = Splitter.fixedLength(3).splitToList(f);
System.out.println(p); // [sta, cko, ver, flo, w]
Related
I want to print number of possible non-empty sequences of letters .
Eg.
String str="ABC";
Expected output is
A,B,C
AB,AC,BC,BA,CA,CB
ABC,ACB,BAC,BCA,CAB,CBA`
But i get the below output which is incorrect. How to fix my code
BB CC A AB ACC BC ABC AC B BBC CCC BCC C CBC CB
I have written the below code using Recurion
String tiles = "ABC";
Set<String> ans = new HashSet<>();
solve(tiles, 0, "", ans);
public static void solve(String tiles, int idx, String output, Set<String> ans) {
ans.add(output);
if (idx >= tiles.length()) {
return;
}
for (int i = idx; i < tiles.length(); i++) {
solve(tiles, idx + 1, output + tiles.charAt(i), ans);
}
}
This is how recursion tree would look like for str="AAB"
You need to ignore the first passing of the "" from output and then you need to ignore each letter you already passed through
public static void main(String[] args) {
String tiles = "ABC";
List<String> ans = new ArrayList<>();
solve(tiles, "", ans);
System.out.println(ans);
}
public static void solve(String tiles, String output, List<String> ans) {
if (!output.equals("")) ans.add(output);
for (int i = 0; i < tiles.length(); i++) {
String str = tiles.substring(0, i) + tiles.substring(i + 1);
solve(str, output + tiles.charAt(i), ans);
}
}
Output
[A, AB, ABC, AC, ACB, B, BA, BAC, BC, BCA, C, CA, CAB, CB, CBA]
you can try this
public class Permutation {
public static List<String> getPermutations(String str) {
Set<String> permutations = new HashSet<>();
permute(str, "", permutations);
return new ArrayList<>(permutations);
}
private static void permute(String string, String prefix, Set<String> permutations) {
if (string.length() == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < string.length(); i++) {
char charAt = string.charAt(i);
String remainingString = string.substring(0, i) + string.substring(i + 1);
permute(remainingString, prefix + charAt, permutations);
}
}
}
}
The "permute" method takes in 3 parameters: a string, a prefix string and a set of permutations.
The "permute" method takes in 3 parameters: a string, a prefix string and a set of permutations.
If the input string is not empty, it uses a for loop to iterate through the characters of the input string.
For each iteration, it gets the character at the current index, creates a new string by removing that character from the input string.
it then calls the permute method 3 times:
it then calls the permute method 3 times:
One with the original string and prefix
One with the remaining string and prefix
This way, the function explores all the possible permutations of the characters in the input string, including the option of not having one of the characters in the permutation and the permutation of positions, without including an empty string as an option.
Then you use like:
Permutation p = new Permutation();
List<String> permutations = p.getPermutations("abc");
Make 1 change:
Set<String> ans = new TreeSet<>(Comparators.comparing(String::length).thenComparing(s -> s));
It's a quite popular backtracking problem. You can find almost same problem here:
https://leetcode.com/problems/subsets/
The input are numbers instead of characters but the idea is the same.
You can switch to the solution tab and explore different answers:
https://leetcode.com/problems/subsets/solutions/
To take an arraylist of strings consisting of strings like:
fewf5677
kskfj654
pqoen444
mgnwo888
And i want to split them up BUT i DON'T want to use the split method because I have to perform other calculations with the letters that i'have split up.
SO i'have decided to use the subList method. But I can't seem to find a proper example of implementing this correctly. Take a look at my code. Below is a method that takes in an arraylist of strings as the parameter:
public static void splitup(ArrayList<String> mystrings){
mystrings.subList(String[] letters, double numbers);
}
So overall, how do I take each string of letters and numbers and store them into their own string arrays? For example, i want
fewf
kskfj
pqoen
mgnwo
to be in their own string along with
5677
654
444
888
to be their own numbers.
You could use regex as seen in this answer and then check for a pattern as shown in this answer as follows:
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringSplitter {
public static void main(String[] args) {
ArrayList<String> myStringsList = new ArrayList<String>();
ArrayList<String> stringsList = new ArrayList<String>();
ArrayList<String> numbersList = new ArrayList<String>();
myStringsList.add("fewf5677");
myStringsList.add("kskfj654");
myStringsList.add("pqoen444");
myStringsList.add("mgnwo888");
for (String s : myStringsList) {
String splittedString[] = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (String string : splittedString) {
Matcher match = Pattern.compile("[0-9]").matcher(string);
if (match.find()) {
numbersList.add(string);
} else {
stringsList.add(string);
}
}
}
for (String s : numbersList) {
System.out.println(s);
}
for (String s : stringsList) {
System.out.println(s);
}
}
}
This will output:
5677
654
444
888
fewf
kskfj
pqoen
mgnwo
Remember that split() takes a regex as parameter, not a String and so, you can do something like the above code to get the desired output.
What you are trying to do is a bit strange. Why are you trying to overload subList method?
One of possible examples of what you could do is to iterate over mystrings list and separate each string into two variables.
http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/
If you are familiar with regular expressions you can use them them.
If not you can iterate over string characters to separate letters from number.
http://java11s.blogspot.com/2012/02/java-program-to-separate-alphabets-and.html
Then add result to two separate lists List<String> and List<Double> (or probably List<Integers>) or create custom data structure.
You can try this way :
If we consider that the format of your input is a String in which you want to extract integers, then you should to test one element by one:
Main
public static void main(String[] a) {
List<String> myList = new ArrayList<>();
myList.add("fewf5677");
myList.add("kskfj654");
myList.add("pqoen444");
myList.add("mgnwo888");
List<String> listStrings = new ArrayList<>();
List<Integer> listIntegers = new ArrayList<>();
for (int i = 0; i < myList.size(); i++) {
listStrings.add(getStringPart(myList.get(i)));
listIntegers.add(Integer.parseInt(getIntegerPart(myList.get(i))));
}
System.out.println(listStrings);
System.out.println(listIntegers);
}
Get the string part of your element
private static String getStringPart(String str) {
String s = "";
for (int i = 0; i < str.length(); i++) {
if (!testInteger(str.charAt(i))) {
s += str.charAt(i);
} else {
break;
}
}
return s;
}
Get the Integer part of your element
private static String getIntegerPart(String str) {
String s = "";
for (int i = 0; i < str.length(); i++) {
if (testInteger(str.charAt(i))) {
s += str.charAt(i);
}
}
return s;
}
A method to check if your str is and Integer or not
private static boolean testInteger(char str) {
try {
Integer.parseInt(str+"");
return true;
} catch (Exception e) {
return false;
}
}
Output
[fewf, kskfj, pqoen, mgnwo]
[5677, 654, 444, 888]
Hope this can help you.
I have 2 string arrays.
string [] first = {"ajunkbc","ajunkHello","adedbc","abcjunk","add","ad","a","","junk","ajunk","aajunkbb"};
String [] second = {"abc","aHello","adedbc","abcjunk","add","ad","a","","junk","a","aajunkbb"};
I'd like the result of my merge() method to concatenate each element from the first array with the respective element of the second array separated by a comma.
Below is my code
private static String[] merge(String [] tests, String [] expectations){
List<String> testList = Arrays.asList(tests);
List<String> expectationsList = Arrays.asList(expectations);
List<String> retList = new ArrayList<String>();
for(String test : testList){
for(String val : expectationsList){
retList.add(test+","+val);
break;
}
}
This does not work. What's wrong with my code?
What's wrong is that you are looping over expectationsList and breaking out of the loop after the first iteration:
for(String val : expectationsList){
retList.add(test+","+val);
break; //<--- breaking out of loop after first iteration each time
}
So the result is that you are always retrieving the first element of expectationsList.
Since what you want is to loop over two arrays, you should use an index:
for (int i = 0; i < testList.size(); i++) {
retList.add(testList.get(i)+","+expectationsList.get(i));
}
Also, note that this implies that the size of testList is the same as the size of expectationsList. Your method should probably throw an exception if this is not the case.
Note that you do not need to convert the input arrays into lists. You can use them as-is.
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
String[] result = new String[tests.length];
for (int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i]);
}
return result;
}
Java 8 solution:
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
return IntStream.range(0, tests.length).mapToObj(i -> tests[i] + "," + expectations[i]).toArray(String[]::new);
}
You're iterating through each member of testList and then for each one, iterating through each member of expectationsList. You want to iterate through each of both of them together.
What you want to do is something like this:
private static String[] merge(String[] tests, String[] expectations) {
String[] result = new String[tests.length];
for(int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i];
}
return result;
}
This code makes the assumption that tests and expectations have the same length. You might want to do a check for that at the beginning:
if (tests.length != expectations.length) {
throw new IllegalArgumentException("tests and expectations are of different lengths")
}
Notice how now you're getting the element at the same index from both arrays.
Sidenote: You can iterate over arrays with the for each format. This works just fine:
String[] myStringArray = getStringArray();
for (String myString : myStringArray) {
// Do something
}
You don't need to convert to a List in order to iterate :)
I'm trying to find all permutations of a word and add that to an Arraylist and return the array list. But, I believe my recursion is right but, there is a problem with adding the results to the ArrayList.This is what I have so far. The parameters I passed were "eat" and "" and what is returned is "tea" three times
public static ArrayList<String> permutations(String word, String beginning)
{
int l = word.length();
ArrayList<String> temp = new ArrayList<String>();
if(l == 0)
temp.add(beginning + word);
else
{
char c = word.charAt(l-1);
String blah = (beginning + c);
word = word.substring(0, l-1);
for(int i = 0; i < l; i++)
{
permutations(word, blah);
temp.add(blah + word);
}
}
return temp;
}
Probably I didn't have the right idea of your approach to find an easy fix and by the time I got things working I ended up with this. I hope it isn't too much of a departure and that it's still helpful. The output is:
[tea, tae, eta, eat, ate, aet]
import java.util.ArrayList;
public class Perm {
public static void main(String[] args) {
ArrayList<String> perms = new ArrayList<String>();
permutations("tea", perms);
System.out.println(perms);
}
public static ArrayList<String> permutations(String word, ArrayList<String> perms)
{
int l = word.length();
// If the word has only a single character, there is only
// one permutation -- itself. So we add it to the list and return
if (l == 1) {
perms.add(word);
return perms;
}
// The word has more than one character.
// For each character in the word, make it the "beginning"
// and prepend it to all the permutations of the remaining
// characters found by calling this method recursively
for (int i=0; i<word.length(); ++i) {
char beginning = word.charAt(i);
// Create the remaining characters from everything before
// and everything after (but not including) the beginning char
String blah = word.substring(0,i)+word.substring(i+1);
// Get all the permutations of the remaining characters
// by calling recursively
ArrayList<String> tempArray = new ArrayList<String>();
permutations(blah, tempArray);
// Prepend the beginning character to each permutation and
// add to the list
for (String s : tempArray) {
perms.add(beginning + s);
}
}
return perms;
}
}
I need to obtain all combinations of a String of length k from given elements. For example, for
char[] elements = {'a', 'b', 'c'}
k = 4
the output should be: aaaa, aaab, ..., cccc. Now I have the following code which gives proper results BUT isn't fast enough. What can I improve in my code?
public static ArrayList<String> printAllKLength(char[] elements, int nrElements, int patternLength) {
ArrayList<String> patternVariations = new ArrayList<String>();
patternVariations = printAllKLengthRec(elements, "", nrElements, patternLength, patternVariations);
return patternVariations;
}
public static ArrayList<String> printAllKLengthRec(char[] elements, String prefix, int nrElements, int patternLength, ArrayList<String> patternVariations) {
if (patternLength == 0) {
patternVariations.add(prefix);
//System.out.println(prefix);
return patternVariations;
}
for (int i = 0; i < nrElements; ++i) {
String newPrefix = prefix + elements[i];
printAllKLengthRec(elements, newPrefix, nrElements, patternLength - 1, patternVariations);
}
return patternVariations;
}
Thank you!
Try doing it without recursation ... see the explanation here.
recursion versus iteration
I hope this helps you
You can use dynamic programming approach(memorization). Something very similar:
http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/