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
Related
I'm rather new to Java, and I'm trying to figure out a way to copy all primes inside of an array and copy those to another array.
To do so, I've implemented a separate isPrime() method to check whether the element is a prime, and another method that counts the number of primes in that array countPrimes(), such that I can determine the new array's size.
Here is where I'm kind of stuck:
public static int[] primesIn(int[] arr) {
int primeHolder = countPrimes(arr);
int[] copyArr = new int[primeHolder];
for (int i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) == true) {
copyArr[>Needs to start from 0<] = arr[i];
}
}
return copyArr;
}
int[] arrayMan = {3,5,10,15,13};
At copyArr the position should be 0, followed by +1 everytime it finds a prime. If I were to give it i position, as in copyArr[i] = arr[i], then say the prime is at position 5, it would try to save the prime onto position 5of copyArr, which doesn't exist if there are only three primes in the original array, which would've given copyArr a length of only three.
Something tells me a different for loop, or maybe even an additional one would help, but I can't see how I should implement it. Help is greatly appreciated!
Have a second index variable int primeCount, and increment it whenever you find a prime. No need for a 2nd loop.
In modern days of abundant memory, things are usually not done like this. If you don't have some extra hard requirements, you could just use a resizable ArrayList<Integer>, and add() stuff in there. (and convert it back to int[] at the end if needed). This is also better in this case, because typically your countPrimes call will run much slower than ArrayList reallocations.
Read your words carefully:
At copyArr the position should be 0, followed by +1 everytime it
finds a prime.
That means that index in a new array does not depend on its position in the old array. Create a counter. And each time you place a prime number into a new array, increment it by 1. Thus you can always know where to put a new number.
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.
I've been having an issue with my code concerning arrays and int variables. In the section that I have issues with, I'm trying to check if an array (in which the user inputs their own integers) is in an increasing order, and if it is in an increasing order, the array is printed; if not, an error message is displayed. I am trying to do this using int two variables, one called c1 and another called orderCheck1 (both initialized to 0).
int[ ] list1 = new int [10000];
int a1 =0;
int b1 =0;
int c1 =0;
int value1;
int orderCheck1 =0;
while (a1 ==0){
if (b1 < list1.length){
value1 = scan.nextInt();
//checks to see if value entered is positive
if (value1 >=0){
list1[b1] = value1;
b1++;
}
else{
a1 =1;
}
}
}
while (c1 <(list1.length-1)){
if (list1[c1] >list1[(c1+1)]){
orderCheck1 =1;
}
c1++;
}
if (orderCheck1 ==0){
for (int i =0; i < b1; i++){
System.out.print (list1[i] + " ");
}
}
else{
System.out.println ("ERROR: One or both arrays are not in an increasing order.);
}
Basically, if a number in the array is larger than the number following it, orderCheck will become 1. Later in the code, it checks if orderCheck1 is either zero or one. If orderCheck1 is zero, then the ints in the array are printed; if it is one, then the error message is displayed.
The issue is, no matter what I enter, orderCheck1 always becomes a one, so the error message is always printed. What is wrong with my code?
Note: When the user enters values into the array, they are supposed to enter a negative number to stop entering values.
The main problem, I believe, is that you've allocated a list of 10000 elements, and you don't use them all. Java initializes the elements to 0. (Note that in some other languages, a construct like this could initialize the elements to random garbage values.)
You then write a loop that inputs numbers until the user enters a negative number. This will set the first n elements of the loop for some number n. But the remaining elements do not get chopped off the array. They are still there, and they are still 0.
This causes a problem for this loop:
while (c1 <(list1.length-1)){
if (list1[c1] >list1[(c1+1)]){
orderCheck1 =1;
}
c1++;
}
Note that list1.length is still 10000, even though the user didn't enter 10000 values. Once an array is created with new int[10000] or something like that, that fixes the .length of the array. This length cannot be changed. That means c1 will go up to 9999, regardless of how many values were entered.
Therefore, at some point, you will hit a point where you start comparing to the 0 values that got put in the array when you created it. Since all the values the user entered are positive, that means list1[c1] > list1[c1+1] will be true when list[c1] is the last value entered, because list1[c1+1] will still be 0.
The solution is that instead of letting c1 go up to list1.length-1, you have to stop it when it gets to, I think, one less than the number of user entries. It looks like you already have a b1 that counts the number of entries, so the while needs to be changed to while (c1 <some-expression-that-uses-b1). I'll let you work on getting that upper limit right.
One more thing: When you have an array like this whose size isn't really known, it's better to use an ArrayList. Unlike an int[], an ArrayList<Integer> will grow as you add elements to it, and the size() method will return the actual number of elements added.
I would suggest a method:
static boolean isAscending(int[] nums) {
for (int i = 1; i < nums.length; i++)
if (nums[i - 1] > nums[i])
return false;
return true;
}
Note that this handles the edge case of arrays of size zero or one correctly.
I'm trying to use a bubble sort to alphabetize an array that I've read into a program. The code compiles without error but I get an Array Index Out Of Bounds Exception on my 'if' construct when I try to run the program. I have initialized int i to 0 to account for the first index of the array so I think my error is elsewhere. I'm not asking anyone to write code for me, just maybe a point in the right direction. Thanks for any help.
public static String[] bubbleSort(String[] inL)
{
String temp;
int i = 0, passNum;
for(passNum = 1; passNum <= (inL.length); i++) // controls passes through bubble sort
{
if(inL[i].compareToIgnoreCase(inL[i + 1]) < 0)
{
temp = inL[i];
inL[i] = inL[i + 1];
inL[i + 1] = temp;
}
}
return inL; // returns sorted array
} // end bubbleSort method
You compare passNum instead of i against the length of the array. Since passNum is never modified, the loop condition is always true, and i gets incremented until it exceeds the range of the array.
Even if this particular issue is resolved, you may still run into problems with off-by-one errors with your current implementation. Consider whether you should compare i against inL.length - 1.
You never increment passNum so i continues incrementing forever. Also, array indexing in Java is based at 0. That means that the largest valid index is inL.length - 1. Since the body of your loop accesses inL[i+1], you should arrange your code so that i never exceeds inL.length - 2. At a minimum, you should change <= to < in the for loop termination test. (However, the logic of your comparison and incrementing escapes me; you need to fix that as well.)
Array.length stores the total length of an array, starting counting at 1.
The first index in an array however is 0, meaning that the last index is length-1.
adjust your check in your for-loop to fix the error
Your problem is the passNum <= (inL.length) it should be passNum < (inL.length) due to 0 being the first index of an array in java
I'm taking an online class so there isn't any help from the teachers or other classmates. Our assignment is that we need to find the max value and index of an array of random numbers. We need to do it in two ways. A regualr loop(brute force) and divide and conquer. In the divide and conquer we need to split the array into two smaller arrays and find the max of both and then merge.
I got the brute force to work and I got the divide and conqure to find the max also. But I can't seem to get the max of the two smaller arrays and merge the two. We also need to check for how many comparison is made by both methods and print the output.
Here's what I have so far:
public class MinMaxValues{
// Find maxiumum (largest) value in array using Divide and Conquer
public static int findMax( int[]numbers, int left, int right )
{
int middle;
int max_l, max_r, max_m;
if ( left == right ) // Only one element...
{
// Base case: solved easily...
return numbers[left];
}
else
{
// Solve smaller problems
middle = (left+right)/2; // Divide into 2 halves
max_l = findMax( numbers, left, middle);
// Find max in first half
max_r = findMax( numbers, middle+1, right);
// Find max in second half
//System.out.println("Maximum Value = " + max_r);
max_m = max_l+ max_r;
// Use the solutions to solve original problem
if ( max_l > max_r )
return(max_l);
else
return(max_r);
//return(max_m);
}
}
}
You are never returning an array.
Also you don't make any changes to the array.
You must change the array in some way once you find the max.
Try wrapping it with a method.
public static int[] maxSort(int[] array,int length){
int[] sorted = new int[array.length];
sorted[arrayLength]=findmax(array,0,sorted,arrayLength);//assumes find max returns maximum value of entire array.
while(length>0){
sorted=maxsort(array,length--);
}
return sorted;
}
I am not 100% sure it's working by i think it's a step in the right direction.
You need to more carefully address points in your program where you are comparing the index or the value at that index. For example, instead of checking whether max_l > max_r, I believe you mean to be checking whether numbers[max_l] > numbers[max_r].