Print same index position out of 2 ArrayLists - java

Given two ArrayLists, one containing Strings whereas the other contains Integers.
The next step would be to grab the first position of each ArrayList and print them out side by side next to each other.
Then 2, 3, 4 , 5, You name it.
1st List: public List getDoubleHistory(){...}
2nd : List<StringBuilder> timeAtThatMoment = new ArrayList<>();
I guess that we start with a for loop in which i is the index.

First we have to assume that the lists are the same size, or else we cannot continue to do as you asked.
for (int i = 0; i < getDoubleHistory().size(); i++){
System.out.println(getDoubleHistory.get(i));
System.out.println(timeAtThatMoment.get(i));
}
If the lists are not the same size you will have to add some if statements to make sure you dont get index out of bounds exceptions.
You can read more on this here. https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html

Related

How to merge arrays in alternating pattern without duplicates

I'm currently learning in school but am unable to complete this part of the assignment.
An explanation with the use of for loops would be greatly appreciated.
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.
Because the number of elements in the merged array is unknown, its size should be set to the maximum possible number of elements it should contain, and after all elements which should form the merged array appear, any remaining unfilled spaces in the array should be 0. The first 0 encountered in the array should signal the end of the “actual” elements of the array, and therefore the 0s at the end of the array should not be printed by your program.
I propose to use a HashSet to remember which number you have already inserted into the array. For each number, you first check if the hash set already contains the number; if not, you add it to both the array and the set. For large inputs, this is much faster than checking the result array for each number. O(n*log(n)) or so (depending on how well the HashSet works for your input) instead of O(n^2).
#bubble
An example using a Set is very simple - however your teacher is asking for
an alternate list:
Integer[] one = new Integer[] {10,2,3,1};
Integer[] two = new Integer[] {3,8,5,4};
List<Integer> li_one = Arrays.asList(one); // First convert the arrays to a list
List<Integer> li_two = Arrays.asList(two);
Set<Integer> set = new HashSet<>();
set.addAll(li_one);
set.addAll(li_two);
System.out.println("The unique list is: " + set);
A HashSet was my first idea too, but the order of storing values depends
one hash values. The ... teacher likes to have alternating values which
I dont like to comment - because it is a really strange request.
Following code prints: merged list is: [1, 3, 2, 4, 5, 10, 8]
int[] one = new int[] {1,2,3,10};
int[] two = new int[] {3,4,5,8};
int one_len = one.length;
int two_len = two.length;
List<Integer> merged = new ArrayList<>();
int oneval,twoval;
for (int i = 0;i < one_len;i++)
{
oneval = one[i];
if (!merged.contains(oneval)) merged.add(oneval);
if (i < two_len)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
if (two_len > one_len)
{
for (int i = one_len; i < two_len;i++)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
System .out.println("merged list is: " + merged);

Android compare string with array and remove array index values

if(responseArr.size()!=0) {
for(int i=0;i<responseArr.size();i++) {
if(responseArr.get(i).equals("busy")) {
stylistId.remove(i);
}
}
}
If any values in the array contain the string busy, I want to remove the value from the stylistId array in that position. In the code above, the responseArr array and the stylistId array are the same size.
When I try to remove values from stylistId, it works fine when the loop executes for the first time. When loop executes the second time, I get indexOutOfBound Exception.
This is happening because the index of some elements in the list changes when you remove an element. For example, if your list has five elements (0, 1, 2, 3, 4) and you remove element 2, then elements 3 and 4 will get renumbered so that you have (0, 1, 2, 3) afterwards.
There are many possible solutions to this problem, but one way is simply to traverse responseArr backwards.
for(int i= responseArr.size() - 1;i >= 0; i--){
if(responseArr.get(i).equals("busy")){
stylistId.remove(i);
}
}
That way, you'll only be changing the indexes of elements that you've already checked.
Because There are two version of remove method.
remove element at index
remove given element
You need to call second method which return element. So, You can use Like,
for (int i = 0; i < responseArr.size(); i++) {
if (responseArr.get(i).equals("busy")) {
int id = stylistId.remove(i); //use your type instead of int.
}
}

How to initialise an int java array of size n initially empty?

In a function,I want to initialise a java array of max size n, which is empty initially.If I add 3 elements(say n>3) and return the array, the array should contain only the 3 elements and not 3 elements followed by (n-3) 0's.
//PSEUDO CODE
func(){
//Create array A of max size 5
A[0]=1;
A[1]=2;
A[2]=3;
return A;
}
main(){
int[] B=func();
//B.length should give 3
for (int i=0;i<B.length;i++){
print B[i];
}
/*Should print 1 2 3
and Not 1 2 3 0 0
*/
}
And I don't want to use array list.I want to use java array only.
Your problem seems to be that you only want to print the non-default values of the array. If your values are always different from zero, then you can just do:
for (int i=0;i<B.length;i++){
if (B[i] != 0){
print(B[i]);
}
}
However, if your values can also be zero, you can also keep a counter of how many values you currently have, and only print that many values:
int counter = 3; //the array might be {1, 2, 3, 0, 0}
for (int i=0; i<counter; i++){
print(B[i]); //will print "1 2 3"
}
The counter must be incremented everytime you add a value.
Both solutions are limited though, depending on how you access and use the array.
then u have to make the array dynamic by urself. Everytime u add an element to the array create a new array of size=no of elements (let u r adding the 3rd element then size of new array would be 3). take the elements from old array to the new one. Each time u add 1 element u have to follow this.

Remove all elements in one list and add to another list - Java

So I'm trying to remove all cards from a player's 'Rack' (an ArrayList) and put it in the discard pile (Stack), one by one. So far I have the following code which I've come to realize will stop once it hits 5. (Note: each players rack has 10 cards).
int rackSize = player.getPlayerRack().getRack().size(); // rackSize = 10
for (int i = 0; i < rackSize; i++) {
getDeck().getDiscardPile().add(player.getPlayerRack().getRack().remove(i));
}
My question is how do I remove all items in the players 'Rack' so the rackSize = 0, and add all of them to the discard pile?
Terribly sorry if this is confusing. You can generalize this by saying there are 10 integers in an ArrayList<Integer> hand, so: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. How would you remove all items from this list and add them to a Stack<Integer> discardPile?
What's happening is as you're removing the elements from Rack, you're still incrementing with i++, meaning that the new value at the old index i is still left behind. What you'll want to do is change your code to this:
int rackSize = player.getPlayerRack().getRack().size(); // rackSize = 10
for (int i = 0; i < rackSize; i++) {
getDeck().getDiscardPile().add(player.getPlayerRack().getRack().remove(0));
}
This way, you're always reaching into the first new element in the Rack until it's empty, assuming Rack is not repopulated while this code is executing.
Use 0 instead of i to access the ArrayList.
When you remove an element, it is no longer in the ArrayList so you have to keep this is mind - further references through the array index should be decremented 1 in each iteration. As a result you probably want to access the first item every time.

Understanding Java sorting

I'm still learning about sorting and Arrays. Came up with this code which does sorting letters or numbers on ascending order but I really don't get the last part where System.out.println(SampleArray[i]);. Why is it SapleArray[i]? can someone enlighten me please.
public class TestClass {
public static void main(String[] args) {
String SampleArray[] = {"B","D","A","R","Z"};
Arrays.sort(SampleArray);
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
}
}
SampleArray refers to the whole array - here containing five strings.
SampleArray[0] refers to the first item in the array (here the string "B").
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
lets i take the values 0, 1, 2, 3, 4 one after another, so you print out first SampleArray[0]and then SampleArray[1] and so on until all the items have been printed.
You are trying to print an array, which is an ordered collection of items.
SampleArray[i] inside the loop lets you access one element at a time, in order.
More specifically, i takes on the values 0 through 4 in this case.
SampleArray[0] would give you the first element of SampleArray, because Java uses zero-based indexing for arrays.
Going through your code:
first you create a String array with those letters as element, which are saved like this: element 0 of array = B, element 1= D, etc. (in Arrays the counting always begin by 0 and not by 1).
Then it sort it in ascending order.
The for loop is there to print the sorted array, it iterate through the array beginning by element 0, until it is at the last element of the Array and it print these element.
The for loop does something over and over again.
The first part of the for loop, int i = 0 sets up a variable.
The second part i < SampleArray.length is the 'terminating condition' - it's the condition that has to remain true before each iteration of the loop.
The last part i++ is what happens after each iteration - i gets incremented.
So we are printing each element within SampleArray. i goes between 0 and the one less than the number of elements in the array. (e.g. if the array contained 4 elements, i would be 0 to 3, which is what we want).
And in the body of the loop, the [i] bit selects that element from SampleArray, and that is the value that gets printed on each line.
Another way of looking at it: SampleArray supports the [] operator, which when applied, will return an element from the array.

Categories