With much assistance I have developed a method that makes anagrams and then adds them into an ArrayList.
public void f(String s, String anagram, ArrayList<String> array)
{
if(s.length() == 0)
{
array.add(anagram);
return;
}
for(int i = 0 ; i < s.length() ; i++)
{
char l = s.charAt(i);
anagram = anagram + l;
s = s.substring(0, i) + s.substring(i+l, s.length());
f(s,anagram,array);
}
}
The problem is when I attempt to use this function to make ArrayLists in a loop that adds Strings from one ArrayList to another, I get an error saying I can't use a void, and the method f() is void.
List<String> Lists = new ArrayList<String>(); //makes new array list
for(String List : words)
{ //takes values from old array list
List.trim();
Lists.add(f(List,"",new ArrayList<String>())); //this is where it doesn't work
}
Let me clarify once more:
I want to use this function to insert ArrayLists of anagrams into each position in another ArrayList. The anagram Lists are derived from Strings that are being read from one list to another. I tried changing the method to static but that doesn't work, I also removed the return; in the method once, but that doesn't fix it either.
How do I make this whole thing work?
The error happens because the method f() is void, meaning: it doesn't return any value that can be added to the ArrayList.
The answer of invoking f() is stored in the ArrayList passed as a parameter to f, you should probably use that ArrayList to add all of its elements to Lists. Something like this:
List<String> lists = new ArrayList<String>();
for (String list : words) {
list.trim();
ArrayList<String> answer = new ArrayList<String>();
f(list, "", answer);
lists.addAll(answer);
}
Your method header for F needs to look like this:
public String f(String s, String anagram, ArrayList<String> array)
And then you return a String value to add to that ArrayList you are using.
Your function definition for f() shows the return value of type void. So looking at your code you're attempting to do this:
Lists.add(void);
which is obviously illegal.
Your choice really is to have the ArrayList declared in a greater scope.
private List<String> anagrams;
public void f(String s, String anagram) {
...
anagrams.add(anagram);
...
}
....
for(String List : words) {
//takes values from old array list
anagrams = new ArrayList<String>();
List.trim();
f(list,"");
Lists.add(anagrams); //this is where it doesn't work
}
Related
We have to find all simple words from a bunch of simple and compound words. For example:
Input: chat, ever, snapchat, snap, salesperson, per, person, sales, son, whatsoever, what so.
Output should be: chat, ever, snap, per, sales, son, what, so
My sample code:
private static String[] find(String[] words) {
// TODO Auto-generated method stub
//System.out.println();
ArrayList<String> alist = new ArrayList<String>();
Set<String> r1 = new HashSet<String>();
for(String s: words){
alist.add(s);
}
Collections.sort(alist,new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
});
//System.out.println(alist.toString());
int count= 0;
for(int i=0;i<alist.size();i++){
String check = alist.get(i);
r1.add(check);
for(int j=i+1;j<alist.size();j++){
String temp = alist.get(j);
//System.out.println(check+" "+temp);
if(temp.contains(check) ){
alist.remove(temp);
}
}
}
System.out.println(r1.toString());
String res[] = new String[r1.size()];
for(String i:words){
if(r1.contains(i)){
res[count++] = i;
}
}
return res;
}
I am unable to get a solution with the above code. Any suggestions or ideas
compound word = concatenation of two or more words;rest all words are considered as simple words
We have to remove all the compound words
Algorithm
Read the input into a set of Strings i.e. Set<String> input
Create a empty set for simple words i.e. Set<String> simpleWords
Create a empty set for compound words i.e. Set<String> compoundWords
Iterate over input. For each element
Let length of element be elemLength
Create a set Set<String> inputs of all Strings from the set input (excluding element) for which the below is true
Length less than element
Not present in compundWords
Create set of all permutations of inputs(by concatenating) with max length = elemLength i.e. Set<String> currentPermutations
See if any of currentPermutations is = element
If yes, add element into compoundWords
If no, continue with iteration
After the iteration is done place all Strings from input which are not present in compoundWords into simpleWords
That is your answer.
Before you start writing code decide the logic that you are going to use. Use descriptive variable names and you are basically done.
The reason your logic is not working has to do with the way you are checking temp.contains(check). This is checking for substring not a compound word as per your definition.
I am trying to show the list of words which start with the letter specified by the user input.
So for example if I add three words to my list, cat, corn and dog, and the user inputs the letter c, the output on the Java applet should be cat, corn.
However, I have no idea on how to go about this.
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1 ){
x = textf.getText();
wordList.add(x);
textf.setText(null);
}
if (e.getSource() == b2 ){
}
}
b1 is adding all the user input into a secretly stored list, and I now want to make another button when pressed to show the words that start with the specified letter by the user.
textf = my text field
wordList = my list I created
x = string I previously defined
You could loop through all the possible indices, check if the element at that index starts with the letter, and print it if it does.
ALTERNATIVE (and probably better) code (I was going to put this after, but since its better it deserves to be first. Taken form #larsmans's answer here.
//given wordList as the word list
//given startChar as the character to search for in the form of a *String* not char
for (String element : wordList){
if (element.startsWith(startChar)){
System.out.println(element);
}
}
DISCLAIMER: This code is untested, I don't have much experience with ArrayList, and Java is more of a quaternary programming language for me. Hope it works :)
//given same variables as before
for (int i = 0; i < wordList.size(); i++){
String element = wordList.get(i);
//you could remove the temporary variable and replace element with
// wordList.get(i)
if (element.startsWith(startChar){
System.out.println(element);
}
}
You can try something like this -
public static void main(String[] args) {
String prefix = "a";
List<String> l = new ArrayList<String>();
List<String> result = new ArrayList<String>();
l.add("aah");
l.add("abh");
l.add("bah");
for(String s: l) {
if(s.startsWith(prefix)) {
result.add(s);
}
}
System.out.println(result);
}
Result is -
[aah, abh]
If you can use Java 8 then you can build in features to filter your list:
public static void main(String[] args) throws Exception {
final List<String> list = new ArrayList<>();
list.add("cat");
list.add("corn");
list.add("dog");
System.out.println(filter(list, "c"));
}
private static List<String> filter(final Collection<String> source, final String prefix) {
return source.stream().filter(item -> item.startsWith(prefix)).collect(Collectors.toList());
}
This uses the filter method to filter each list item which starts with the String of the prefix argument.
The output is:
[cat, corn]
I have a List of Strings, and most of them are multiple words:
"how are you"
"what time is it"
I want to remove the space from every string in this list:
"howareyou"
"whattimeisit"
I know of the Collections.replaceAll(list, to replace, replace with), but that only applies to Strings that are that exact value, not every instance in every String.
What you must is to apply the replace function to each of the string in your list.
And as the strings are immutable you will have to create another list where string with no space will be stored.
List<String> result = new ArrayList<>();
for (String s : source) {
result.add(s.replaceAll("\\s+", ""));
}
Immutable means that object can not be changed, it must be created new one if you want to change the state of it.
String s = "how are you";
s = s.replaceAll("\\s+", "");
The function replaceAll returns the new string if you did not assign it to variable s then would still have spaces.
It doesn't sound very useful.
But try this:
import java.util.Arrays;
import java.util.List;
/**
* http://stackoverflow.com/questions/20760578/how-do-i-replace-characters-in-every-string-in-my-list-in-java/20760659#20760659
* Date: 12/24/13
* Time: 7:08 AM
*/
public class SpaceEater {
public static void main(String[] args) {
List<String> stringList = Arrays.asList(args);
System.out.println("before: " + stringList);
for (int i = 0; i < stringList.size(); ++i) {
stringList.set(i, stringList.get(i).replaceAll("\\s+", ""));
}
System.out.println("after : " + stringList);
}
}
disrvptor was correct - original snippet did not alter the list. This one does.
You can try this:
No need to define new array list. Use list.set this set replaces the element at the specified position in this list with the specified element.
int i = 0;
for (String str : list)
{
list.set(i, str.replaceAll(" ", ""));
i++;
}
Output
for (String s : list)
{
System.out.println(s);
}
//Thisisastring
//Thisisanotherstring
The only way I know how to do this is to iterate over the list, perform the replace operation on every object and replace the original object with the new one. This is best handled with 2 lists (source and target).
Hey guys I'm trying to get the concept of recursion down by making a program that generates String of an ArrayList recursively. My basic algorithm is:
public static ArrayList<String> generateListOfAll1sStrings(int maxBits)
terminal condition: if maxBits is 1, return the simplest case: a list containing just "1"
otherwise:
recursively call generateListOfAll1sStrings() for the next-smallest bit-length, saving the list that is returned
find the longest string in that list and create a new string with "1" appended to it (making the next-longest string)
return a new list that contains all the elements of the shorter list along with the new string just added.
The code I have so far is:
package bincomb.model;
import java.util.ArrayList;
public class BinaryCombinationGenerator {
public static ArrayList<String> generateListOfAll1sStrings(int maxBits) {
String string = null;
ArrayList<String> listofJust1 = new ArrayList<String>();
ArrayList<String> otherArray = new ArrayList<String>();
int i = 1;
if (maxBits == 1) {
listofJust1.add("1");
return listofJust1;
}
if (maxBits > 1) {
for (String string2 : listofJust1) {
String comp = "";
if (!(comp.equals(string2))) {
comp = string2;
}
string = comp;
}
listofJust1.add(i, (string + "1"));
i++;
listofJust1 = BinaryCombinationGenerator.generateListOfAll1sStrings((maxBits-1));
System.out.println(listofJust1);
return listofJust1;
}
return listofJust1;
}
public static void main(String[] args) {
generateListOfAll1sStrings(10);
}
}
However, currently, I'm returning an IndexOutOfBoundsException. I think my for loop is causing the problem, but I'm not certain how to go about fixing it.
You're getting an java.lang.IndexOutOfBoundsException at this line listofJust1.add(i, (string + "1"));.
This is because the method list.add(index, objects) tries to add the object at index "1" but your array has 0 elements.
Either change it to listofJust1.add(i-1, (string + "1")); or simply listofJust1.add((string + "1"));
#Edit: here:
listofJust1.add(i, (string + "1"));
You want to add the string for the current (N) level of recursion but below you substitute this array with:
listofJust1 = BinaryCombinationGenerator.generateListOfAll1sStrings((maxBits-1));
Which basically says "get the result for (maxBits-1) and replace with it listofJust1" therefore you are losing what you added before.
Instead you should first get the list for level N-1 and then add the string for the current level:
listofJust1 = BinaryCombinationGenerator.generateListOfAll1sStrings((maxBits-1));
listofJust1.add(stringForThisLevel);
Also you need to rething how you are computing "string" at level N, doesn't seem right.
I have an arraylist of Strings that want to have all possible combinations stored into another collection.
For example:
[air,bus,car]
->
[air]
[bus]
[car]
[air,bus]
[air,car]
[bus,air]
[bus,car]
[car,air]
[car,bus]
[air,bus,car]
[air,car,bus]
...
[car,bus,air]
Repetitions are not important. The code right now I have is:
public ArrayList<String> comb(ArrayList<String> wrds, ArrayList<String> str, int size)
{
ArrayList<String> s = new ArrayList<String>();
s.addAll(str);
if(size != a1.size())
{
Iterator e = a1.iterator();
while(e.hasNext())
{
s.add((String)e.next());
}
size++;
}
}
I am trying to get it to recursively call itself so it can store the combinations. Can I get any help as to where or which part I am missing in my code?
Seeing as this is homework, I'll try to give you background to the answer.
The key to solving this is to use recursion.
First imagine you have two items in your array. You'd could remove the first item to give you your first combination. Adding the remaining item to the first item gives you the second combination. Removing the second item give you the third combination. Adding the remaining item gives you the forth combination. If you had ["air", "bus"] it'd be something like:
["air"]
["air", "bus"]
["bus"]
["bus", "air"]
A method that returns that might look like:
String[][] combinations(String[] strings)
The important things to note are the an array containing a single string can be passed to this method and it can return an array containing an array with a single string in it.
The problem is complicated a little because you have to keep a tally of the string combinations, so before we get to solving that, it's important that you understand recursion.
Imagine you wanted to write a multiplication method that takes two numbers and multiplies them but you only have addition and subtraction at your disposal. You could write a recursive function that adds one of the numbers to itself until the other number reaches an exit condition, something like:
public int multiply(int value1, int value2)
{
if (value1 > 1)
{
int remaining = value1 - 1;
return value2 + multiply(remaining, value2);
}
else
{
return value2;
}
}
You can do just the same thing with an array, only instead to exiting when the a value hit's 1 you exit when the array contains one item, something like:
public String[][] combinations(String[] strings)
{
if (strings.length > 1)
{
...
}
else
{
return new String[][]{strings};
}
}
For reasons with the Java API it's much easier to use java.util.List rather than arrays so you want something like:
public List<List<String>> combinations(List<String> strings)
{
if (strings.size()> 1)
{
...
}
else
{
List<List<String>> result = new ArrayList<List<String>>();
result.add(strings);
return result;
}
}
Now it's the ... that's the important bit. You need to keep an list-of-lists that will be the result and iterate over the strings. For each of the strings you can add that string to the results and then you need create a sub-list that is minus the current string, which you use to call the combinations method again iterating over the result adding the current string each list it contains. In code it looks something like:
public List<List<String>> combinations(List<String> strings)
{
if (strings.size() > 1)
{
List<List<String>> result = new ArrayList<List<String>>();
for (String str : strings)
{
List<String> subStrings = new ArrayList<String>(strings);
subStrings.remove(str);
result.add(new ArrayList<String>(Arrays.asList(str)));
for (List<String> combinations : combinations(subStrings))
{
combinations.add(str);
result.add(combinations);
}
}
return result;
}
else
{
List<List<String>> result = new ArrayList<List<String>>();
result.add(new ArrayList<String>(strings));
return result;
}
}
In summary, what you're doing is reducing the list of strings down to a single item, then combining it with the preceeding items to produce all the possible combinations as the thread returns up the call stack.
public static void combination(Object[] array){
for(int x = 0; x < (1 << array.length); x++){
System.out.print("[");
for(int y = 0; y < array.length; y++){
if(checkIsOn(x, y){
System.out.print(array[y]);
}
}
System.out.println("]");
}
}
public static boolean checkIsOn(int mast, int position){
return (mast & (1 << position) > 0);
}
Use the list as a parameter to the recursive function. You can call the function from within itself with a new list containing everything except the first item.