Hi I want to get the lowest 3 elements of an array. By lowest I mean the minimum value. I cannot use the collections.Sort method as I need to know the index of the elements. Therefore I am using the following code to get the lowest, but I need to know how I can get the lowest 3.
int minimum = grades[1];
int index = 1;
for(i=1; i<= numberOfStudents; i++){
if (grades[i]<minimum){
minimum = grades[i];
index = i;
}
}
Here is a really simple way of doing it:
public static void main(String[] args) {
int[] myArray = { 5, 8, 12, 9, 50, 11, 4 };
System.out.println(Arrays.toString(myArray));
System.out.println(Arrays.toString(getThreeLowest(myArray)));
}
private static int[] getThreeLowest(int[] array) {
int[] lowestValues = new int[3];
Arrays.fill(lowestValues, Integer.MAX_VALUE);
for(int n : array) {
if(n < lowestValues[2]) {
lowestValues[2] = n;
Arrays.sort(lowestValues);
}
}
return lowestValues;
}
This outputs:
[5, 8, 12, 9, 50, 11, 4]
[4, 5, 8]
The call to Arrays.sort is only done to the local array, not your main array. The reason it does this is just to simplify the comparison against n.
Building off what you had
int[] grades = { 100, 99, 98, 97, 10, 95, 11, 9, 94 };
int numberOfStudents = grades.length;
int minimum = grades[1];
int minimum2 = grades[1];
int minimum3 = grades[1];
int index = 1;
int index2 = 1;
int index3 = 1;
for(int i=1; i< numberOfStudents; i++){
if (grades[i]<minimum3 && grades[i]>=minimum2){
minimum3 = grades[i];
index3 = i;
}
if (grades[i]<minimum2 && grades[i]>=minimum){
//We have a new 2nd lowest - shift previous 2nd lowest up
minimum3 = minimum2;
index3 = index2;
minimum2 = grades[i];
index2 = i;
}
if (grades[i]<minimum){
//We have a new lowest - shift previous lowest up
minimum3 = minimum2;
index3 = index2;
minimum2 = minimum;
index2 = index;
minimum = grades[i];
index = i;
}
}
System.out.println("Smallest is at " + index + " with value of " + minimum);
System.out.println("Next Smallest is at " + index2 + " with value of " + minimum2);
System.out.println("Next Smallest is at " + index3 + " with value of " + minimum3);
This may be a bit 'too much' but off the top of my head possible that you could make an array of objects, each object containing the value and index it has in the original 'grades' array and sort that?
The only other way I can think of is to good through the array and manually keep track of the 3 lowest elements and their indexes like what you're already doing...
Take three variables: the smallest, second smallest and third smallest.
In the same way you are finding your smallest element, find at each step which are the three smallest elements.
You need to check if any element is smaller than the smallest number, or it is between the smallest and the second smallest, or it is between the second smallest and the third smallest.
As this is probably an assignment, task or homework, i will not write the code here.
Can we do
int[] myArray = { 5, 8, 12, 9, 50, 11, 4 };
Arrays.sort(myArray);
System.out.println(myArray[0] +","+ myArray[1] +","+ myArray[2]);
Related
I have a function public static void sortedlist(int[] l, int r) that takes an array int[] l and returns a new array where every non-negative element in the list would be added with every element until the rth element.
So here is an example.
Lets say we have l = {1, 2, -3, 4, 5, 4}, and r = 3. In this case, we would:
Replace l[0] with l[0] + l[1] + l[2] + l[3].
Replace l[1] with l[1] + l[2] + l[3] + l[4].
Not do anything to l[2] because it is negative.
Replace l[3] with l[3] + l[4] + l[5]. (We can't go further than the end of the array.)
Replace l[4] with l[4] + l[5].
Not change the value of a[5] because there are no values after l[5]. So the sum is l[5] itself.
Thus, the result after calling `sortedlist` would be {4, 8, -3, 13, 9, 4}.
Here is my code so far:
public class Practice2 {
public static void sortedlist(int[] l, int r) {
int[] A;
int sum = 0;
for (int i = 0; i < l.length + r; i+=r) {
sum = sum +=
}
}
}
As you can see, I'm not done with the code because I'm stumped on how am I supposed to move forward from this point.
What I'm trying to do is create a new Array A and then add the new values that I've received from sum into Array A.
Any help would be greatly appreciated. Furthermore, if you could explain the logic behind a working code would be extremely beneficial for me as well.
Thank you :)
Try this.
public static void sortedlist(int[] l, int r) {
for (int i = 0, max = l.length; i < max; ++i)
if (l[i] >= 0)
for (int j = i + 1; j <= i + r && j < max; ++j)
l[i] += l[j];
}
and
int[] a = {1, 2, -3, 4, 5, 4};
sortedlist(a, 3);
System.out.println(Arrays.toString(a));
output:
[4, 8, -3, 13, 9, 4]
Please find the solution below and i have also provided some explanation regarding the logic behind it.
Note: I have unit tested it for few cases and it seems working fine.
1) r is less than array length
2) r is equals to array length
3) r is greater than array length
public class Test {
public static void main(String[] args) {
int[] input = new int[]{1, 2, -3, 4, 5, 4};
int r = 3;
sortedlist(input,r);
}
public static void sortedlist(int[] l, int r) {
List<Integer> list = new ArrayList<>();
int itr = 0;
for(int i = itr; i < l.length ; i++){//This loop is for iterating over the given array
int temp = 0;
int itr2 = Math.min(itr + r, l.length-1);//This function takes the minimum value and it helps when the (itr+r) > l.length, it will consider the (l.length-1)
if(l[i] > 0){// checking whether the selected value is -ve or not
for(int j = i; j <= itr2 ; j++){ // This loop is for calculating the addition over the selected range
temp = temp + l[j];
}
} else {// if it is-ve, assigning the same value to temp
temp = l[i];
}
list.add(temp);// storing the calculated value in a list of integers
itr++; // incrementing the main loop iterator
}
System.out.println(list);
}
}
Output:
[4, 8, -3, 13, 9, 4]
Maximum Product Subarray
Given an array that contains both positive and negative integers, find the subarray of the maximum product .
Examples:
Input: arr[] = {6, -3, -10, 0, 2}
Output: The subarray is {6, -3, -10}
Input: arr[] = {-1, -3, -10, 0, 60}
Output: The subarray is {60}
Input: arr[] = {-2, -3, 0, -2, -40}
Output: The subarray is {-2, -40}
Note: Finding the Max Product is done as using the kadane algo where i tried to reuse it for finding sub array but not able to break the part of finding the start index, finding end index is easy. end index is where res < max.
public int maxProductSubArray(int arr[], int len) {
int res = arr[0];
int max = arr[0];
int min = arr[0];
for (int i = 1; i < len; i++) {
int temp = max;
max = Math.max(Math.max(max * arr[i], min * arr[i]), arr[i]);
min = Math.min(Math.min(temp * arr[i], min * arr[i]), arr[i]);
res = Math.max(res, max);
}
return res;
}
but not able to break the problem to find the SubArray.
There are several possible ways to solve this problem:
Brute-Force
Divide-and-Conquer
Backtracking
I will only show you the Brute-Force-Solution. It is not the fastest solution, but in my opinion the most clear and easily understandable solution:
public class SubArray {
public static int findMax(int[] num) {
int max = num[0];
int start = 0;
int end = 0;
for(int i = 0; i < num.length; i++) { //Iterating over every possible starting position
for(int j = i; j < num.length; j++) { //Iterating over every possible end position
int multiply = 1;
for(int k = i; k <= j; k++) { //Multiply from start to end
multiply *= num[k];
}
if(max < multiply) { //Did we find a new maximum?
max = multiply;
start = i;
end = j;
}
}
}
System.out.print("The subarray is {"); //Print subarray with highest product
for(int i = start; i <= end; i++) {
System.out.print(num[i]);
if(i < end) {
System.out.print(", ");
}
}
System.out.println("}");
return max;
}
public static void main(String[] args) {
int[] array = {6, -3, -10, 0, 2} ;
int max = findMax(array);
System.out.println("Maximal product is: " + max);
}
}
This problem can be efficiently solved by divide and conquer.
Assume you want to solve the problem for a subarray [l, r]; Then, assuming c = (l + r) / 2 the solution is either subarray in [l, c], or in [c + 1, r], or in some subarray containing c and c + 1.
Then let's define a function f(l, r) returning the answer for subsegment; Then, to compute this function, first recursively call f(l, c) and f(c + 1, r) and pick the maximum as the temporary answer. Then compute multiplications of segments [c, c], then [c - 1, c] and so on (using multiplication of [c - k, c] = multiplication of [c - k + 1, c] * array[c - k]) and compute maximum and minimum multiplications across all such segments. Do the same for segments to the right of c ([c + 1, c + 1], [c + 1, c + 2] and so on) Then, the answer will be either a temporary answer, of multiplication of maximums or multiplication of minimums or multiplication of minimum and maximum and vice versa (minimum times maximum is required if such multiplication would be negative). Return the maximum across these four values or the temporary answer as the function result.
If it is necessary, instead of returning just the value of multiplication function can also return the segment where these value is reached.
This solution uses Θ(n log n) time and Θ(n) space.
I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
I'm trying to get the minimum and maximum value of an array. The problem is that I'm not sure what exactly happens in the for loop. We create a for loop with an int. Then comes the if statement and also my question: What should numbers[i] mean? I thought that numbers already has specified size (9, by initializing { 1,2,3,...,9}). How can we change that to [i] and what does that i stand for?
public class Array {
public static void main(String[] args) {
int numbers[] = { 92, -108, 2, 120, 67, 4, -81, 9, 88, 1 };
int min, max;
min = max = numbers[0];
for (int i = 1; i < 10; i++) {
if (numbers[i] < min)
min = numbers[i];
if(numbers[i] > max){
max = numbers[i];
}
}
System.out.println("min is: " + min + "; max is: " + max);
}
}
Looking forward to your replies
numbers[i] is how you access the ith element in the array.
As Andrew Rueckert mentioned, in Java, as well as in most other major languages, array[i] notation provides access to ith element of array array. You may use square brackets [] to specify the size of an array in its definition, for example:
int[] array = new int[10];
But later on, you use brackets to specify to which element of the array you want to have access to. In your example, there is for loop iterating from 1 to 10. In each iteration it reads current (ith) element from the array numbers.
If u want get min and max value from array, you can use sort() method from java.util Arrays class.
import java.util.Arrays;
public class TestClass {
public static void main(String[] args) {
int[] numbers = { 92, -108, 2, 120, 67, 4, -81, 9, 88, 1 };
// print your array (no sorted)
System.out.println(Arrays.toString(numbers));
Arrays.sort(numbers);
//print your array (sorted)
System.out.println(Arrays.toString(numbers));
for(int i = 0; i<numbers.length;i++){
System.out.println("My array: ["+i+"] " +numbers[i]);
// min = numbers[0] = -108
// My array: [0] -108
// My array: [1] -81
// My array: [2] 1
// My array: [3] 2
// My array: [4] 4
// My array: [5] 9
// My array: [6] 67
// My array: [7] 88
// My array: [8] 92
// My array: [9] 120
// max = numbers[9] = 120
}
}
}
Lets take the barebones of what you are trying to understand
int numbers[] = { 92, -108, 2, 120, 67, 4, -81, 9, 88, 1 };
int min, max;
min = max = numbers[0];
for (int i = 1; i < 10; i++) {
if (numbers[i] < min)
min = numbers[i];
if(numbers[i] > max){
max = numbers[i];
}
}
First, you are initializing an array of numbers to whatever you have within the {}. So you have an array that is of length 10. Then we declare two int's min and max. The values are as such:
numbers[0] = 92;
numbers[1] = -108;
numbers[2] = 2;
numbers[3] = 120;
numbers[4] = 67;
numbers[5] = 4;
numbers[6] = -81;
numbers[7] = 9;
numbers[8] = 88;
numbers[9] = 1;
The next statement is declaring min and max as the very first element of the array (0 is the first, all the way up to size-1 for arrays, which in this case is 9).
min = numbers[0] (92).
max = numbers[0] (92).
Next part is the for loop, which is where all the calculations come into play. The for loop is saying start an int named i off at 1. Everytime you go through this loop, compare the boolean value in the middle, which in this case is i < 10 which means as long as i is less than 10, stay in the loop. After each iteration, do the third operation which in this case is i++, which means increment i variable by 1.
Great, we are going through the for loop. Lets start off with the first iteration, which means i is 1. We are taking the SECOND element of the numbers array (0 is the first element, remember?) and comparing that with the current value of min first (which is the first element of the array, 92).
Well if you look at the values, -108, which is the second element in the array, is less than min. Therefore, min is set to the first element in the array now. Next, we compare -108 and see if it is greater than max, which again is 92. -108 is NOT greater than 92, so it skips that if statement.
i = 1
min = numbers[1] (-108).
max = numbers[0] (92).
Lets go through the second iteration of the for loop. Since we got to the end, we do the i++ statement. Now we are at i = 2. Lets check to make sure we dont exit. Is the value of i less than 10? Yes so lets continue from the top!
Is numbers[2] (which is 2) less than the current value of min (-108)? No, skip that if statement. is numbers[2] greater than the current value of max (92)? No, lets take another look at the values:
i = 2
min = numbers[1] (-108)
max = numbers[0] (92)
Next, since we are at the bottom, do i++. i now equals 3.
This continues all the way through till i = 9, because when i = 10, it exits out of the for loop due to that middle statement in the for loop, the exit clause.
I have an integer array: int[] numbers = new int[...n]; // n being limitless.
Where all the numbers are between 0 and 100.
Say numbers[] was equal to: [52, 67, 32, 43, 32, 21, 12, 5, 0, 3, 2, 0, 0];
I want to count how often each of those numbers occur.
I've got a second array: int[] occurrences = new int[100];.
I'd like to be able to store the amounts like such:
for(int i = 0; i < numbers.length; i++) {
// Store amount of 0's in numbers[] to occurrences[0]
// Store amount of 1's in numbers[] to occurrences[1]
}
So that occurrences[0] would be equal to 3, occurrences[1] would be equal to 0 etc.
Is there any efficient way of doing this without having to resort to external libraries? thanks.
You can simply do something like this:
for (int a : numbers) {
occurrences[a]++;
}
Also, if you mean 0 to 100 inclusive then occurrences will need to be of size 101 (i.e. 100 will need to be the maximum index).
You might also want to perform an "assertion" to ensure that each element of numbers is indeed in the valid range before you update occurrences.
Updated to put results in the 100-array.
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
<P>{#code java IntOccurancesInArray}</P>
**/
public class IntOccurancesInArray {
public static final void main(String[] igno_red) {
int[] ai = new int[]{52, 67, 32, 43, 32, 21, 12, 5, 0, 3, 2, 0, 0};
Map<Integer,Integer> mpNumWHits = new TreeMap<Integer,Integer>();
for(int i = 0; i < ai.length; i++) {
int iValue = ai[i];
if(!mpNumWHits.containsKey(iValue)) {
mpNumWHits.put(iValue, 1);
} else {
mpNumWHits.put(iValue, (mpNumWHits.get(iValue) + 1));
}
}
Set<Integer> stInts = mpNumWHits.keySet();
Iterator<Integer> itrInts = stInts.iterator();
int[] ai100 = new int[100];
int i = 0;
while(itrInts.hasNext()) {
int iValue = itrInts.next();
int iHits = mpNumWHits.get(iValue);
System.out.println(iValue + " found " + iHits + " times");
ai100[iValue] = iHits;
}
for(int j = 0; j < ai100.length; j++) {
if(ai100[j] > 0) {
System.out.println("ai100[" + j + "]=" + ai100[j]);
}
}
}
}
Output:
[C:\java_code\]java IntOccurancesInArray
0 found 3 times
2 found 1 times
3 found 1 times
5 found 1 times
12 found 1 times
21 found 1 times
32 found 2 times
43 found 1 times
52 found 1 times
67 found 1 times
ai100[0]=3
ai100[2]=1
ai100[3]=1
ai100[5]=1
ai100[12]=1
ai100[21]=1
ai100[32]=2
ai100[43]=1
ai100[52]=1
ai100[67]=1
This method is useful for knowing occurrences of all elements
You can reduce the space by finding the length of new array using sorting and taking value of last element + 1
import java.util.Arrays;
public class ArrayMain {
public static void main(String[] args) {
int a[] = {52, 67, 32, 43, 32, 21, 12, 5, 0, 3, 2, 0, 0};
Arrays.sort(a);
int len=a[a.length-1]+1;
int count[]=new int[len];
for(int n:a){
count[n]++;
}
for(int j=0;j<count.length;j++){
if(count[j]>=1){
System.out.println("count:"+j+"---"+count[j]);
}
}
}
}
Time Complexity : O(n)
Space Complexity : O(R) // last element value +1
Note : Creating new array may not be good idea if you have extreme numbers like 1, 2 and 96, 99 etc in terms of space.
For this case sorting and comparing next element is better approach
import java.util.Scanner;
public class CountNumOccurences {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] frequency = new int[100];
System.out.println("Enter the first integer: ");
int number = input.nextInt();
//Enter up to 100 integers, 0 to terminate
while (number != 0){
++frequency[number];
//read the next integer
System.out.print(
"Enter the next int value (zero to exit): ");
number = input.nextInt();
}
input.close();
System.out.println("Value\tFrequency");
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > 0){
if (frequency[i] > 1)
System.out.println(i + " occurs " + frequency[i] + " times");
else
System.out.println(i + " occurs " + frequency[i] + " time");
}
}
}
}