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));
}
Related
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;
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 came across this interview question.
Write a program that accepts an array of integers and returns an integer whose digits consist of the numbers in that array?
For instance, if the array contains {1,2,3}, the method should return 123.
Thanks.
Currently I have this
public int transformArray(int [] numberArray){
for(int i=0; i<=numberArray.length;i++){
int number=number+number.CharAt(i);
}
}
You can concatenate each char to a string and convert it back to int:
public int transformArray(int [] numberArray){
String ans = "";
for(int i=0; i<=numberArray.length;i++){
ans = ans + numberArray[i];
}
return Integer.parseInt(ans)
}
Or multiply by 10 as David Conrad suggested
public int transformArray(int [] numberArray){
int ans = 0;
for(int i=0; i<=numberArray.length;i++){
ans = ans * 10;
ans = ans + numberArray[i];
}
return ans
}
Try something simple like:
int result = 0;
for (int i = 0; i<array.length; i++) {
result += array[i] * Math.pow(10, array.length - i - 1);
}
return result;
Use this:
public String getName() {
//create new ArrayList
ArrayList<Integer> numbers = new ArrayList<Integer>();
//add numbers
numbers.add(1);
numbers.add(9);
//for each element in the list, add the number
String s = "";
for(int i : numbers) {
s = s + i;
}
System.out.println("String: " + s);
return s;
}
The output of the method in this case:
String: 19
If you want the String s as an Integer use:
int i = Integer.parseInt(s)
I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.
A have array with numbers, for example 1,2,3,4,5.
I need to return the element which have nearest value to the average of whole array.
For example,
1+2+3+4+5=15
15/5=3
The result should be the number 3.
If there is no number that is the same as the average, the result should be the nearest number from the array.
I need only the method which will return that value.
Integer sum = 0;
Integer a = 0;
for(int i=0; i<array.getLength();i++)
{
a = array.get(i); sum=sum+a;
}
Integer average= sum/array.getLength();
return average;
}
I tried this, but it returns only the exact value as the average, not the nearest.
Here is simple solution. Probably there could be used some more clever algorithm to get most close value from array if it is sorted.
If there are two numbers that are both nearest to average thi one wich occurst first in array is chosen.
Edit changed the comparation so the lowest number nearest to average is foud.
public static Integer nearestToAverage(int[] res) {
if (res.length < 1) {
return null; //if there is no array return null;
}
int sum = 0; //variable to sum up the array
for (int i = 0; i < res.length; i++) {
int act = res[i];
sum += act; //adding elements of array to sum
}
int avg = sum / res.length; //computing the average value
int minDistance = Integer.MAX_VALUE; //set distance to integer max so it is higher than any of values in array
Integer ret = null; //setting return value to null it will be replaced with value from array
for (int i = 0; i < res.length; i++) {
int act = res[i];
int actDistance = Math.abs(act - avg); //computing distance of actual value and average
if ((actDistance < minDistance) || ((actDistance == minDistance) && (act < ret))) { //if it is less than actual minimal distance or it is the same and act number is lower than return value
minDistance = actDistance; //the distance is set to new
ret = act; //also is return value
}
}
return ret;
}
void findelement()
{
int[] arr = {1,2,3,4,5};
int a`enter code here`ve = 3, elem=0;
long tempi=0, tempdiff;
long diff=-1;
for(int i=0; i<arr.length;i++)
{
tempdiff = (long)arr[i]-(long)ave;
tempdiff = (tempdiff < 0 ? -tempdiff : tempdiff);
diff = (diff==-1)?tempdiff : diff;
if(diff>tempdiff){
diff = tempdiff;
elem = i;
}
}
System.out.println("hi element is "+elem+" and value near to average is "+arr[elem]);
}
Try this ::
int[] arr = {1,2,3,4,5};
double closeDiff = 0;
double arravg = getAverage(arr); // write a method which will return the average
int resultIndex = 0;
for(int i=1;i<arr.length;i++)
{
if(arr[i-1] > arr[i])
tempDiff = (arr[i-1] - arr[i]);
else
tempDiff = (-arr[i-1] + arr[i]);
if(tempDiff<closeDiff)
resultIndex = i;
}
return arr[i];