Understanding Java sorting - java

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.

Related

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.
}
}

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.

Print same index position out of 2 ArrayLists

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

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.

How to check ALL elements of a boolean array are true

I have a boolean array whose size depends on the size of a randomly selected string.
So I have something like this:
boolean[] foundLetterArray = new boolean[selectedWord.length()];
As the program progresses, this particular boolean array gets filled with true values for each element in the array. I just want to print a statement as soon as all the elements of the array are true. So I have tried:
if(foundLetterArray[selectedWord.length()]==true){
System.out.println("You have reached the end");
}
This gives me an out of bounds exception error. I have also tried contains() method but that ends the loop even if 1 element in the array is true. Do I need a for loop that iterates through all the elements of the array? How can I set a test condition in that?
Using the enhanced for loop, you can easily iterate over an array, no need for indexes and size calculations:
private static boolean allTrue (boolean[] values) {
for (boolean value : values) {
if (!value)
return false;
}
return true;
}
There is a Java 8 one-liner for this:
boolean allTrue(boolean[] arr) {
return IntStream.range(0, arr.length).allMatch(i -> arr[i]);
}
boolean[] foundLetterArray = new boolean[5];
The memory allocation for the abow array is like
foundLetterArray[0],foundLetterArray[1],foundLetterArray[2],foundLetterArray[3],foundLetterArray[4]
Array index starts with 0 and the total memory count is 5 and the last array index is 4.
You are trying to get index 5 that is foundLetterArray[5] which does not exist. That's why you are getting the ArrayIndexOutofBoundsException
if(foundLetterArray[selectedWord.length()-1]==true){
System.out.println("You have reached the end");
}
Arrays in Java starts from index 0 and last index is always [array.length()-1]
As you are checking for foundLetterArray[selectedWord.length()] ,its giving you a array out of Bound Exception try foundLetterArray[selectedWord.length()-1]
Like:
if(foundLetterArray[selectedWord.length()-1]){
System.out.println("You have reached the end");
}
Indices in java, as well as most programming languages, are 0-based, meaning that individual elements in an array with n elements have indices 0, 1, 2, ..., n-1. The last element in an array is always at index array.length - 1.
Array index start from 0 so last index is always 1 less then array length so here you are trying to access last index + 1 by doing foundLetterArray[selectedWord.length()] this so it is throuing ArrayIndexBoundEception use array.lastIndex() method or subtract 1 form length.
Implementing this foundLetterArray[selectedWord.length()-1] You must take care about one thing if your array does not contains any elements then selectedWord.length() return 0 and again you will get same exception so Its good to check lengh before doing this foundLetterArray[selectedWord.length()-1].
do this
public boolean allTrue(boolean[] array) {
for (boolean b : array) {
if (!b) {
return false;
}
}
return true;
}
There is no 'one line' way of knowing whether all of the elements of an array meet a certain condition (there are libraries that take care of the looping for you, but you still need to write the condition). Querying array[x] will only tell you about the xth item in that array, so for your question you need to check every item.
Also, as other people have pointed out, array indices are 0-based, so the first element is at array[0] and the last at array[array.length() - 1].
My example uses an alternate looping construct known as for-each. This is appropriate when you don't need to modify the array contents, you only need to read from them. It avoids any messing around with indices.
You do the check only for last element in the array ( and do it wrong, above is described why ).
In order to get if arrays contains only true values you should check all of them.
boolean allAreTrue = true;
for (boolean val : foundLetterArray) {
allAreTrue = allAreTrue && val;
}
// at this line allAreTrue will contain true if all values are true and false if you have at least one "false"

Categories