I have a simple program here which is meant to find all permutations of a set of letters, or a set of words. From what I can see the program does work in finding the number of permutations there are, however it will only print blank lines in place of where the possible permutations should be.
(Note, UI.println() works in every other case in printing outlines, but for some reason will not work here :( )
I included my method here which should do as I've described, as well as a method that should be able to print out the permutations.
Would anyone have any ideas on what I have done wrong here?
public class Permutations {
public List<List<String>> findPermutations(Set<String> items){
Set<String> copyOfItems = new HashSet<String>(items); // a copy of the set of items that can be modified
List<List<String>> ans = new ArrayList<List<String>>(); // where we will collect the answer
counter=0;
//suggested approach:
extendPermutation(copyOfItems, new Stack<String>(), ans);
return ans;
}
public void extendPermutation(Set<String> remainingItems, Stack<String> permutationSoFar, List<List<String>> allPermutations){
/*# YOUR CODE HERE */
Set<String> alternateSet = new HashSet<String>(remainingItems);
if (remainingItems.isEmpty()) {
allPermutations.add(permutationSoFar);
this.counter = counter + 1;
}
for (String str : remainingItems) {
alternateSet.remove(str);
permutationSoFar.push(str);
extendPermutation(alternateSet,permutationSoFar,allPermutations);
permutationSoFar.pop();
}
}
public void setupGUI(){
UI.addButton("A B C D E", ()->{printAll(findPermutations(Set.of("A","B","C","D","E")));});
UI.addTextField("Letters", (String v)->{printAll(findPermutations(makeSetOfLetters(v)));});
UI.addTextField("Words", (String v)->{printAll(findPermutations(makeSetOfWords(v)));});
UI.addButton("Quit", UI::quit);
UI.setDivider(1.0);
}
public void printAll(List<List<String>> permutations){
UI.clearText();
for (int i=0; i<permutations.size(); i++){
for (String str : permutations.get(i)){UI.print(str+" ");}
UI.println();
}
UI.println("----------------------");
UI.printf("%d items:\n", permutations.get(0).size());
UI.printf("%,d permutations:\n", counter);
UI.println("----------------------");
}
public Set<String> makeSetOfLetters(String str){
Set<String> ans = new HashSet<String>();
for (int i=0; i<str.length(); i++){
if (str.charAt(i)!=' '){
ans.add(""+str.charAt(i));
}
}
return Collections.unmodifiableSet(ans);
}
public Set<String> makeSetOfWords(String str){
Set<String> ans = new HashSet<String>();
for (String v : str.split(" ")){ans.add(v);}
return Collections.unmodifiableSet(ans);
}
// Counter for the number of complete permutations found
private long counter = 0;
public void reportCounter(){
if ((counter<<54)==0) {UI.printMessage((counter>10000000)?((counter>>>20)+"M"):((counter>>>10)+"K"));}
}
// Main
public static void main(String[] arguments) {
Permutations p = new Permutations();
p.setupGUI();
}
}
Your code
permutationSoFar.push(str);
extendPermutation(alternateSet, permutationSoFar, allPermutations);
permutationSoFar.pop();
You first add an item to the permutationSoFar,
then you add a refrence (not a deep copy) the permutationSoFar to your allPermutations, only to pop permutationSoFar. Making sure that your permutationSoFar never contains any elements.
When you print the list of permutationSoFars, the allPermutations, you print an list of empty lists.
Just glancing over your problem, this will likely solve the issue:
allPermutations.add(List.copyOf(permutationSoFar));
But, to be blunt, it is like the rest of your code, not the cleanest solution.
Related
In the code given below I am adding the a particular permutation of ArrayList in the function permute but while printing in the main function all possible permutations are not printed. Instead, the same ArrayList<String> is printed n! times where n is length of given ArrayList<String>.
I am adding the permutations in set(my global variable) in permute function as set.add(names) but while printing it in main function it gives output as the same unarranged Arraylist.
import java.util.*;
public class Q1 {
static Set<ArrayList<String>> set = new HashSet<>(); ;
public static void main(String args[]) {
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
ArrayList<String> names = new ArrayList<String>();
for(int i=0;i<n;i++) {
String temp;
temp = in.next();
names.add(temp);
}
System.out.println(set.size());
permute(names,0,names.size()-1);
System.out.println(set.size());
for(ArrayList<String> i : set) {
System.out.println(i);
}
}
public static void permute(ArrayList<String> names , int l, int r) {
if(l==r) {
if(set.contains(names)) {
return;
}
set.add((ArrayList<String>)names);
//System.out.println(names);
return;
}
for(int i=l;i<=r;i++) {
Collections.swap(names,l ,i);
permute(names , l+1, r);
Collections.swap(names,l,i);
}
}
}
You are repeatedly adding the same object names to set. But you need to add a copy of names.
set.add((ArrayList<String>)names);
→
set.add(new ArrayList<>(names));
today I learn to write code puzzle word in java. I stress with search word in a list and I want to search it only (Vertical,horizontal) but not diagonal. My code is not gave me error and result. and can you help me to refresh it.
public class WordPuzzle {
private final String puzzleString[][];
private final int rowNumber;
public WordPuzzle(String[][] puzzleString,int rowNumber){
this.puzzleString=puzzleString;
this.rowNumber=rowNumber;
}
public void showPuzzle(){
for(int i=0;i<rowNumber;i++){
for(int j=0;j<rowNumber;j++){
System.out.print(" "+puzzleString[i][j]);
}
System.out.println();
}
}
public Set<String> searchWord(Set<String> word){
Set<String> foundWord=new HashSet<String>();
int minimumWordLength=findMinimumWordLenght(word);
Set<String>compWord=CompatitableWord(minimumWordLength);
for(String w:word){
for(String posibleWord:compWord){
if(posibleWord.contains(w) || posibleWord.contains(new StringBuffer(w).reverse())){
foundWord.add(w);
break;
}
}
}
return foundWord;
}
private int findMinimumWordLenght(Set<String> wordLength){
int minimumLenght=Integer.MAX_VALUE;
for(String w:wordLength){
if(w.length()<minimumLenght){
minimumLenght=w.length();
}
}
return minimumLenght;
}
private Set<String> CompatitableWord(int minimumWordLength){
Set<String>compWord=new LinkedHashSet<String>();
int puzzleLength=puzzleString.length;
if(puzzleLength>=minimumWordLength){
for(int i=0;i<puzzleLength;i++){
if(puzzleString[i].length>=minimumWordLength){
compWord.add(new String(puzzleString[i].toString()));
}
}
for(int i=0;i<puzzleLength;i++){
StringBuffer tmp=new StringBuffer();
for(int j=0;j<puzzleLength;j++){
tmp=tmp.append(puzzleString[j][i]);
}
compWord.add(new String(tmp));
}
}
return compWord;
}
public static void main(String[] args){
String[][] a={{"g","y","r","a","r","b","i","l","e"},
{"u","a","a","n","c","h","o","r","i"},
{"i","b","y","d","v","e","x","t","r"},
{"t","z","c","h","y","n","e","q","u"},
{"a","m","a","n","g","o","d","v","q"},
{"r","n","i","h","p","l","o","d","l"},
{"f","o","r","e","s","t","u","d","y"},
{"j","d","l","w","a","r","c","h","u"},
{"h","a","v","g","h","y","e","t","y"}
};
WordPuzzle pn=new WordPuzzle(a,9);
pn.showPuzzle();
Set<String> str=new HashSet<String>();
str.add("library");
Set<String>wordFound=pn.searchWord(str);
for(String w:wordFound){
System.out.println("Found"+pn.searchWord(str));
}
}
}
You can rewrite your program, because it is so complex and hardly. First, replace strings to chars: you should have matrix of char, char[][] mat. Second, save all rows and columns to String:
String[] rows = ... // use new String(mat[i])
String[] columns = ... // transform matrix and see solution for rows
After this, use rows[i].indexOf or columns[i].indexOf.
Also, you can use rows[i].reverse().indexOf or columns[i].reverse().indexOf.
Sorry for my bad English
In this method I am trying to compare all the elements in one arraylist to all the elements in another. Then, if an element in the first arraylist does not equal any element in the second arraylist, delete that element. Something is wrong in either the comparison step or the deletion step, but I am not sure which. Any help would be greatly appreciated.
If you want clarification, don't hesitate to ask.
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
int[] counter = new int[compare.size()];
for (int x: counter) {
x = 0;
}
for (int i = 0; i < compare.size(); i++) {
counter[i] = 0;
for (int number: array2) {
if (compare.get(i) ==number) {
counter[i]++;
}
}
}
for (int i=0; i<counter.length;i++) {
if (counter[i]==0) {
compare.remove(new Integer(i));
}
}
return compare;
}
EDIT: (courtesy of Memento Mori)
The reason your code is not working is that the positions in your ArrayList are changing when you remove an element. Lets say you removed element 3. Now element 3 is different than it was before.
public class Test {
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
ArrayList<Integer> a3 = new ArrayList<Integer>();
for (Integer a : compare)
{
if(array2.contains(a))
a3.add(a);
}
System.out.println(a3);
return a3;
}
public static void main(String[] args) {
ArrayList<Integer> a1=new ArrayList<Integer>();
ArrayList<Integer> a2=new ArrayList<Integer>();
a1.add(1);
a1.add(5);
a1.add(3);
a2.add(3);
a2.add(4);
a2.add(5);
a2.add(6);
Test test=new Test();
test.compareArrayandList(a1,a2);
}
}
You are not doing what you really want to do here. You remove the element(s) which its value is i from the compare array instead of the element at position i which is not find in the second for loop.
for (int i=0; i<counter.length;i++) {
if (counter[i]==0) {
//compare.remove(new Integer(i)); // problem is here!
// remove element at index i not element equals to i
compare.remove(i);
}
}
You don't need your counter array. You can do the comparison in one step if you use an iterator. I believe this should work:
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
ListIterator<Integer> iter = compare.listIterator(compare.size());
while (iter.hasPrevious()){
Integer a = new Integer(iter.previous());
for (int number: array2) {
if (a==number) iter.remove();
}
}
return compare;
}
EDIT: The reason your code is not working is that the positions in your ArrayList are changing when you remove an element. Lets say you removed element 3. Now element 3 is different than it was before.
ListUtils.sum(Arrays.asList(firstarray),Arrays.asList(secondarray))
I've written a method that has some casting errors:
public class Factor {
public static int[] findFactors(ArrayList<Integer> nums){
ArrayList<Integer> factors= new ArrayList();
for(Integer i=new Integer(0);i<nums.size();i++) {
System.out.println(nums.get(i));
for(int j=0;j<nums.get(i);j++) {
if (nums.get(i) %j==0) {
factors.add(j);
}
}
}
int ct=0;
String factorString= factors.toString();
char[] charArray= factorString.toCharArray();
int[] factorArray= new int[(charArray.length+1)/2];
for(int a=0;a<charArray.length;a++) {
if(charArray[a]==',') {
continue;
} else {
String s= Character.toString(charArray[a]);
factorArray[ct]=Integer.parseInt(s);
ct++;
}
}
return factorArray;
}
}
any help would be appreciated
The problem you have that you only escape the , but when you use toString() on a List it is enclose in square brackets []. When you fix that you will discover that size of result array is not valid also you have to subtract 2 (the brackets).
Good Luck with rest. And please read some basic manual about Java.
This is a pice of my code :
ArrayList<String> Alist= new ArrayList<String>();
ArrayList<String> Blist= new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
so i have two array list i want to compare all items and check if they are not equal and if they are to print out only the items that are not equal.
so i make something like this:
http://postimage.org/image/adxix2i13/
sorry for the image but i have somekind of bug when i post here a for looop.
and the result is :
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
i want to print only the 2 that are not equal in the example they are gsm and pc
not equals..:gsm
not equals..:pc
Don't use != to compare strings. Use the equals method :
if (! Blist.get(i).equals(Alist.get(j))
But this wouldn't probably fix your algorithmic problem (which isn't clear at all).
If what you want is know what items are the same at the same position, you could use a simple loop :
int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size());
for (int i=0; i<sizeOfTheShortestList; i++) {
if (Blist.get(i).equals(Alist.get(i))) {
System.out.println("Equals..: " + Blist.get(i));
}
}
If you want to get items that are in both lists, use
for (int i = 0; i < Alist.size(); i++) {
if (Blist.contains(Alist.get(i))) {
System.out.println("Equals..: " + Alist.get(i));
}
}
You can use the RemoveAll(Collection c) on one of the lists, if you happen to know if one list always contains them all.
You could use the following code:
ArrayList<String> Alist = new ArrayList<String>();
ArrayList<String> Blist = new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
for (String a : Alist)
{
for (String b : Blist)
{
if (a.equals(b))
{
System.out.println("Equals " + a);
break;
}
}
}
Output is:
Equals gsm
Equals pc
right now your comparing each element to all of the other ones. Do something like
for (int i = 0; i < Alist.size(); i++) {
if (!Alist.get(i).equals(Blist.get(i)) {
// print what you want
}
}
Thats of course assuming both lists have the same length.
Rather than writing code to manually compare list elements you might consider using Apache Commons Collections.
import org.apache.commons.collections.CollectionUtils;
List listA = ...;
List listB = ...;
Collection intersection = CollectionUtils.intersection(listA, listB);
import java.util.HashSet;
public class CheckSet<T> extends HashSet<T>{
#Override
public boolean add(T e) {
if (contains(e)) {
remove(e);
return true;
} else {
return super.add(e);
}
}
}
Add all elements of both of your lists to a CheckSet intance, and at the end it will only contain the ones not equal.
Here is one way:
public static boolean compare(List<String> first, List<String> second) {
if (first==null && second==null) return true;
if (first!=null && second==null) return false;
if (first==null && second!=null) return false;
if ( first.size()!=second.size() ) return false;
HashMap<String, String> map = new HashMap<String, String>();
for (String str : first) {
map.put(str, str);
}
for (String str : second) {
if ( ! map.containsKey(str) ) {
return false;
}
}
return true;
}
public static void main(String args[] ) throws Exception {
List<String> arrayList1 = new ArrayList<String>();
arrayList1.add("a");
arrayList1.add("b");
arrayList1.add("c");
arrayList1.add("d");
List<String> arrayList2 = new ArrayList<String>();
arrayList2.add("a");
arrayList2.add("b");
arrayList2.add("c");
arrayList2.add("d");
boolean isEqual = false;
if(arrayList1.size() == arrayList2.size()){
List<String> arrayListTemp = new ArrayList<String>();
arrayListTemp.addAll(arrayList1);
arrayListTemp.addAll(arrayList2);
HashSet<Object> hashSet = new HashSet<Object>();
hashSet.addAll(arrayListTemp);
if(hashSet.size() == arrayList1.size() &&
hashSet.size() == arrayList2.size()){
isEqual = true;
}
}
System.out.println(isEqual);
}
we can compare two different size arrayList in java or Android as follow.
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
array1.add("1");
array1.add("2");
array1.add("3");
array1.add("4");
array1.add("5");
array1.add("6");
array1.add("7");
array1.add("8");
array2.add("1");
array2.add("2");
array2.add("3");
array2.add("4");
for (int i = 0; i < array1.size(); i++) {
for (int j=0;j<array2.size();j++) {
if (array1.get(i) == array2.get(j)) {
//if match do the needful
} else {
// if not match
}
}
}
import java.util.Arrays;
public class ExampleContains {
public static boolean EligibleState(String state){
String[] cities = new String[]{"Washington", "London", "Paris", "NewYork"};
boolean test = Arrays.asList(cities).contains(state)?true:false;
return test;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(EligibleState("London"));
}
}