I'm trying to make an average (moy) of an arrayList's column but I need to sum it first, I don't know how to do it
int sumX = 0;
val = new ArrayList<>();
float moy[] = new float[3];
if (i < 100) {
val.add(sensorEvent.values);
i++;
} else {
for (; i > 0; i--);
{
sumX = ?
moy[0] = sumX/100;
}
val.clear();
i = 0;
}
Using DoubleStream:
Variants:
The input is an array of double
double[] values = new double[] {1.1D, 2.33D, 4D};
double average = DoubleStream.of(values).average().getAsDouble();
The input is an ArrayList of Integer
ArrayList<Integer> values = new ArrayList<>();
values.add(1);
values.add(42);
values.add(-1);
double average = values.stream().mapToDouble(value -> (double) value).average().getAsDouble();
You can use this code snippet: (Written in kotlin)
fun main() {
val s: List<Float> = listOf(1.2F, 1.4F, 5.6F)
// populate it with your custom list data
var sum = 0F
s.forEach { it ->
sum+=it
}
println("Sum = $sum and avg = ${sum/(s.size)}")
}
Well here is the java solution:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
List<Float> s = new ArrayList(Arrays.asList(1.2F, 1.3F, 5.4F, 6.5F));
Float sum = 0F;
for (int i=0; i< s.size(); i++) {
sum+=s.get(i);
}
System.out.println("Sum: "+sum+" and Avg: "+sum/(s.size()));
}
}
Here is how to sum all values in an ArrayList
ArrayList<Integer> nums = new ArrayList<>();
// Populate ArrayList
int sum = 0;
for (int num : nums) {
sum += num;
}
// Do whatever you want with sum after
Just use averaging collector in streams and you don't have to calculate SUM and NUMBER of elements:
ArrayList<Double> numbers = new ArrayList<>() {{
add(1d);
add(2.45d);
add(100d);
}};
final double average = numbers.stream()
.collect(Collectors.averagingDouble(d -> d));
moy[0] = average;
Related
I need an algorithm that accepts the total numbers count and the first number as input, where the sum of these numbers must be 100.
Examples:
Input:
count = 5,
first = 50
Output must be something LIKE that:
50, 30, 15, 3.5, 1.5
Input:
count = 7,
first = 30
Output must be something LIKE that:
30, 25, 20, 10, 7.5, 5, 2.5
it is not very important for me that the output is as I indicated it in the examples, it's all about
I just do this code, and I can't figure out how to integrate the "first" variable to it:
public class Main {
public static void main(String[] args) {
var count = 5;
var first = 50;
System.out.println(calc(first, count)); // [6.7, 13.3, 20.0, 26.7, 33.3]
}
private static List<BigDecimal> calc(double first, double count) {
double total = 100;
int multiplier = 0;
for (int i = 1; i <= count; i++) {
multiplier+=i;
}
BigDecimal a = BigDecimal.valueOf(total / multiplier);
List<BigDecimal> list = new ArrayList<>();
BigDecimal b = BigDecimal.ZERO;
for (int i = 0; i < count; i++) {
b = b.add(a);
list.add(b.setScale(1, RoundingMode.HALF_UP));
}
return list;
}
}
Why can't you subtract the first number from the total, and decrease count by 1?
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
var count = 5;
var first = 50;
System.out.println(calc(first, count)); // [6.7, 13.3, 20.0, 26.7, 33.3]
}
private static List<BigDecimal> calc(double first, double count) {
double total = 100 - first; // Decrease total by first
count--; // Decrement
int multiplier = 0;
for (int i = 1; i <= count; i++) {
multiplier+=i;
}
BigDecimal a = BigDecimal.valueOf(total / multiplier);
List<BigDecimal> list = new ArrayList<>();
list.add(BigDecimal.valueOf(first)); // Add first to list
BigDecimal b = BigDecimal.ZERO;
for (int i = 0; i < count; i++) {
b = b.add(a);
list.add(b.setScale(1, RoundingMode.HALF_UP));
}
return list;
}
}
I'm new to Java, so apologies.
I've got two arrays:
int[] grades = {64,55,45,67,65,88};
String[] unitCode = {"APP:","BSAD:","CF","DAD:","N&CS:","POP:"};
And I need to bring each one next to each other to form:
[APP:64, BSAD:55, CF45, DAD:67, N&CS:65, POP:88]
I've managed to achieve this with this code:
public String[] unitMarks(int[] grades, String[] unitCode)
{
double sum = 0;
for (double i : grades)
sum += i;
double average = (sum/grades.length);
for (int i = 0; i <grades.length; i++)
{
String combination = unitCode[i]+grades[i];
unitCode[i] = combination;
}
return unitCode;
}
But I also need to display the average grade at the end of it, so it should say:
[APP:64, BSAD:55, CF:45, DAD:67, N&CS:65, POP:88, Average:64.0]
I've already written the code for finding the average of the grades array. I'm just having trouble with returning the average with the combined array (and also displaying "Average:" before it).
I've tried doing things like -
String includedAverage = unitCode+" Average:"+average;
return includedAverage;
But then it starts saying that it can't convert from String to String[].
If i change the method return type to String it doesn't work with this:
System.out.println(Arrays.toString(myArrays.unitMarks(grades, unitCode)));
Any help or pointers would be great. Thanks.
You could add a result array which has one more space than your unitcode array and assign the values to it instead of modifing the input:
public String[] unitMarks(int[] grades, String[] unitCode) {
double sum = 0;
for (double i : grades) {
sum += i;
}
double average = (sum / grades.length);
String[] result = new String[grades.length +1];
for (int i = 0; i < grades.length; i++) {
String combination = unitCode[i] + grades[i];
result[i] = combination;
}
result[result.length-1]= "Average:"+average;
return result;
}
Two ways of doing this.
1. Use ArrayList which grows in size when you add elements to it
public List<String> unitMarks(int[] grades, String[] unitCode)
{
List<String> unitCodeArrayList = new ArrayList<String>();
double sum = 0;
for (double i : grades)
sum += i;
double average = (sum/grades.length);
for (int i = 0; i <grades.length; i++)
{
String combination = unitCode[i]+grades[i];
unitCodeArrayList.add(combination);
}
unitCodeArrayList.add("Average:"+average);
return unitCodeArrayList;
}
Use primitive array but append to it this way (as I am not sure what is the size of it)
public String[] unitMarks(int[] grades, String[] unitCode)
{
double sum = 0;
for (double i : grades)
sum += i;
double average = (sum/grades.length);
for (int i = 0; i <grades.length; i++)
{
String combination = unitCode[i]+grades[i];
unitCode[i] = combination;
}
String[] resUnitCode = appendArray(unitCode, "Average:"+average);
return resUnitCode;
}
private String[] appendArray(String[] array, String x){
String[] result = new String[array.length + 1];
for(int i = 0; i < array.length; i++)
result[i] = array[i];
result[result.length - 1] = x;
return result;
}
If you only need to display the values, you could use Stream to compute average and display in one go:
private void displayGradesAndAverage(int[] grades, String[] unitCode) {
IntStream.range(0, grades.length)
.peek(i -> System.out.print(unitCode[i] + grades[i] + ", "))
.map(i -> grades[i])
.average()
.ifPresent(avg -> System.out.println("Average:" + avg));
}
Code below generates 100 sorted random doubles from 0 to 100, then it's calculating average (avg) from those 100 numbers. My intention was to calculate 10 averages from those numbers and then sort them, but in many tries I get or my 100 sorted-random numbers or 1 average :(
How to get those 10 sorted averages?
public class NewMain {
private static Random rand = new Random();
public static void main(String[] args) {
System.out.println(Arrays.toString(sortowacz(100, 0, 100)));
}
public static Object[] sortowacz(final double length, final double min,
final double max) {
List<Double> nieposortowanaLista = randList(length, min, max);
Collections.sort(nieposortowanaLista);
return nieposortowanaLista.toArray();
}
private static List<Double> randList(final double length, final double min,
final double max) {
List<Double> list = new ArrayList<>();
List<Double> avg = new ArrayList<>();
double sum = 0.0;
for (int i = 0; i < length; i++) {
list.add(min + (max - min) * rand.nextDouble());
}
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
avg.add(sum / list.size());
return list;
}
}
This is your required code which calculate 10 averages out of 100 and sort them at the end
public class TestAverages {
public static void main(String... args) {
List<Double> averages = sortowacz(1000, 0, 100);
averages.forEach(System.out::println);
}
public static List<Double> sortowacz(final double length, final double min, final double max) {
List<Double> list = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < length; i++) {
list.add(min + (max - min) * rand.nextDouble());
}
List<Double> averages = new ArrayList<>();
while (!list.isEmpty()) {
List<Double> subList = list.subList(0, (int) (length/10));
double avg = subList.parallelStream().mapToDouble(d -> d).average().getAsDouble();
averages.add(avg);
list.removeAll(subList);
}
return averages;
}
}
I don't know what your multiple averages are but to get one you could use
List<Double> list=new ArrayList<>();
double average = list.stream().mapToDouble(d->d).average().getAsDouble();
Is it possible to iterate over a ArrayList adding not all instances but every 12? There are many threads on using addAll to add all instances but not sections.
I currently have an ArrayList containing hundreds of float values:
Snippet:
120.5, 22.2, 76.2, 64.5, 38.3, 27.1, 149.4, 62.3, 127.9, 79.1, 83.4, 68.3, 61.0, 83.4, 5.4, 83.8, 78.3, 111.8, 104.1, 145.2, 94.3, 20.0, 104.7, 35.9, 68.6, 10.1, 41.1, 82.2, 170.7, 17.2, 122.1, 61.0, 46.3, 101.1, 59.0, 30.0, ...
What I want to do is sum the first 12 instances and put this total in a new ArrayList, sum the next 12 instances, store this into the newly created ArrayList and so on. There are exactly 996 instances so i should have 83 new values in this new ArrayList (996/12=83).
Can this be done? If so how? Here is where I have got to...
// ArrayList that contains the float values shown above
public MonthData depthValues() {
ArrayList<Float> rValue = new ArrayList<>();
for (int i = 0; i<months.size(); i++)
{
rValue.add(months.get(i).getDepthMM());
}
System.out.println(rValue);
System.out.println(rValue.size());
return null;
}
//New arrayList im trying to make
//probably done this wrong, help needed here
public MonthData depthTotals() {
ArrayList<Float> depthAdd = new ArrayList<Float>();
int t = 12;
for(int i = 0; i<rValue.size(); ++i)
{
??????????????????
}
}
Any help will be greatly appreciated I cant seem to find anything on this anywhere as I think the sum of all instances is such a popular topic. Its probably a case of iterating properly. In regards to the summing I would have use accumulate in c++, but do not know the equivalent of this in java (if there is one). Thank you for any advice/assistance in advance!
MORE CODE:
public class WeatherStation {
private ArrayList<MonthData> months;
private ArrayList<MonthData> rValue;
private ArrayList<MonthData> depthAdd;
MonthData is a model for data being read to this class it consists on a lot of getters....
public class MonthData {
int y;
int m;
float h;
...
public MonthData(String data) throws Exception {
...
this.parseData(data);
}
void parseData(String csvData) {
String[] parseResult = csvData.trim().split("\\s+");
this.setYear(parseResult[0]);
this.setMonth(parseResult[1]);
...
public String toString() {
return "y =" + year + ", m =" + month + ",...
}
public int getY() {
return y;
}
// followed by lots of getters for: m, h, c, f, r, s, ...
public MonthData depthValues() {
ArrayList<Float> rValue = new ArrayList<>();
for (int i = 0; i<months.size(); i++)
{
rValue.add(months.get(i).getDepthMM());
}
System.out.println(rValue);
System.out.println(rValue.size());
return null;
}
Code recommended:
public MonthData depthTotals() {
ArrayList<Float> depthAdd = new ArrayList<>();
Iterator<Float> it = rValue.iterator();
final int MAX = 12;
while (it.hasNext()){
float sum = 0f;
int counter = 1;
//iterating 12 times
//still check if there is an element in list
while (counter < MAX && it.hasNext()){
sum += it.next();
counter++;
}
depthAdd.add(sum);}
}
ISSUE: Iterator<Float> it = rValue.iterator();
Type mismatch: cannot convert from Iterator<MonthData> to Iterator<Float>
The best way to do this is using Iterator and a counter of 12 by using a while. Here's an example:
List<Float> yourList = ...;
// fill yourList
List<Float> results = new ArrayList<>();
Iterator<Float> it = yourList.iterator();
final int MAX = 12;
while (it.hasNext()) {
float sum = 0f;
int counter = 1;
//iterating 12 times
//still, check if there's an element in your list
while (counter <= MAX && it.hasNext()) {
sum += it.next();
counter++;
}
result.add(sum);
}
I would recommend you use double or Double instead of float as it has around half a trillion times the accuracy.
You can sum every block of 12 like this
public static List<Double> sumBlocks(List<Double> list, int blockSize) {
List<Double> ret = new ArrayList<>();
for(int i = 0; i < list.size(); i += blockSize) {
double sum = 0;
for(int j = 0, len = Math.min(list.size() - i, blockSize); j < len; j++)
sum += list.get(i + j);
ret.add(sum);
}
return ret;
}
and call
List<Double> sums = sumBlocks(list, 12);
Just to demonstrate yet another way to accomplish this:
public static List<Double> sumBlocks(List<Double> list, int blockSize) {
List<Double> result = new ArrayList<>();
double sum = 0d;
for (int i = 0; i < list.size(); i++) {
if (i > 0 && i % blockSize == 0) {
result.add(sum);
sum = 0d;
}
sum += list.get(i);
}
result.add(sum);
return result;
}
Lista<Double> list = // original list
List<Double> ret = new ArrayList<>();
int counter = 0;
double sum = 0;
for (Double f : list) {
if (counter == 12) {
sum = 0;
counter = 0;
ret.add(sum);
}
sum += f;
counter++;
}
// if list is not a multiple of 12
if (list.size() % 12 != 0) {
ret.add(sum);
}
return ret;
try this:
public float total;
for(int i; i < rValue.Size(); i ++)
{
total += rValue[i];
if(i%12=0)
{
add total to new ArrayList
total = 0;
}
}
Arraylist objects inherit the sublist(start, end) method from the List class. You can use myList.sublist(i, j) to access the sublist and get your sum. From there, it should be just simple arithmetic to get your iteration. Inside your for-loop, it should be: myList.sublist(i*12, i*12 + 12).
//Input list
ArrayList<Float> inputList = new ArrayList<Float>();
ArrayList<Float> result = new ArrayList<Float>();
int groupSize = 12;
int offset=0;
while(offset < inputList.size()) {
int toIndex = (inputList.size()-offset)>=groupSize? offset+groupSize : inputList.size();
result.add( listSum(inputList.subList(offset, toIndex)) );
offset += groupSize;
}
Helper method to add items in a list
static float listSum(List<Float> ar) {
float accumulator = 0f;
for(float item:ar) {
accumulator += item;
}
return accumulator;
}
I need to implement four static methods in a class named ArrayStatistics. Each of the four methods will calculate the mean, median, mode, and population standard deviation, respectively, of the values in the array.
This is my first time working with Java, and cannot figure out what should I do next. I was given some test values for, you guessed it, test out my program.
public class ArrayStatistics {
public static void main(String[] args) {
final int[] arr;
int[] testValues = new int[] { 10, 20, 30, 40 };
meanValue = a;
meadianValue = b;
modeValue = c;
sqrtDevValue = d;
average = (sum / count);
System.out.println("Average is " );
}
static double[] mean(int[] data) {
for(int x = 1; x <=counter; x++) {
input = NumScanner.nextInt();
sum = sum + inputNum;
System.out.println();
}
return a;
}
static double[] median(int[] data) {
// ...
}
public double getMedian(double[] numberList) {
int factor = numberList.length - 1;
double[] first = new double[(double) factor / 2];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = numbersList[i];
}
for (int i = numberList.length; i > last.length; i--) {
last[i] = numbersList[i];
}
for (int i = 0; i <= numberList.length; i++) {
if (numberList[i] != first[i] || numberList[i] != last[i]) middleNumbers[i] = numberList[i];
}
if (numberList.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
return b;
}
}
static double[] mode(int[] data) {
public double getMode(double[] numberList) {
HashMap<Double,Double> freqs = new HashMap<Double,Double>();
for (double d: numberList) {
Double freq = freqs.get(d);
freqs.put(d, (freq == null ? 1 : freq + 1));
}
double mode = 0;
double maxFreq = 0;
for (Map.Entry<Double,Doubler> entry : freqs.entrySet()) {
double freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
mode = entry.getKey();
}
}
return c;
}
static double[] sqrt(int[] sqrtDev) {
return d;
}
}
This is pretty easy.
public double mean(ArrayList list) {
double ans=0;
for(int i=0; i<list.size(); i++) {
ans+=list.get(i); }
return ans/list.size()
}
`
Median:
public void median(ArrayList list) {
if(list.size()%==2) return (list.get(list.size()/2)+list.get(list.size()+1))/2;
else return list.get((list.size()/2)+1)
}
For Mode, just a keep a tally on the frequency of each number occurrence, extremely easy.
For standard deviation find the mean and just use the formula given here: https://www.mathsisfun.com/data/standard-deviation-formulas.html