Java learning problems arrays - java

Can someone explain to me the answer?
What does x equal at the end?
int[] vs = {4, 15, 6, 26, 7, 8};
int x = vs[0];
for (int v : vs)
{
if (v < x) { x = v; }
}

I'll give this another try since I find sfThomas' answer a little confusing.
So:
The answer to your question upfront: x will equal 4. And the purpose of your little algorithm is simply to find the smallest (numerical) value in a given list of values.
Detailed explanation:
In line 1 you set up an array (think of it as an ordered list of values) of integer values (aka "whole numbers"). This array is called vs.
In line 2 you assign the variable x to the first element within vs. This happens to be 4.
Line 3 a for-each loop (official terminology in Java: "Enhanced for Loop") is declared. It executes the loop body (lines 4-6) for each element of the array vs. In each iteration v will hold the value of the currently processed element. Processing order equals declaration order. Thus: In the first iteration v will equal 4, in the second 15 and so on.
A traditional for loop to accomplish the same is given below.
The body of your loop (line 5) consists of a check whether v is ever smaller than x. This is never the case (i.e. there is no value within your array vs that is smaller than the value of the first element of vs) and therefore the code within the brackets x = v; (which would reassign x to the value of this smaller element every time such a smaller element is found) never gets executed. In other words: x always stays with its initial value vs[0] and that is 4.
I hope this was clear enough for a beginner.
for (int i=0; i<vs.length; i++) {
int v = vs[i];
// rest of the loop body
}

It looks for the smallest element in your array - the last part iterates over each element, and if it finds one that is smaller than the previous value, saves that instead in variable 'x'.
for (int v : vs) - this executes the block that is after with each value in the vs array, in a way that variable v is assigned to the given value.
Have a look at this.
{ if (v < x) { x = v; }} - this checks if the current v value is smaller than x, and then if so, saves that value in x.

Related

Print all possible combinations for a given array of elements

public class TestPossibleNumbers {
public static void main(String[] args) {
int input[] = { 1, 2, 3 };
// int input[] = {10,11,12,13};
possibleNumbers(input, 0);
}
public static void possibleNumbers(int[] x, int index) {
if (index == x.length) {
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
System.out.println();
}
for (int i = index; i < x.length; i++) {
int temp = x[index];
x[index] = x[i];
x[i] = temp;
possibleNumbers(x, index + 1);
temp = x[index];
x[index] = x[i];
x[i] = temp;
}
}}
Can anyone help me to understand the code inside for loop?
This program run perfectly. But, I am unable to figure out how it is working
You are recursively calling the method again at:
possibleNumbers(x, index + 1);
Thus the method runs the method again, with index + 1 passed. It checks if
if(index == x.length)
If the statement is correct it prints the numbers.
It then enters the 2nd for loop again(if the if statement was incorrect it will still enter it). And calls the recurring method again. It will keep entering 2nd for loop but when "index" will be equal to or greater than "i.length" no iterations of the for loop will run because you specified for loop to run only when:
i<i.length
When 2 for loop does not do any iterations the method will stop recurring. So in your case when index is equal to 3 no iterations of 2nd for loop will run.
Try running debug step by step to see what is happening more in depth.
The Program prints permutation of numbers not combination.
Permutation - Order matters
Combination - Order doesnt matter and more of choosing k elements out of n
for example
int a= {a,b};
permutation = {ab,ba}
whereas combination ={{},{a},{b},{a,b}}
To understand how the program works
go through the following link will
https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Don't get confused on recursion inside for loop.
if (index == x.length) is the terminating condition for recursion.
Inside the for loop before and after calling the recursive call possibleNumberselements are swapped.
Before swap helps to generate all possible outcomes and after swap elements will swap to previous position so that all other permutation will be generated from the for loop. It may sounds confusing please go through the link.
I'll provide an alternative explanation that I feel is more intuitive.
Consider the case of only 1 number in the list: [a]. This is pretty trivial: there's a single combination [a].
Now consider the case of 2 numbers in the list: [a, b]. In this case you can take each of the elements in turn and then look at all combinations of the remaining element using the previous method and then add the element back.
Now consider the case of 3 numbers in the list: [a, b, c]. In this case you can take each of the elements in turn and then look at all combinations of the other 2 elements using the previous method and then add the element back.
And so on for 3, 4, 5... elements.
So, in general, consider the case of n numbers in the list: [a1, a2, ... an]. In this case take each of the elements in turn and then look at all combinations of the other n-1 elements using the exact same method and then add the element back.
Converting to pseudo code:
getCombos(values)
for each value
for each combo in getCombos(values with value removed)
add value + combo to results
return results
The only thing to add is the base case which is necessary for all recursive implementations. One possibility is the case of a single item. However there's an even simpler one: if there are no values then the result is a single empty list.
So converting that to Java, using sets to make clear that the elements need to be unique (to avoid duplicate results), using streams and making it generic so it'll work for any type:
Stream<List<C>> combos(Set<C> values) {
if (values.isEmpty())
return Stream.of(new ArrayList<>());
else
return values.stream().flatMap(value ->
combos(values.stream()
.filter(v -> !v.equals(value))
.collect(toSet())).peek(r -> r.add(value)));
}
Your code is really just an alternate implementation of the same algorithm that swaps the element under consideration to the front of the array instead of creating a new collection.

What do array[] and array[i] operators do in Java?

I'm trying to teach myself coding, and I stumbled on an example I don't understand. Could someone give me an overview of what this code is supposed to do? I'm a bit confused about int a[] and what is later int a[i]. I know what an array is, but could someone please explain how this is being used in this context? Thank you in advance.
public class all {
public int select(int a[],int n,int x)
{
int i=0;
while(i<n && a[i]<x)
{
if(a[i]<0)
a[i]=-a[i];
i++;
}
return(a[i-1]);
}
}
This
if(a[i]<0)
a[i]=-a[i];
i++;
is he same like this
if(a[i]<0) {
a[i]=-a[i];
}
i++;
a[i] -> value at the position i, into the Array
if(a[i]<0) { -> if the value at position i is smaller than 0, also negative number
a[i]=-a[i]; -> replace the value with a reverse sign.
i++ -> increment loop Counter
Also what is done here: negative numbers convert to positive numbers.
while(i<n && a[i]<x) -> i = loop counter; if i smaller n and the value at position i in the array is smaller than x, then go into the loop.
return(a[i-1]); -> return the last value, that has been checked into the while loop
the method gets an array and two int args n and x (as a side note, I must say the names leave a lot to be desired...)
anyway, lets see what are the args for. they both are used in the while loop. the condition i<n tells us that n serves as upper limit to the iteration, while the condition a[i]<x tells us that x is used as upper limit to the values in the array.
so far, we can say:
select method receives an array, int arg specifying iteration-upper-limit and int arg specifying cell-value-upper-limit.
iterate over the array until you reach position specified by iteration-upper-limit or you reach a cell value that exceeds cell-value-upper-limit (which ever comes first)
can you continue to say what's being done inside the loop? it's fairly straightforward.
1.) a[] is the declaration of array.size is not defined.
2.)In a[i], i is the index number of the array...that means indicating the position of the element in array.
a[] is an array and we do not know its length. n must be lower than the length of a[] or it will throw an exception. It it traverses from the first element toward the last untill it one element is larger than x. it returns these element's absolute value which were traversed

Is there a difference in runtime efficiency if I evaluate the size of the array outside the loop?

The traditional way to iterate over an (integer, in this example) array of elements is the following:
int[] array = {5, 10, 15};
for(int i = 0; i < array.length; i++) [
//do something with array[i]
}
However, does this mean that after each iteration 'array.length' is re-evaluated? Would it not be more efficient to do this? :
int[] array = {5, 10, 15};
int noOfElements = array.length;
for(int i = 0; i < noOfElements; i++) {
//do something with array[i]
}
In this way, (to my understanding) the program only has to calculate it once and then look up the value of 'noOfElements' variable.
Note: I am aware of the enhanced for-loop, but it cannot be used when you want to use the variable that is being incremented ('i' in this example) to achieve other things within the for-loop.
I'm suspecting that this is actually a question of whether the Java compiler has the capability of realising that 'array.length' doesn't change and actually reusing that value after calculating it once.
So my question is: Is there a difference in runtime efficiency of the first block of code I wrote and the second one?
What I gather from the replies below, is that when an array is instantiated (is that the right word?) an instance variable called length is created and it is equal to the number of elements in the array.
What this means is that the statement array.length has nothing to do with calculation; it is only referencing the instance variable.
Thanks for the input guys!
See JLS- 10.7. Array Members:
The members of an array type are all of the following:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
Calling array.length is O(1) (constant time operation - it's final member of the array).
Also note that as mentioned in the comments, "traditional" way is not necessarily the way you proposed. You can use for-each loop:
for(int i : array) {
...
}
length is a field, therefore is not calculated when examining the for loop condition.
Your second block of code introduces a field to represent the length, thus increases memory usage (slightly, but still an important factor).
Yet further, if the array were to be re-created/re-assigned at some point, with a different set of values, your field would not be updated, but the array's length field would.
length is a field of an array that is not being calculated if you call myArray.length, instead it is being set when you create the array. So no, it's not more efficient to save it to a variable before starting the for() loop.

Get confused with nested loops

I know the rationale behind nested loops, but this one just make me confused about the reason it wants to reveal:
public static LinkedList LinkedSort(LinkedList list)
{
for(int k = 1; k < list.size(); k++)
for(int i = 0; i < list.size() - k; i++)
{
if(((Birth)list.get(i)).compareTo(((Birth)list.get(i + 1)))>0)
{
Birth birth = (Birth)list.get(i);
list.set( i, (Birth)list.get( i + 1));
list.set(i + 1, birth);
}
}
return list;
}
Why if i is bigger then i + 1, then swap i and i + 1? I know for this coding, i + 1 equals to k, but then from my view, it is impossible for i greater then k, am i right? And what the run result will be looking like? I'm quite confused what this coding wants to tell me, hope you guys can help me clarify my doubts, thank you.
This method implements a bubble sort. It reorders the elements in the list in ascending order. The exact data to be ordered by is not revealed in this code, the actual comparison is done in Birth#compare.
Lets have a look at the inner loop first. It does the actual sorting. The inner loop iterates over the list, and compares the element at position 0 to the element at position 1, then the element at position 1 to the element at position 2 etc. Each time, if the lower element is larger than the higher one, they are swapped.
After the first full run of the inner loop the largest value in the list now sits at the end of the list, since it was always larger than the the value it was compared to, and was always swapped. (try it with some numbers on paper to see what happens)
The inner loop now has to run again. It can ignore the last element, since we already know it contains the largest value. After the second run the second largest value is sitting the the second-to-last position.
This has to be repeated until the whole list is sorted.
This is what the outer loop is doing. It runs the inner loop for the exact number of times to make sure the list is sorted. It also gives the inner loop the last position it has to compare to ignore the part already sorted. This is just an optimization, the inner loop could just ignore k like this:
for(int i = 0; i < list.size() - 1; i++)
This would give the same result, but would take longer since the inner loop would needlessly compare the already sorted values at the end of the list every time.
Example: you have a list of numbers which you want to sort ascendingly:
4 2 3 1
The first iteration do these swap operations: swap(4, 2), swap(4, 3), swap(4, 1). The intermediate result after the 1st iteration is 2 3 1 4. In other words, we were able to determine which number is the greatest one and we don't need to iterate over the last item of the intermediate result.
In the second iteration, we determine the 2nd greatest number with operations: swap(3, 1). The intermediate result looks then 2 1 3 4.
And the end of the 3rd iteration, we have a sorted list.

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