For my assignment I have to create a code that reads in 10 assignment grades, and calculates and displays the largest value, the smallest value, and the average. So far, I have been able to get my code to read in the 10 grades and calculate and display the average, however I need help with the part that displays the largest value entered and the smallest value entered.
I believe I will be using if statements for that.
Thanks for your time and help
I'm definitely not giving you code, but I'll suggest a start.
Set max to 0 and min to something huge, like Integer.MAX_VALUE.
When you read each value, if it's larger than the max, set the max to that value. If it's smaller than the min, set the min to that value.
Have two local variables.
int high = 0, lo=Integer.MAX_VALUE;
as your reading in values.
if ( value > high ) high = value;
if ( value < low ) low = value;
I will definitely not provide you with code either, but I will offer an approach to how you can do it:
Create a double[] with a size of 10
Read in 10 decimal numbers and assign them at different indexes within the array (index 0 = first input number, index 1 = second input number, index 2 = third input number, etc...)
Calculate the average of the array (sum of all elements / size of array)
Sort the array (you should probably use bubble sort or Arrays#sort if you're allowed)
Depending on how you sort it, the smallest value will be at index 0 (or 9) and the largest value will be at index 9 (or 0)
Print out the appropriate information
Add all the grades to an int array, then use these functions i've made for you
//This will find the largest number in your int array
public static int largestNumber(int[] numbers){
int largest = numbers[0];
for(int i = 0; i < numbers.length - 1; i++){//for each number in the array
if(numbers[i] > largest){//Check if that number is larger than the largest int recorded so far
largest = numbers[i];//If that number is larger, record it to be the largest, and continue on to the next number
}
}
return largest;//After checking each number, return the largest in the array
}
//This will find the lowest number in your int array, it works the same way as the last function does
public static int lowestNumber(int[] numbers){
int lowest= numbers[0];
for(int i = 0; i < numbers.length - 1; i++){
if(numbers[i] < lowest){
lowest= numbers[i];
}
}
return lowest;
}
Hope this helps you out! :)
Assign the first element of the array as the max and min ..
Then start traversing the array , and compare it with the other array elements.
if(a[i]>max)
max=a[i]
if(a[i]<min)
min=a[i]
at the end of the loop , you will have your answer
Related
I want to find the frequency of occurence for large value, like in the array largest value is 98, I want to find how many times it is repeating. Help me guys
public static void main(String[] args) {
int numbers[] = new int[]{32,43,53,25,98,54,32,65,63,98,43,23,25,98};
int largest = numbers[0];
for (int i=1; i< numbers.length; i++) {
if(numbers[i] > largest)
largest = numbers[i];
}
System.out.println("Largest Number is : " + largest);
}
Not sure if this is a homework question, so I'll try to help by giving you a design in pseudocode rather than Java.
Suppose you're looking at an element. There are three cases:
It's smaller than the previous max. Ignore it.
It's bigger than the previous max (or it's the first item). Make it the new max. As of now, its count must be 1.
It's equal to the previous max. Increment the max's count by 1.
You need to add a count variable. Reset this variable to one whenever you find a new largest value, and increment it whenever the value at your current index is equal to the largest number that you found so far.
Use a counter that you increment each time you see the largest value and reset each time you find a new larger value:
int largest = numbers[0];
int counter = 1;
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largest) {
largest = numbers[i];
counter = 1;
} elseif (numbers[i] == largest) {
counter++;
}
}
A conventional way to go about such a problem is to use a hash table. The first time you see an element, put it into the hash table with count = 1. Each time you see the same element after that, increase its count by 1. At the end, loop through the keys of the hash table and find the key which is the greatest, then output that key and its associated value (i.e. its count).
There may be solutions which are more efficient in some sense, but I'm guessing they are also more complicated. You can say whether you need to consider that.
In the following Java code:
int max = arr[0];
for (int i = 0; i < arr.length i++) {
if (arr[i] > max) {
max = arr[i];
}
}
How many times does the line max = arr[i]; run assuming that the array is unsorted.
Expected valued can be computated via linearity of expectations. I could provide a more rigorous answer if this site supported MathJax.
The answer is sum 1/(n-i+1) for i = 1 to n = sum 1/i for i = 1 to n = O(log n) where n is the size of the array (assuming all elements of the array are distinct)
Warning, Math-sy part ahead.
The key idea is that if we assign each element a lexicographical index 'i' where 'i' denotes that the element is the 'i'th smallest element, then an assignment will happen only if none of the n-i+1 larger elements apprar before the ith element in the array. The probability that this happens in a random array is 1/(n-i+1) for all i. Then we just apply linearity of expectations using an indicator random variable :)
I want to find The number of ways to divide an array into 3 contiguous parts such that the sum of the three parts is equal
-10^9 <= A[i] <= 10^9
My approach:
Taking Input and Checking for Base Case:
for(int i=0;i<n;i++){
a[i]= in.nextLong();
sum+=a[i];
}
if(sum%3!=0)System.out.println("0");
If The answer is not above Then Forming the Prefix and Suffix Sum.
for(int i=1;i<=n-2;i++){
xx+=a[i-1];
if(xx==sum/3){
dp[i]=1;
}
}
Suffix Sum and Updating the Binary Index Tree:
for(int i=n ;i>=3;i--){
xx+=a[i-1];
if(xx==sum/3){
update(i, 1, suffix);
}
}
And Now simple Looping the array to find the Total Ways:
int ans=0;
for(int i=1;i<=n-2;i++){
if(dp[i]==1)
{
ans+= (query(n, suffix) - query(i+1, suffix));
// Checking For the Sum/3 in array where index>i+1
}
}
I Getting the wrong answer for the above approachI don't Know where I have made mistake Please Help to Correct my mistake.
Update and Query Function:
public static void update(int i , int value , int[] arr){
while(i<arr.length){
arr[i]+=value;
i+=i&-i;
}
}
public static int query(int i ,int[] arr){
int ans=0;
while(i>0){
ans+=arr[i];
i-=i&-i;
}
return ans;
}
As far as your approach is concerned its correct. But there are some points because of which it might give WA
Its very likely that sum overflows int as each element can magnitude of 10^9, so use long long .
Make sure that suffix and dp array are initialized to 0.
Having said that using a BIT tree here is an overkill , because it can be done in O(n) compared to your O(nlogn) solution ( but does not matter if incase you are submitting on a online judge ).
For the O(n) approach just take your suffix[] array.And as you have done mark suffix[i]=1 if sum from i to n is sum/3, traversing the array backwards this can be done in O(n).
Then just traverse again from backwards doing suffix[i]+=suffix[i-1]( apart from base case i=n).So now suffix[i] stores number of indexs i<=j<=n such that sum from index j to n is sum/3, which is what you are trying to achieve using BIT.
So what I suggest either write a bruteforce or this simple O(n) and check your code against it,
because as far as your approach is concerned it is correct, and debugging is something not suited for
stackoverflow.
First, we calculate an array dp, with dp[i] = sum from 0 to i, this can be done in O(n)
long[]dp = new long[n];
for(int i = 0; i < n; i++)
dp[i] = a[i];
if(i > 0)
dp[i] += dp[i - 1];
Second, let say the total sum of array is x, so we need to find at which position, we have dp[i] == x/3;
For each i position which have dp[i] == 2*x/3, we need to add to final result, the number of index j < i, which dp[j] == x/3.
int count = 0;
int result = 0;
for(int i = 0; i < n - 1; i++){
if(dp[i] == x/3)
count++;
else if(dp[i] == x*2/3)
result += count;
}
The answer is in result.
What wrong with your approach is,
if(dp[i]==1)
{
ans+= (query(n, suffix) - query(i+1, suffix));
// Checking For the Sum/3 in array where index>i+1
}
This is wrong, it should be
(query(n, suffix) - query(i, suffix));
Because, we only need to remove those from 1 to i, not 1 to i + 1.
Not only that, this part:
for(int i=1;i<=n-2;i++){
//....
}
Should be i <= n - 1;
Similarly, this part, for(int i=n ;i>=3;i--), should be i >= 1
And first part:
for(int i=0;i<n;i++){
a[i]= in.nextLong();
sum+=a[i];
}
Should be
for(int i=1;i<=n;i++){
a[i]= in.nextLong();
sum+=a[i];
}
A lot of small errors in your code, which you need to put in a lot of effort to debugging first, jumping to ask here is not a good idea.
In the question asked we need to find three contiguous parts in an array whose sum is the same.
I will mention the steps along with the code snippet that will solve the problem for you.
Get the sum of the array by doing a linear scan O(n) and compute sum/3.
Start scanning the given array from the end. At each index we need to store the number of ways we can get a sum equal to (sum/3) i.e. if end[i] is 3, then there are 3 subsets in the array starting from index i till n(array range) where sum is sum/3.
Third and final step is to start scanning from the start and find the index where sum is sum/3. On finding the index add to the solution variable(initiated to zero), end[i+2].
The thing here we are doing is, start traversing the array from start till len(array)-3. On finding the sum, sum/3, on let say index i, we have the first half that we require.
Now, dont care about the second half and add to the solution variable(initiated to zero) a value equal to end[i+2]. end[i+2] tells us the total number of ways starting from i+2 till the end, to get a sum equal to sum/3 for the third part.
Here, what we have done is taken care of the first and the third part, doing which we have also taken care of the second part which will be by default equal to sum/3. Our solution variable will be the final answer to the problem.
Given below are the code snippets for better understanding of the above mentioned algorithm::-
Here we are doing the backward scanning to store the number of ways to get sum/3 from the end for each index.
long long int *end = (long long int *)calloc(numbers, sizeof(long long int);
long long int temp = array[numbers-1];
if(temp==sum/3){
end[numbers-1] = 1;
}
for(i=numbers-2;i>=0;i--){
end[i] = end[i+1];
temp += array[i];
if(temp==sum/3){
end[i]++;
}
}
Once we have the end array we do the forward loop and get our final solution
long long int solution = 0;
temp = 0;
for(i=0;i<numbers-2;i++){
temp+= array[i];
if(temp==sum/3){
solution+=end[i+2];
}
}
solution stores the final answer i.e. the number of ways to split the array into three contiguous parts having equal sum.
I have a sorted array. Let's say it is int [] numArr=new int[]{6, 9, 10, 27};
The smallest distance is between the 9 and the 10, and it is 1. The program should print this 1.
I am not expecting code, but I hope someone can give me an idea of how to proceed.
Declare a variable to hold the current minimum distance. It can be initialized to a really large number Integer.MAX_VALUE so that the first distance calculated becomes the initial minimum distance.
Use a for loop to loop over the values. You'll be accessing the element at the current index and the next index, so stop your for loop early to prevent an ArrayIndexOutOfBoundsException.
In the for loop, calculate the difference. If the difference is less than the current minimum, then update the current minimum to the current difference.
public static final int findSmallestDistance(final int[] pArray) {
int lMinimumDistance = Integer.MAX_VALUE;
for(int i = 1; i < pArray.length; i++) {
int lDifference = pArray[i] - pArray[i - 1];
if(lDifference < lMinimumDistance) {
lMinimumDistance = lDifference;
}
}
return lMinimumDistance;
}
Step 1: create a variable to save the actual smallest distance
Step 2: iterate through your array
Step 3: compare your actual number with the previous on your array (if this is the first element jump this step) and if it's smaller than your smallest save the result
Step 4: if the array has more elements, get the next one, else print your result
Here's some pseudocode:
Be smallest = a number surely greater than the one you're looking for
For each element i in array except the first
Be n = array[i] - array[i-1]
If n < smallest then
smallest = n
End If
End For
int numArr[] = {6, 9, 10, 27};
for(int i=0;i<numArr.length-1;i++){
if(numArr[i+1]-numArr[i]>0){
System.out.println("distance between " +numArr[i]+ " and "+numArr[i+1]+ " is: "+ (numArr[i+1]-numArr[i]));
}
}
int smallest = 100000
for (int i = 0; i < array.length; i++)
if(array[i+1]-array[i]<smallest)
{
smallest = array[i+1]-array[i];
}
System.out.println(smallest);
I need to use this method:
public static int countNegative(double[] numbers, int count){ }
to count the number of negative numbers in a double array. I could easily do it if I could include a 3rd parameter, sum, but I can only use the array and an int. I'm completely stuck. I've tried a few things, but cannot get it right. I've gotten everything from the size of the array to ArrayIndexOutOfBounds, but never the right answer. Could anyone help me out with this?
-EDIT-
Well here is the exact assignment:
Write a program that reads in a sequence of numbers (not necessary integers) from standard input until 0 is read, and stores them in an
array, similar to what you did in assignment 2. This part is done
using iteration . You may assume that there will not be more than 100
numbers.
Then compute the maximum number stored in the array, the count of
negative numbers, and compute the sum of positive numbers, using
recursion. Thus you will create recursive methods findMax,
countNegative, and computeSumPositive in Assignment9 class and they
will be called by a main method.
Specifically, the following recursive methods must be implemented
(These method should not contain any loop):
public static double findMax(double[] numbers, int count) -> It finds the maximum number in the array, count is the number of elements
in the array
public static int countNegative(double[] numbers, int count) ->
counts the negative integers
public static double computeSumPositive(double[] numbers, int count)
-> sums number of positive integers
findMax() was easy:
public static double findMax(double[] numbers, int count){
if(numbers.length - 1 == count)
return numbers[count];
else
return Math.max(numbers[count], findMax(numbers, count+1));
}
This is my most recent attempt at countNegative. It just returns 99 (I have the array initialized with 100 elements):
public static int countNegative(double[] numbers, int count){
int i=0;
if(numbers[count]<0)
i=1;
if(numbers.length-1==count)
return count;
else
return i+countNegative(numbers,count+1);
}
I should be able to figure out the computeSumPositive if I can figure out this negative one.
Count can be whatever you need it to be. I used it more as an index in findMax.
What is the use of count? It would make sense if it is index:
public static int countNegative(double[] numbers, int index)
{
if(index == numbers.length) return 0;
return (numbers[index] < 0 ? 1 : 0) + countNegative(numbers, index + 1);
}
and call it like this:
int count = countNegative(array, 0);
Use the int parameter as an index into the numbers array. Determine if the current index's value is negative (count 0 or 1 here). Then return the sum of that 0/1 count and the recursive call that looks at the next index position. The base case is when you've run past the end of the array, which returns 0.
public static int countNegative(double[] numbers, int count){
if(count == numbers.length){
return 0;
}
int sum = countNegative(numbers, count + 1);
if(numbers[count] < 0){
sum++;
}
return sum;
}
You call this method: countNegative(numbers, 0);
count is to be used as the base condition of recursion. You return the result back up the stack
Example:
double a[]={-12.0,1.0,0.0,23.0,-23.0,-9.0};
System.out.println(countNegative(a, 0));
I get 3 in console
Start by implementing it for an array with 0 elemtents. The for an array of 1 element. The for an array of more,usign the previous results...
here's how it might work
public static int countNegative(double[] numbers){
int result = numbers[0] < 0 ? 1 : 0;
if(numbers.length > 1) {
result += countNegative(Arrays.copyOfRange(numbers, 1, numbers.length));
}
return result;
}
You don't need the count parameter because of the way recursion works. when you call the function with an array it first determines if the first element is less than zero, making it negative. Next it checks if the array has more than one element, and if it does it calls itself with everything but the first element of the array and adds that to the result.
After that it returns the result which depending if it's in a recursive call or not, will either add it to the result of the call above it or give it back to the person calling it.