Permutations of ArrayList<Integer> - java

im working on a problem where i have to obtain all permutations of an arraylist of numbers. The only restriction is that any number cant start with 0, so if we have [0,1,2] we would obtain
[1,2,0]
[1,0,2]
[2,0,1]
[2,1,0]
i know how to do this with 3 loops but the thing is that i have to repeat this to different sets of numbers with differentes sizes, so i need one method that i can apply to different sets of numbers but i have no clue on how to do this. I imagine i have to used some kind of recursive function but i dont know how to implement it so the numbers cant start with a 0. Any ideas? please dont just post the code i want to understand the problem, thank you in advantage!!

Curious question! Interesting code kata.
I naively think I would have a recursive method that takes:
a list of the items currently chosen by the caller
a set of the items available for the callee
The method would iterate over the set to chose 1 more item and call itself with the list extended by this item, and the set reduced by this item. Upon return, remove from list, add back to set and go on with next item (take a defensive copy of the set of course).
If the current list is empty, the selected first item cannot be 0, as per your rules. If you must collect the permutations somewhere (not just print), a 3rd argument would be required for a collection or an observer.
The recursion obvioulsy stops when the available set is empty, at which point the permutation is sent to the collection or observer.
If items can repeat, you may have benefit from sorting them first in order to skip electing the same item again at a given position.
Beware this quires a recursion depth of N, for N items. But the danger is minimal because even with N=10000, it may not stackoverflow, but the CPU time to complete would be order(N!) (probably end of universe...)

You could solve this recursively as described here: Permutation of an ArrayList of numbers using recursion.
The only thing that is missing there is your restriction with the zeros, which could be solved somehow like this (the loop is taken from the example above):
for (List<Integer> al : myLists) {
// The part you need to add:
if (al.get(0) == 0) {
continue;
}
String appender = "";
for (Integer i : al) {
System.out.print(appender + i);
appender = " ";
}
System.out.println();
}
You basically check the first element of each permutation and skip the ones with a leading zero. The continue jumps to the next iteration of the loop and therefore to the next permutation.

Related

Efficient way for checking if a string is present in an array of strings [duplicate]

This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 2 years ago.
I'm working on a little project in java, and I want to make my algorithm more efficient.
What I'm trying to do is check if a given string is present in an array of strings.
The thing is, I know a few ways to check if a string is present in an array of strings, but the array I am working with is pretty big (around 90,000 strings) and I am looking for a way to make the search more efficient, and the only ways I know are linear search based, which is not good for an array of this magnitude.
Edit: So I tried implementing the advices that were given to me, but the code i wrote accordingly is not working properly, would love to hear your thoughts.`
public static int binaryStringSearch(String[] strArr, String str) {
int low = 0;
int high = strArr.length -1;
int result = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (strArr[mid].equals(str)) {
result = mid;
return result;
}else if (strArr[mid].compareTo(str) < 0) {
low = mid + 1;
}else {
high = mid - 1;
}
}
return result;
}
Basically what it's supposed to do is return the index at which the string is present in the array, and if it is not in the array then return -1.
So you have a more or less fixed array of strings and then you throw a string at the code and it should tell you if the string you gave it is in the array, do I get that right?
So if your array pretty much never changes, it should be possible to just sort them by alphabet and then use binary search. Tom Scott did a good video on that (if you don't want to read a long, messy text written by someone who isn't a native english speaker, just watch this, that's all you need). You just look right in the middle and then check - is the string you have before or after the string in the middle you just read? If it is already precisely the right one, you can just stop. But in case it isn't, you can eliminate every string after that string in case it's after the string you want to find, otherwise every string that's before the just checked string. Of course, you also eliminate the string itself if it's not equal because - logic. And then you just do it all over again, check the string in the middle of the ones which are left (btw you don't have to actually delete the array items, it's enough just to set a variable for the lower and upper boundary because you don't randomly delete elements in the middle) and eliminate based on the result. And you do that until you don't have a single string in the list left. Then you can be sure that your input isn't in the array. So this basically means that by checking and comparing one string, you can't just eliminate 1 item like you could with checking one after the other, you can remove more then half of the array, so with a list of 256, it should only take 8 compares (or 9, not quite sure but I think it takes one more if you don't want to find the item but know if it exists) and for 65k (which almost matches your number) it takes 16. That's a lot more optimised.
If it's not already sorted and you can't because that would take way too long or for some reason I don't get, then I don't quite know and I think there would be no way to make it faster if it's not ordered, then you have to check them one by one.
Hope that helped!
Edit: If you don't want to really sort all the items and just want to make it a bit (26 times (if language would be random)) faster, just make 26 arrays for all letters (in case you only use normal letters, otherwise make more and the speed boost will increase too) and then loop through all strings and put them into the right array matching their first letter. That way it is much faster then sorting them normally, but it's a trade-off, since it's not so neat then binary search. You pretty much still use linear search (= looping through all of them and checking if they match) but you already kinda ordered the items. You can imagine that like two ways you can sort a buncha cards on a table if you want to find them quicker, the lazy one and the not so lazy one. One way would be to sort all the cards by number, let's just say the cards are from 1-100, but not continuously, there are missing cards. But nicely sorting them so you can find any card really quickly takes some time, so what you can do instead is making 10 rows of cards. In each one you just put your cards in some random order, so when someone wants card 38, you just go to the third row and then linearly search through all of them, that way it is much faster to find items then just having them randomly on your table because you only have to search through a tenth of the cards, but you can't take shortcuts once you're in that row of cards.
Depending on the requirements, there can be so many ways to deal with it. It's better to use a collection class for the rich API available OOTB.
Are the strings supposed to be unique i.e. the duplicate strings need to be discarded automatically and the insertion order does not matter: Use Set<String> set = new HashSet<>() and then you can use Set#contains to check the presence of a particular string.
Are the strings supposed to be unique i.e. the duplicate strings need to be discarded automatically and also the insertion order needs to be preserved: Use Set<String> set = new LinkedHashSet<>() and then you can use Set#contains to check the presence of a particular string.
Can the list contain duplicate strings. If yes, you can use a List<String> list = new ArrayList<>() to benefit from its rich API as well as get rid of the limitation of fixed size (Note: the maximum number of elements can be Integer.MAX_VALUE) beforehand. However, a List is navigated always in a sequential way. Despite this limitation (or feature), the can gain some efficiency by sorting the list (again, it's subject to your requirement). Check Why is processing a sorted array faster than processing an unsorted array? to learn more about it.
You could use a HashMap which stores all the strings if
Contains query is very frequent and lookup strings do not change frequently.
Memory is not a problem (:D) .

Count elements in array

I am trying to count an element in an array of objects.
long number = Stream.of(jobTitle).count();
System.out.println("There are " + number + " employees.");
What happens is that it will print out the message as many times as many employees have the same job title. Yet "number" stays always 1.
Any guiding would be much appreciated.
long number = Stream.of(jobTitle).count();
Counts the elements in a stream that contains one element.
It is not surprising that this operation always ends up with the exact same result.
Your code is equivalent to:
List<Whatever> titels = new ArrayList<>();
titels.put(oneEntry);
... print titels.size()
Long story short: that statement is nonsensical. What you probably meant was:
if (arbetstitel.equalsIgnoreCase(jobCount)){
g++;
or something alikw. Of course g is a rather bad name for a counter.
But the real answer here is: step back. Think what the problem is you intend to solve, and what the elements are you need to look at. The code you are showing here is simply not making (much) sense. I can't tell you how to fix it, because, as said: it is not clear what you try to achieve here.
A streamish way of counting:
long usersWithMatchingTitle = Arrays.stream(employees).filter(e -> e.getJobTitle().equalsIgnoreCase(jobTitleFromUser)).count();
Meaning: instead of manually iterating your array, you can turn the whole array into a stream, and then filter/count whatever you want to.
Please note: your code seems to only care about the first 30 elements in that array. If that is really what you want, you will need ...stream(employees).limit(30)...
You need to change the stream of command to define a proper Predicate for filter option.
Stream.of(employees).filter(e -> e.getJobTitle().equals(jobTitle)).count();

Add a number to an ArrayList by sorting

Include a method addEventToTimeline that will be passed an Event. When an element is added to the ArrayList of events, it should be put in the correct place in the list. The elements in events should always be in chronological order.
Use similar logic and code to what we used yesterday to add an Event into the
correct place in the list. (Events are compared using compareTo.)
My code looks like this so far. I know it's wrong but I have no idea where to go from here.
public void addEventToTimeline(Event a){
for(int i = 0; i <events.size(); i++){
if(a.compareTo(events.get(i))<0);
events.add(i+1, events.get(i));
events.set(i, a);
}
}
}
Are you forced to use an ArrayList ? I would use a tree for this kind of problem. Here's what you should do with an ArrayList solution:
Find the correct place for the new Event (O(n) if the arrayList is unsorted, Log(n) if it is sorted - using Binary Search
Put the Event in its place, and move all the subsequent Events one position to the right ( O(n) )
I would use a more advanced data structure for this. For example if all you want is the min Event each time use a heap
If you need a global order, use a BST , or even better, a red black tree
This post on StackExchange can also be useful

element of a Linked List

Can someone please explain In Java how do you find middle element of a linked list in single pass?
I have googled it, but cannot seem to find a simple explanation on how to code it.
LinkedList<String> list = new LinkedList<>();
list.add("foo");
list.add("bar");
list.add("baz");
String middle = list.get(list.size()/2);
System.out.println(middle); // bar
The call to assign middle will pass through half of the list during the get call.
As pointed out in the comments, the middle is the worst place to operate on a LinkedList. Consider using another variation, such as ArrayList.
I think this is a sort of trick question that you see on lists of possible interview questions.
One solution would be to have two pointers to step through the list, one taking steps of two and one taking steps of one.
When the pointer that is taking two steps at a time reaches the end of the list, the one taking only one step will be halfway through.
I doubt that this practice is really useful though..
good luck!
Since it's a LinkedList, you won't be able to find out its size until after the first (and only) pass. To find the middle element, you need to know two things; what index is at the middle, and what is the value of the element at that index. Finding the middle index is easy--just make one pass through the list, keeping a counter of how many nodes there are. As you do this, you'll need to keep track of each element in a separate data structure, perhaps an ArrayList, since you're only allowed one pass through the LinkedList. Once you're done, half the counter to find the middle index, and return the ArrayList element at that index.
The pseudo code looks like this:
int count
ArrayList elements
for each node in LinkedList:
count++
elements.append(node)
middleIndex = count/2
middleElement = elements.getIndex(middleIndex)
return middleElement
Of course, you'll need to take care of the case where there isn't a single middle element.

select odd/even elements of array using recursion

Am working on some programming homework and am a bit lost. The project is to select the even/odd elements of a listarray and store in another array. It is not the even numbers in each element, but the elements themselves so if an array had values "1,2,5,7,9" and returned the even elements it would give "1, 5, 9". Also have to use recursion. Would anyone be able to give me a starting point or some advice. Though about starting with 2 elements and taking 2nd element and then building up from that, but don't know how it would add on the 2nd pass
public static ArrayList<Integer> even(ArrayList<Integer> list)
ArrayList<Integer> evenlist = ListMethods.deepClone(tList);//make copy of list
if (evenlist.size()<=1) // The list is empty or has one element
{
// return null;// Return the list as is
}
if
(evenlist.size()==2)
{
//return right element
//call method again
//add to list
}
Psuedocode
int[] evens,odds;
function categorize(List<Integer> in,int idx)
if(idx>=in.length)
return
int cur = in[idx]
if(even), add to evens
else add to odds
categorize(in,idx+1)
This sounds similar to the homework I just completed, so if it is (And you're in my class!), I'll not tell you to use any terminology we haven't covered as I know it can be daunting trying to discover something new for practicals (beyond what we have to do).
First, set your exit condition. As you've already said, you have to create a new ArrayList out of the existing one. You are going to remove items from the existing ArrayList, storing the integers that are at even (or odd) indices, until the list is empty.
So your exit condition is:
if (evenList is Empty)
return evenList;
Then, work your way through the steps. I would advise determining if the Array you start with has an even of odd number of steps, something like this:
if (evenList has Even Elements)
int holderForIntsAtEvenElements = last evenList EVEN element
Note we start at the last element, so when you are coming OUT of the recursive method, this will be the last one added to your new ArrayList, and thus it'll be in numerical order. You might find this post interesting to do this: What does this boolean return mean?
We then want to remove the last element from the list and recursively call the method again.
Finally, when we hit our exit condition and start to come out, we want to add the ints we've been storing to them, e.g.:
evenList.add(holderForIntsAtEvenElements);
return evenList;
That doesn't solve one problem, which is what to do with the very first element if the list does NOT have an even number of elements - however, I'll let you try and solve that!
That's a good mix of code and pseudo code and will hopefully help to get you on the right track.
You could use a simple for loop like this:
for (int i = 0; i < list.size(); i += 2) {
System.out.println(list.get(i));
}
If you have to use recursion, here's an outline of the steps you might take. (I won't tell you exactly what to do because you haven't tried anything and it is like homework.)
Take first element and store it
Remove (new) first element from list
Call self

Categories