The method I'm building should print all values above the average values in the method.
I have built the method to calculate the average and then print only the values above that amount.
However it prints the values that are positive.
int total = 0;
for (int i = 0; i < intList.length; i++)
{
total += intList[i];
{
if (intList[i] > intList[total])
{
System.out.println(intList[i] + "\t");
}
}
}
return total;
How do I make it so instead of printing all positives it prints only the values in the array above the average value in the array?
You need two different loops. One to add all the numbers together to get the total. Then you need to get the average from that total. Then loop again to check and print
public static void main(String[] args) {
int[] values = new int[] { 1, 5, 2, 6, 3, 7, 4, 8 };
double sum = 0;
for (int value : values)
sum += value;
double avg = sum / values.length;
System.out.printf("AVG = %.2f\n----------\n", avg);
for (int value : values) {
if (value > avg)
System.out.println(value);
}
}
Output:
AVG = 4.50
----------
5
6
7
8
You have to loop 2 times, one for calculating average and then when you get total calculated you have to change if comparision. intList[i] > intList[total] to intList[i] > total
Example :
public static void main(String args[]){
int[] intList = {1,2,3,4,5,6,7,8,9,10};
int total = 0;
// first loop calculate
for (int i : intList){
total += i;
}
double average = total / (double)intList.length;//take care array can't be empty.
System.out.println("average :"+ average);
//then show
for(int i : intList){
if (i > average){
System.out.println(i + "\t");
}
}
}
The answers above nailed it, your second loop isn't comparing it to the average, rather the total. You need one loop first to get the average of the array, and then a second one to test the array against the average.
for (int i = 0;i < array.count; i++){
total = total + array[i]
}
average = total / array.count
for (int i = 0;i < array.count; i++){
if (array[i]>total){
print
}
}
Theres some pseudocode/ish to get you going.
Related
Hi I'm having trouble subtracting one array element to the next element to get the correct answer. The value of the array are given by the user.
Example:
If the user wants to input 3 numbers which are 10, 8, 1
10-8-1 = 1
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
for(int t =0; t<number.length-1; t++)
{
total = number[t] - number[t+1];
}
System.out.println("total: " + total);
Change the 2nd loop to this:
total = number[0];
for (int i=1; i<number.length; i++) {
total -= number[i];
}
You want to subtract the remaining array items from the first one. Therefore total in the beginning should be equal to the first item and in the loop subtract each consequent (start from the index 1) item from the total.
Remember the number of items in the array must be equal to or larger than 2.
this line is totally wrong : total = number[t] - number[t+1]; as in the last loop
total = number[1] - number[2] which will be equivalent to total = 8 - 1 = 7 which is totally wrong because you have to accumulate the total variable .
so as mentioned above the full correct answer code is :
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
total = number[0];
for (int i=1; i<number.length; i++) {
total = total - number[i];
}
System.out.println("total: " + total);
}
}
and here is image of the output:
[][1]
Here is a one liner (computation wise) using streams. Take the first element, stream the array skipping the first element and subtract the sum of the remaining.
int[] arr = { 10, 8, 3, 1 };
int sum = arr[0] - IntStream.of(arr).skip(1).sum();
System.out.println(sum);
But no matter how you do it, you have the potential for int overflow or underflow depending on the size of your values and the length of the array.
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.
public static void main(String[] args) {
int arr[] = {6,6,6,6,6,6};
int matched = 1;
int value = 0;
int total = 0;
for(int i=0;i<arr.length;i++){
for(int j=(i+1);j<arr.length;j++){
if(ar[i] == ar[j]){
matched++;
value = ar[i];
break;
}
}
total = (matched * value);
} // End for loop
System.out.println("Matched:"+(matched)+"");
System.out.println("Total:"+total);
}
But, if the array was for example...
int arr[] = {6,1,1,6,6,6};
The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?
Interpreting the question as "provide the total number of values that occur more than once and their sum", and taking into account that nothing "fancy" (sic) such as a map can be used:
int[] array = {6, 1, 1, 6, 6, 6};
int sum = 0;
int matches = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (i != j && array[i] == array[j]) {
sum += array[i];
matches++;
break;
}
}
}
System.out.println(matches); // 6
System.out.println(sum); // 26
If you are allowed to use arrays - if not too fancy - then you could use 3 loops:
The first finds minimum and maximum elements
The second determines the occurrence of each item
The third calculates the totals
In Java this would look like this:
public static void main(String[] args) {
int[] array = {6, 3, 3, 6, 6, 6, 4, 4, 20};
int min = array[0];
int max = array[0];
// Find min max
for (int i : array) {
if (i < min) {
min = i;
}
if (i > max) {
max = i;
}
}
// Use array to sum up all elements
int[] holderArray = new int[max - min + 1];
for (int i : array) {
holderArray[i - min]++;
}
// Calculate occurrence and sums
for(int i = 0; i < holderArray.length; i++) {
if(holderArray[i] > 0) {
System.out.printf("number: %2d; count: %2d; sum: %2d%n", i + min, holderArray[i], (i + min) * holderArray[i]);
}
}
}
This prints out:
number: 3; count: 2; sum: 6
number: 4; count: 2; sum: 8
number: 6; count: 4; sum: 24
number: 20; count: 1; sum: 20
I don't completely understand your question, but based from what I understood, you want to get the sum of all matched numbers if its greater than 1? In that case there is a O(n) solution that you could use.
Create an empty Map then iterate over the array, and if the current number is not within the map add it to the map with value 1, if the current element is already existing in the map then just increment it's value (val++), at the end you will have a map and for each key (each distinct number) you will have the number of matched numbers from the array as the value. All you need to do is iterate over the pairs of key,val multiply each key*val then sum up the multiplied values and you get your correct total. And if you need just the number of matched, you can in another variable sum up just the vals.
So for lets say array [1,1,5,1,5,2,2,5,1], your map will something like:
{1:4, 2:2, 5:3},
and your totals:
total matches: 9
total: 23
I hope this helps!
Here is a code fragment I just wrote. This method takes in an array of integers and creates a map of each unique integer and it's count in the list. In the second part of the method, the HashMap object countOfNumbersMap is iterated and the sum of each element is printed.
private void findSumOfMatchingNumbers(int array[]) {
HashMap<Integer, Integer> countOfNumbersMap = new HashMap<>();
// Setting up the map of unique integers and it's count
for (int i = 0 ; i < array.length ; i++) {
if (countOfNumbersMap.containsKey(array[i])) {
int currentCount = countOfNumbersMap.get(array[i]);
countOfNumbersMap.put(array[i], currentCount + 1);
} else {
countOfNumbersMap.put(array[i], 1);
}
}
for (Integer integer : countOfNumbersMap.keySet()) {
int sum = countOfNumbersMap.get(integer) * integer;
System.out.println(String.format("Number = %d, Sum = %d", integer, sum));
}
}
The worst case runtime of the program is O(n).
If the range of your integers is limited, the easiest way to do this would be to create a histogram (i.e. create an array, where under index i you store the number of occurrences of the number i).
From that, it's easy to find elements that occur more than once, and sum them up. This solution has a complexity of O(n+k), where k is the range of your integers.
Another solution is to sort the array,then the matching numbers will be next to each other, and it's easy to count them. This has O(nlogn) complexity.
If these methods are not allowed, here is a solution in O(n^2) that only uses for loops:
Sum up the whole array
With a double loop, find all elements that are unique, subtract them from the sum, and count their number.
The remaining sum is the sum of all elements occurring more than once, and the count of unique elements subtracted from the length of the array gives the number of matching element.
I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>
I leave the normal answers for others to do. For java people,Here we go!
public static void main(String[] args) {
int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
System.out.println("Average is " + statisticalData.getAverage());
System.out.println("Sum is " + statisticalData.getSum());
}
Other data like count,minimum element,maximum element can also be obtained from the IntSummaryStatistics object
public static void main(String args[]) {
Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
int a[] = new int[10]; //Define an array
int i,sum = 0;
for(i = 0; i < 10; i++) {
a[i] = s.nextInt(); //Take the arrays elements as input from the user
}
for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
}
double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
System.out.print(sum + " " + avg); //print the result
}
At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.
int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;
for (int number : numbers) {
sum += number;
}
average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);
You can also iterate in this way:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
void sumAndAverage(int a[]){
if(a!=null&&a.length>0{
int sum=0;
//traverse array and add it to sum variable
for(int i=0;i<a.length;i++){
sum=sum+a[i];
}
double avg=(1.0*sum)/a.length;
System.out.println("sum= "+sum);
System.out.println("average= "+avg);
}
}
Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo
I'm having trouble figuring this out:
Write a fragment that uses a for statement to set the double variable sum to the value of:
Here's what I tried:
class thing
{
public static void main (String [] args)
{
double sum = 1;
for (int i = 1; i<=25; i++)
{
sum += Math.pow(i,1.0/i) ;
System.out.println(sum);
}
}
}
I know this is wrong because it does not end with the proper calculation of 1.137411462.
Any help is appreciated! :)
To add to the other replies above, that sum must start with 0, the calculation as you described isn't accurate.
The value of 25√25 is 1.137411462, not the sum from 1 to 25, in which case if you start with
int sum = 0;
You end up with the total: 30.85410561309813 which is the correct total that you want.
change sum to zero at start .you are adding additiona 1 to sum.
double sum = 0;
for (int i = 1; i<=25; i++)
{
sum += Math.pow(i,1.0/i) ;
}
System.out.println(sum);