An array of integers in a for loop? - java

I'm working on an textbook assignment and am having trouble understanding arrays. I'm looking at a practice question and am confused.
Declare an array of integers containing the first five prime numbers.
This would be int[]primes = {2,3,5,7,11}
Assume the array 'primes' has been initialized. What does it contain after executing the following loop?
for(int i = 0; i < 2; i++)
{
primes[4 - i] = primes[i];
}
The textbook gives the answer {2,3,5,3,2} for this...can anyone explain how this loop works?

I assume you understand practice 1. For practice 2, the loop
for (int i = 0; i < 2; i++)
iterates twice: once at i=0, and once at i=1. At i=2, the condition i<2 is broken, and the loop does not execute.
The actual line of code inside the loop
primes[4-i] = primes[i];
sets the 4-i'th element in the array to be equal to the i'th element in the array.
Initialized, the array primes is {2,3,5,7,11}
After one loop, the array primes is {2,3,5,7,2} (primes[4] = primes[0] has been executed).
After both loops, the array primes is {2,3,5,3,2} (primes[3] = primes[1] has been executed).
Remember that arrays are indexed by zero. Hope this helped.

the for loop exceutes two times, for i=0 and i=1
primes[4-0] = primes[0] = 2 -> primes[4] = 2
primes[4-1] = primes[1] = 3 -> primes[3] = 3
so the first 3 fields in the array are not changed, just the 4th and the 5th

It seems like you don't understand for loops that well at all, since this is a pretty simple example. For loops are basically shortcuts in code that iterate through data structures. You can type out for loops line by line, but they would be way longer. In this example,
for (int i = 0; i < 2; i++)
{
primes[4 - i] = primes[i];
}
becomes:
primes[4 - 0] = primes[0];
primes[4 - 1] = primes[1];
So all this loop is doing is setting the last element of the array to the first, and the second-to-last element to the second.

Starting with
int[]primes = {2,3,5,7,11}
the for-loop works like this
i=0 -> primes[4-0] = primes[0]; //array {2,3,5,7,2}
i=1 -> primes[4-1] = primes[1]; //array {2,3,5,3,2}

Imagine you have a zoo(memory) with a row of cages(array) next to each other. each cage is the exact size needed to hold an animal(data type like int)
Zoo---------------------
[animal][animal][animal][animal][animal]
------------------------
You decide to label each cage with a number(index)
Zoo---------------------
[animal][animal][animal][animal][animal]
0 1 2 3 4
------------------------
You get some initial funding to purchase animals for your cages (initialize the array). So you buy a Zebra, Panda, Owl, Tiger, and a Bear and put them in the cages. The order you purchased the animals is the order you place them in their cages.
Zoo---------------------
[Zebra][Panda][Owl][Tiger][Bear]
0 1 2 3 4
------------------------
Your zoo just perfected cloning so you are able to make copies of the animals. You Decide people are really enjoying Pandas & Zebras but don't care for Tigers and Bears. You delegate your tasks(algorithm) by having a sequential stack of index cards with instructions(loop). Each index card has a page number going from 0 up to less than 2, so your last index card has the page number 1
_________________________ ___________________________
|0 | |1 |
| | | |
| | | |
| | | |
| | | |
|_________________________| |___________________________|
You love the number 4 and believe that it is way better then any number and should be the starting point of counting instead of the number 0. So you give all instructions using the number 4 as a reference point.
_____________________________ _____________________________
|0 | |1 |
|Yo zoo keeper, | |Yo zoo keeper, |
|Copy the animal | |Copy the animal |
|in the cage that has this | |in the cage that has this |
|card number and put it in | |card number and put it in |
|cage 4 minus this card number| |cage 4 minus this card number|
|-The Boss | |-The Boss |
|_____________________________| |_____________________________|
Your zoo keeper reads the first index card(with the number 0). He makes a copy of the Zebra and puts in the cage with the Bear. The Zebra immediately eats the bear and is the only inhabitant of the cage.
Zoo---------------------
[Zebra][Panda][Owl][Tiger][Zebra]
0 1 2 3 4
------------------------
Your zoo keeper reads the second index card(with the number 1). He makes a copy of the Panda and puts in the cage with the Tiger. The Panda immediately eats the Tiger and is the only inhabitant of the cage.
Zoo---------------------
[Zebra][Panda][Owl][Panda][Zebra]
0 1 2 3 4
------------------------
And that is how arrays work for primitives. For Objects instead of cages in your zoo you just have a map that points to where you can find the animals in the zoo. Any animal that is not on the list gets marked with a tag and swept to the wild, freeing up space in your zoo.

Related

Iterate through arraylist using data from excel file

So I have a document on excel and I have a list of data saying how many people use x or y and how many times. So basically i have a column with people ID, a column with type (x and y) then a column saying how many times the people use x or y. I want to be able to iterate through the list without changing it so as it get the number of people using each type and i want the list to be sorted in ascending order or frequency. So I wanted to use a for loop to go through the list and put an if statement inside of it saying that if x, then another for loop to be able to group them by frequency.
The actual code I have is not good but I am really stuck on that and do not really know how to proceed :
for(int i = 0; i < type1.size(); i++){
if(events.get(i).isX()){
for(int j = 0; j < /*max value of the data in the list*/; j++ )
//here list should group all common frequency
}
else
//do same thing but for y
Excel table eg
QUESTION
Under the assumption that you have an excel-file with three columns:
id | type | frequency
And a List representing the data of your excel-file. You might want to order your Entrys with the Collections.sort(Comparator<T>) method.
Here is an example on how you can achieve that:
Example a:
Arraylist<Row> yourList = new ArrayList();
fillListWithExlData(yourList);
for(int i = 0; i < yourList.size(); i++){
Collections.sort(yourList, new Comparator<Row>()){
//compares row i with the following row
compare(Row oneRow, Row followingRow){
//if the result is 1 =< the entry moves on higher in the list if the result is = 0 it stays on its position and if its <= -1 it moves down.
return oneRow.getFrequenzy() - followingRow.getFrequenzy();
}
});
}
Notice: that you can also use the Comparator to order your "types".
Example b:
return (oneRow.getType() == followingRow.getType()) ? 0 : -1;
Or you might even want to match both, id and frequency. Then you might try this:
Example c:
return (oneRow.getType() == followingRow.getType() &&
oneRow.getFrequenzy() == followingRow.getFrequenzy())
? 0 : -1;
example a should Order a potential List:
id | type | frequency
1 | x | 12
2 | y | 10
3 | x | 12
into:
id | type | frequency
1 | x | 12
3 | x | 12
2 | y | 10

Bidirectional Bubble Sort

I have to solve the following problem. So initially i had a bubble sort and now i modified it to make it bidirectional. The following is my solution.
public void bubbleSort() {
int temp;
int out;
int outNew = 0;
int in;
for (out = nElems - 1; out > outNew; out--) {
for (in = 0; in < out; in++) {
if (a[in] > a[in + 1]) {
temp = a[in + 1];
a[in + 1] = a[in];
a[in] = temp;
}
}
for (int j = in - 1; j > outNew; j--) {
if (a[j] < a[j - 1]) {
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
outNew++;
}
}
When i call my bubble sort to sort few random numbers in an array i created it seems to be sorting fine. My question is rather to all you developers whether my solution is satisfying the question posted above and also what could i have done differently to make this solution more effective (if possible) . I am sorry if this is a little open question , i am usually on here looking for hints and suggestions rather than code as it helps me learn better. I appreciate all answers and am open to any suggestions.
Your first inner loop seems a bit inefficient, since your array will be partially sorted at both ends. After the first round (one time incrementing the index, one time decreasing it) the first and the last element will already be correct, hence no need to start at index 0 (and the task/exercise requires that btw).
The following ASCII art demonstrates, on which indices the algorithm should operate on at the example of a array with 9 elements (including the indices reached with in+1 and j-1; all indices between the | should be considered):
position: 0 1 2 3 4 5 6 7 8
------------------------------------------------------------
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
But what your algorithm does is:
position: 0 1 2 3 4 5 6 7 8
------------------------------------------------------------
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
| -> |
| <- |
You'll have to fix the the initial index of the first inner for loop.
In short, I don't think you can me more effective AND answer the question at the same time. It's pretty explicit in that you have to carry your item to the right until you find one smaller, then take that slightly smaller than the last you carried and bring it up. I don't think there's any performance gain from the regular unidirectional bubble sort but if you're going to make it bidirectional, then this is the way to do it.
How can you tell? Well since there's no performance gain/deterioration to get, the left->right code and the right->left code should be perfectly symmetrical (since they're identical in performance terms). In your case, there are so I'd say it looks good.
Thinking a bit deeper, there's probably some slight optimization to get from being bidirectional, just because you're getting an item you just looked at so you know you can bring to the left from it's initial position, skipping the right side of the array. But in the end, it's negligible and it's still O(n²) performance, no matter how you slice it.

Recursion with an Array

I'm having a bit of trouble understanding the concept of recursion. I understand that it is basically a method that calls itself and turns a big problem into a bunch of smaller parts to solve it. What I'm having difficulty with is using recursion with an array. Here is an example in my book:
//Precondition: x is an array of n integers
public int recur(int[] x, int n)
{
int t;
if(n == 1)
return x[0];
else
{
t = recur(x, n-1);
if(x[n-1] > t)
return x[n-1];
else
return t;
}
}
If anyone has the time, could you explain what this method does and how it works? Greatly appreciated!
This function returns the largest integer of an integer array.
Lets see how, Your function recur takes an integer array x and its length n.
If the length of array is 1 then the lone element x[0] is the largest one.
Else we get the largest element from the array starting with x[0] to x[n-2](that is array of length n - 1) and so on, when we get the largest element we keep on sending it as the return value till recursion finishes, finally returning the largest value.
This method finds the biggest number among the first n elements of an array.
It works by finding the biggest number among the first n-1 elements; then checking whether the nth element is bigger. The recursion comes in when it finds the biggest number in the first n-1 elements - it does that by calling itself with n-1 in place of n.
Of course, if n is 1, then there's nothing to check - we should just return the first element. This is the "base case" of the recursion.
Note that when I say the nth element, this is actually x[n-1], not x[n] because array indexes start from zero.
In recursion we have what is called base case which is a condition to make the recursion stop. In this situation the base case is if (n==1) where the first element of x[] is returned.
Let's go to the second part of the recursion. The function is calling itself but decrementing n, until it reachs to the base case. Once the base case is returned, the function will compare the first element, now t, with the next one x[n-1] (where n is equal to 2) and return the greater of both. When one value is returned the function goes to its previous call in the stack.
In other words, to analize recursion you should go through the function calls until the base case is reached and once there, start to go back leaded by the returns or the final execution of the function.
As stated in above answers this method will return largest among the first n values in the array, i would like to show this answer pictorially
Assume array with values
{5, 4, 2, 1, 8, 6, 4, 2, 12, 33}
-----------------------------------------------------------------------------------
caller | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1
===================================================================================
t | 12 | 8 | 8 | 8 | 8 | 5 | 5 | 5 | 5 | none
===================================================================================
return | 33 | 12 | 8 | 8 | 8 | 8 | 5 | 5 | 5 | 5
Here caller is the invoker of recursive method. and in the n = 10, 33 will be compared with 12 and 33 will be returned to invoker. Hence invoker will received largest value in the array.

java bubble sort issue

I am learning Java from the past one month. I am having difficulties to understand the line
for(int i = 0;i<list.length-1;i++){
Can anybody explain me in layman lang. I am a slow learner. I understand for loop but this thing i am not able to understand
Int[]list = {5͵7͵54͵34͵87͵44};
boolean swap = true;
int temp;
while(swap){
swap = false;
for(int i = 0;i<list.length-1;i++){
if(list[i] > list[i+1]){
temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
swap = true;
}
}
}
Let's consider an array
0 1 2 3 4 5 6 7 8 9 <-- array indexes
_ _ _ _ _ _ _ _ _ _
| | | | | | | | | | |
The line for(int i = 0;i<list.length-1;i++){ tells you you are going to iterate from 0 to lenght - 2. In my example the length is 10, so you're going to iterate from 0 to 8.
The reason for it is to avoid OutOfBoundsException in this line list[i] > list[i+1] where you compare i-th index with i+1-th index. In the last iteration it's going to be i = 8 and i + 1 = 9 (which is the last index of my array).
your code is going through all list.entries in this for loop.
if your list.entry at position i is bigger than list.entry at position i+1
you save your list.entry at position i in temp
then you are saving the bigger list.entry at position i+1 in your actual list at position i.
your list[i+1] is getting the smaller value of temp (which you saved in the beginning)
after that you set swap = true... probably in order to know that you swapped i and i + 1
if swap is not true your while loop is done, because your list is sorted
the loop at line 5 is for comparing all possible pairs of numbers. The while loop is for selecting first member and the for loop is for selecting second member.
You have an array of size 6 i.e from index 0-5. Your for loop starts with the index 0 and checks the element at index 0 with index 1. If index 0 is greater than index 1, swap the two values. Similarly, it checks till index 4(i=4) and index 5(i+1) is reached, because this will be the end of the array index i.e you will check for the last two elements in the array(since the array index starts from 0). If you go any beyond i=4, you will check for 5 and 6(which does not exist in your array and will throw an OutOfBoundsException).
for(int i = 0;i<list.length-1;i++){
goes through items in list. You are accessing each item with list[i]. (the first item has index 0 (list[0]). i is going to be zero (0) on the beginning of your loop and then it is going to increase by one (i++) each iteration; It will increase until the middle expression
i<list.length-1`)
fitting i.
So in your case it will go through the items (you have 6 in your list as you can see). The last item has index 5 list[5]. That is why you have -1 in list.length-1

Enqueue method in CircularArrayQueue class

I have come across the enqueue() method in CircularArrayQueue class:
public void enqueue (T element) {
if (size() == queue.length){
expandCapacity();
}
queue[rear] = element;
rear = (rear+1) % queue.length;
count++;
}
I don't quite understand what the rear = (rear+1) % queue.length; part of the code does, can someone break down the steps of that line of code.
I do understand that it increments rear as a new element has been added however I am unsure of the % operation.
One way to visualize what is happening is to imagine a clock (often used as an analogy for modular arithmetic, which is happening in the line you mentioned with the use of the % operator).
For example, imagine that the CircularArrayQueue has a size of 4 at the moment and that its length is 5 (indices 0 - 4). In the example below, the current value of rear is 4 (index 4)
The items in the internal array might look like this:
INDEX | 0 | 1 | 2 | 3 | 4 |
VALUE | | 8 | 9 | 2 | 1 |
^
|
Rear
Now let's say that you insert the value 7 into the CircularArrayQueue, then the line
rear = (rear + 1) % queue.length;
would be executed. This effectively computes the following:
add 1 to rear (4) -> 5
divide by queue.length (5) -> 5 / 5 = 1 (remainder of 0)
take the remainder of the previous division (0) and set it equal to rear
INDEX | 0 | 1 | 2 | 3 | 4 |
VALUE | 7 | 8 | 9 | 2 | 1 |
^
|
Rear
so after all of these steps, rear now equals 0 and points to the first index in the internal array of the CircularArrayQueue. This behavior of the index "wrapping back around" the array when it reaches the end is the circular behavior that is characteristic of a CircularArrayQueue.
The way that this relates to a clock, is that the minute hand on a clock always "wraps back around" when it reaches 60, and "resets" back to 0.
In other words, the internal array used as an example above, can be thought of as a clock with only 5 minutes (indices 0 - 4). You can think of (rear + 1) as advancing by a minute on the clock. After the "minute hand" (rear) has been incremented 4 times, it starts again at 0.
it basically rounding your queue index for circular queue.
lets say your array queue.length==10,so when rear incremented to 10 it will be rounded to 0 to insert next element at 0 index.
rear = (rear+1) % queue.length; achieves circularity. As CircularArrayQueue class name suggests it is circular. It means that when the last element (queue.length-th) is reached it begins to insert elements from the beginning. rear = (rear+1) % queue.length returns rear+1 in case the rear+1 < queue.length , and 0 if rear+1 == queue.length and in this case it start inserting elements from the beginning of the array.

Categories