Finding permutations of a linked list [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a linked list that I'm trying to generate all permutations of.
The link list is made of ListNode objects that simply contain an integer and a reference to the next ListNode.
I'm trying to do something like this:
public void generatePermutatoins(ListNode head) {
//code that generates permutations
//let's say it finds a permutation and stores the entire list in
//ListNode singlePermutation;
//printList(singlePermutation);
}
I'm wondering if there is a recursive solution as well? I'm quite stuck on any solution, though.

Yes you can do it recursively easily if you define your problem correctly.
You have a linked list and a reference to the head of the list. You have a function that recursively creates all the permutations of all elements after head.
When you get the result you go over each permutation and you add head in each position generating the last permutation.
If you haven't figured it out this was your recursive function. The following is a skeleton/pseudo code in Java to get you started. The addEachPosition(permutation, node.value); adds the value in all possible positions in the list
public List<List<Integer>> getPermutations(ListNode currentNode) {
if(currentNode == null) {
return new ArrayList<ListNode>();
}
List<List<Integer>> nextPermutations = getPermutations(currentNode.next);
addToPermutations(currentNode, nextPermutations);
return nextPermutations;
}
public void addToPermutations(ListNode node, List<List<Integer>> permutations) {
for(List<Integer> permutation:permutations) {
addEachPosition(permutation, node.value);
}
}

This non-recursive (iterative) implementation might be helpful: Collections2.permutations.

Related

More efficient way to get the intersection between 2 or more nested ArrayLists [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
If I had, say separate 3 nested ArrayLists of Strings, i.e., ArrayList<ArrayList<String>>:
What is the most efficient way of finding their intersection (common elements)?
Are there other data structures to replace the nested ArrayLists structure that could improve the efficiency of finding their intersection? (e.g. The first structure I can think of is using a Set, but I would like to see if there are other suggestions for this.)
Thanks in advance!
The intersection of two lists is done using the retainAll() method.
It update the list, so if you don't want that, you should copy the list first.
If you have more than 2 lists, you copy the first and then call retainAll() for each of the remaining lists.
ArrayList<ArrayList<String>> lists = ...
List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
intersection.retainAll(list);
However performance will be a bad O(n*m), where n and m are the sizes of the two largest lists.
That is because retainAll() does a contains() against the list given in the parameter, which is a sequential search, for each element in the intersection list.
Performance can be improved to O(n), where n is the largest list, by converting the lists to sets.
List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
intersection.retainAll(new HashSet<>(list));
In Java 8+, the for loop can be simplified to one of these:
lists.subList(1, lists.size()).stream().map(HashSet::new).forEach(intersection::retainAll);
lists.subList(1, lists.size()).forEach(list -> intersection.retainAll(new HashSet<>(list)));
i would use the list.retainAll method as in
private ArrayList<String> getIntersection(ArrayList<ArrayList<String>> lists) {
if(null == lists || lists.isEmpty()) {
return null;
}
ArrayList<String> intersection = lists.get(0);
lists.forEach(intersection::retainAll);
return intersection;
}

Java .set for lists? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am learning the basics of lists in Java and I was wondering what .set did I already understand the concept of .add however I cant really find anything about .set and its relation to lists other then examples. I would really appreciate if someone could give me some insight on this command.
Set will specify the position in the List for the object you are storing. The List inteface represents an ordered collection of objects so the position is able to be changed. Similar to an array.
Look at the section Positional Access and Search Operators on: http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
set(pos, elem) as per the Java docs:
Replaces the element at the specified position in this list with the
specified element.
This means that you can change the stored element/reference at a specific position in the list, as long as the position is within the allowed position bounds. So, if you have 3 elements within the list already, you can specify position in set(position,element) to a value between 0 and 2, inclusive. Here is a simple demonstration of how you can replace the 1th (so really the 2nd, as it's 0-indexed) element in an ArrayList and then set it back to the original value:
import java.util.ArrayList;
public class Foo {
public static void main(String[] args) throws Exception {
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
System.out.println(foo);
foo.set(1, 999);
System.out.println(foo);
foo.set(1, 1);
System.out.println(foo);
}
}
But really, this is explained more than clearly enough in the Java doc for List, so as others have said: read it and try it out next time.

Parse Java tree structure while nodes can contain ArrayList's [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have started an implementation of a Java tree structure:
Root(Key, Value) --> NODE1(Key, Value)
--> NODE2(Key, Value)
--> NODE3(Key, Value) --> NODE4(Key, Value)
--> NODE5(Key, Value)
--> ...
So here you can see that the root node can contain an undefined number of children and this children can contain also an undefined number of children.
So now my question is, how to find NODE5 with only given the key and starting at the root node?
(Remember: This tree can be really big!)
You need to walk through the tree and check every child. This could be done via recursion. Try something similar like this:
public Node getNode(Key key, List<Node> children) {
if (children != null) {
for (Node child : children) {
if (child.getKey().equals(key)) {
return child;
} else {
return getNode(key, child.getChildren());
}
}
}
}
If your tree is unsorted you have to look in the whole tree. There are common ways how to do this. It is called (traversal). There are 3 ways (Pre/In/Post order). Normaly you implement such behavior as a recursive function.

Best algorithm to find an element in an ordered list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
There is list A which contains numbers in ascending order.
Similarly a list B which also contains numbers in ascending order.
The result should be list C which contains numbers from A which are not in B.
My Solution:
I iterated through A and checked for the number in B using .contains() and added the required elements in C.
I was told using .contains() is higher order of complexity O(n).
Does anyone have a better solution?
Yes, your method will get O(n^2). The idea to get O(n) is just like merging two sorted lists into one. Merging two sorted lists into one is a Union. Finding common elements in two sorted lists is an Intersection. Your problem is to find the set difference of two sorted lists. Drawing a simple example on paper, you will find you can use two iterators to do it in O(n) time.
Use Merge Sort like merge routine to add element from A lists into C using following conditions:-
if (B->data<A->data) just iterate B
if(B->data==A->data) iterate A & B
if(A->data<B->data) Add A->data to C and iterate A
Time complexity O(N)

How to remove Object in Java List? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have one existing code, where the written line is
private Rule[] ruleList;
Where Rule is a CLASS.
I want to remove all Rules which are added here in ruleList.
but as I click right it shows like this
If it is a List, how can I delete these rules from ruleList?
Thanks
The ruleList is an array and not a List. Thus you will not find a clear method.
But you can use
Arrays.fill(ruleList, null);
You have an array and not a list. Solution :
ruleList = new Rule[ruleList.length];
To remove all items from a List use clear()
If you want to remove all items in an array from a List use the remove method.
Example
public class Rules {
public static void main(String[] args) {
Rule[] rules = new Rule[2];
rules[0] = new Rules.Rule();
rules[1] = new Rules.Rule();
//Scenario 1
List<Rule> ruleList = new ArrayList<Rule>();
ruleList.add(Arrays.asList(rules)); //adds array to list
ruleList.clear(); //removes all items from List
//Scenario2
ruleList.add(Arrays.asList(rules)); //adds array to list
ruleList.remove(Arrays.asList(rules)); //remove all rules in [] form list
//Scenario3
Arrays.fill(rules, null); //removes all elements in array
}
static class Rule{
}
}
It is important to determine whether you are using a List or an Array. The provided code depicts an array, however the verbiage keeps referring to a List.
If you actually have a List and want to remove all elements see Scenario 1 in the example.
If you actually have a List and want to remove all elements in the array from the List see Scenario 2 in the example.
If you actually have array and want to remove all elements from the array see Scenario 3 in the example.

Categories