Calculate average of an array and insert in another array - java

How can I calculate the average of an array, and insert it in another array and print that in the console.
For example, I have an array of size 100, and I wanna calculate the average of the numbers in the array and then insert in in an array of size 5.

Here's one way of doing it:
public class Main
{
public static void main(String[] args)
{
float averages[] = new float[5];
int aLotOfNumbers[] = new int[100];
// Initialize the numbers to 0, 1, 2, 3, 4, ..., 99
for(int i=0; i<100; i++)
{
aLotOfNumbers[i] = i;
}
// Compute the averages by summing groups of 20 numbers and dividing the sum by 20
for(int i=0; i<5; i++)
{
float runningSum = 0.0f;
for(int j=0; j<20; j++)
{
runningSum += aLotOfNumbers[i*20 + j];
}
averages[i] = runningSum / 20.0f;
}
// Print the 5 average values
for(int i=0; i<5; i++)
{
System.out.println("Average[" + i + "] = " + averages[i]);
}
}
}

Related

How to modify Rod-Cutting problem to take sizes which increase by more than one

Here is the code for the classic rod cutting problem. As the code stands, the sizes are 1, 2, 3, and 4, the size of the price array arr[]. How would I modify the code so that the sizes are set to different values other than those given. For example, 1, 2, 3 and 5 instead.
static double cutRod(double price[],int n)
{
double val[] = new double[n+1];
val[0] = 0;
for (int i = 1; i<=n; i++)
{
double max_val = Integer.MIN_VALUE;
for (int j = 0; j < i; j++)
max_val = Math.max(max_val,
price[j] + val[i-j-1]);
val[i] = max_val;
}
return val[n];
}
public static void main(String args[])
{
double arr[] = new double[] {1.2, 3, 5.8, 10.1};
int size = arr.length;
System.out.println("Maximum Obtainable Value is " +
cutRod(arr, size));
}
}
In the classical problem, j+1 in your inner loop represents the cut sizes possible. If you have custom cut sizes, store those in an array and use them instead of j + 1.
In the above program, let custom_sizes be the array storing the cuts, eg. 1,2,3,5, etc.
Modifying the above program:
static double cutRod(double price[],int custom_sizes[], int n)
{
double val[] = new double[n+1];
val[0] = 0;
for (int i = 1; i<=n; i++)
{
double max_val = Integer.MIN_VALUE;
for (int j = 0; j < custom_sizes.length; j++) {
if (i - custom_sizes[j] >= 0)
max_val = Math.max(max_val,
price[j] + val[i-custom_sizes[j]]);
}
val[i] = max_val;
}
return val[n];
}
Please note that it is assumed that input is valid and that price and custom_sizes are of equal length = n.

How to sort array in to 'bins', and print out stars for how many numbers are in that bin?

//so basically for all that is below, I'm trying to sort the random numbers that have been generated, and then 'sort' then into bins, and then for how many numbers there are in the bin, a star * will print out for every number. it will look like a histogram at the end. like this:
12 random integers in [0, 10) sorted into 2 bins:
******* 7 0.5833333 [5.0, 10.0)
***** 5 0.41666666 [0.0, 5.0)
but its like its skips that last two methods - generateBins, and printBins. how would i sort the random numbers into bins depending on the number (like above) and print a * for every number in that array bin?
public class BinSort {
final int totalBins;
final int totalRandom;
final float widthBin;
int [] storeNumbers;
int [] binCount;
public BinSort (int nBins, int nSamples, int max) {
totalBins = nBins; //total # of bins, ie 2
totalRandom = nSamples; //total random number generated, ie 12
widthBin = (float) (max/totalBins); ie 2
int [] storeNumbers = new int [max];
for (int i = 0; i < totalRandom-1; i++) {
storeNumbers[i] = Random.rand(i, max);
System.out.println(storeNumbers[i]);
}
}
void generateBins () {
int [] binCount = new int [totalBins];
for (int i=0; i < totalRandom-1; i++) {
int bin = (int)(storeNumbers[i]/ totalBins);
Math.floor(bin);
bin = binCount [i];
}
}
void printBins () {
for (int i = 0; i < binCount.length - 1; i++) {
for (int j=0; j < binCount[j]; j ++) {
System.out.print("*");
System.out.println(); }
float freq = (binCount[i]/totalRandom);
float binMin = (i * widthBin);
float binMax = (binMin * widthBin);
System.out.print(binCount[i] + freq + binMin + binMax);
System.out.println();
}
}
}
In your constructor you have
int [] storeNumbers = new int [max];
The problem here is that this will create a new local variable with the same name as your instance variable, storeNumbers. Also, the size should be totalRandom, not max. You need to create a Random object that you'll use to generate random numbers. Putting this together we get:
public BinSort (int nBins, int nSamples, int max) {
totalBins = nBins; //total # of bins, ie 2
totalRandom = nSamples; //total random number generated, ie 12
widthBin = (float) (max/totalBins); //ie 2
storeNumbers = new int [totalRandom];
Random rand = new Random();
for (int i = 0; i < totalRandom; i++) {
storeNumbers[i] = rand.nextInt(max);
}
}
This will generate totalRandom random numbers between 0 and max(exclusive) and store them the instance variable storeNumbers.
Next, in generateBins you have the same issue with
int [] binCount = new int [totalBins];
Which again will hide your instance variable binCount. The bin that a storeNumber falls into will be given by (int)(storeNumbers[i] / widthBin), and you need to increment the resulting bin by 1.
void generateBins()
{
binCount = new int[totalBins];
for (int i = 0; i < totalRandom; i++)
{
int bin = (int)(storeNumbers[i] / widthBin);
binCount[bin] += 1;
}
}
Finally, to the printing of the bins. This line
for (int j=0; j < binCount[j]; j ++)
should be
for (int j=0; j < binCount[i]; j ++)
Also, you should use printf to format the numbers you want to print.
void printBins()
{
for (int i = 0; i < binCount.length; i++)
{
for (int j = 0; j < binCount[i]; j++)
{
System.out.print("*");
}
float freq = (float)binCount[i] / totalRandom;
float binMin = i * widthBin;
float binMax = (i+1) * widthBin;
System.out.printf(" %d %.3f %.3f %.3f\n", binCount[i], freq, binMin, binMax);
}
}
Test:
public static void main(String[] args)
{
BinSort bs = new BinSort(2, 12, 10);
bs.generateBins();
bs.printBins();
}
Output:
***** 5 0.417 0.000 5.000
******* 7 0.583 5.000 10.000
Which I think is what you were looking for.
Be sure to compare your original code with the changes above and make sure you understand what the issues were and why the changes work.

java if statement in array for loop

Alright so I need to add some additional functions to this array, which gives 10 random integers. It needs to be able to store the numbers that are less than 40 and print them along with the numbers that are less than the average. How do I do this with an if statement in a for loop? (Ignore the stuff that's cometted out.
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
for(int i=0; i<ages.length; i++){ //adds stuff to arrays
ages[i] = gen.nextInt(100); //Determines the maximum used in random number generation
}
for(int x=0; x<10; x++){//prints the array with the below statement
System.out.println(ages[x]);
}
System.out.println("---------------");
System.out.println(ages[9]);
System.out.println(ages[8]);
System.out.println(ages[7]);
System.out.println(ages[6]);
System.out.println(ages[5]);
System.out.println(ages[4]);
System.out.println(ages[3]);
System.out.println(ages[2]);
System.out.println(ages[1]);
System.out.println(ages[0]);
int value = (ages[0] + ages[1] + ages[2] + ages[3] + ages[4] + ages[5] + ages[6] + ages[7] + ages[8] + ages[9]);
System.out.println("The combined value of the integers is " + value + ".");
int average = (value / 10);
System.out.println("The average value of the integers is " + average + ".");
}
}
Something like that? (Sorry guys for code but i don't have a time to make it better):
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
List<Integer> agesLesserThan40 = new ArrayList();
List<Integer> agesLesserThanAverage = new ArrayList();
float value = 0;
for(int i=0; i<10; i++) {
ages[i] = gen.nextInt(100);
value += ages[i];
}
for(int x=0; x<10; x++){
if(ages[x] < value/10) agesLesserThanAverage.add(ages[x]);
if(ages[x] < 40) agesLesserThan40.add(ages[x]);
}
System.out.println("ages:");
for(int z=0; z<10; z++){System.out.print(ages[z] + ", ");}
System.out.println();
System.out.println("Lesser than 40: ");
for(int y=0; y<agesLesserThan40.size()-1; y++){System.out.print(agesLesserThan40.get(y) + ", ");}
System.out.println();
System.out.println("Lesser than average: ");
for(int y=0; y<agesLesserThanAverage.size()-1; y++){System.out.print(agesLesserThanAverage.get(y) + ", ");}
System.out.println();
System.out.println("The average value of the integers is " + value / 10 + ".");
System.out.println("The combined value of the integers is " + value + ".");
}
}
I have no idea how if (value >= 100000) says anything is less than 40...
Here is probably how you could divide your array into above and under 40.
final int AGES_TO_GENERATE = 10;
final int AGE_LIMIT = 100;
final int AGE_DIVIDER = 40;
List<Integer> lesserAge = new ArrayList<>();
List<Integer> upperAge = new ArrayList<>();
Random gen = new Random();
double averageAge = 0.0;
for(int i=0; i<AGES_TO_GENERATE; i++){
int age = gen.nextInt(AGE_LIMIT);
averageAge += age;
if (age < AGE_DIVIDER) lesserAge.add(age);
else upperAge.add(age);
}
averageAge /= AGES_TO_GENERATE;
System.out.println("Here are the values less than 40");
System.out.println(lesserAge);
if (upperAge.isEmpty()) {
System.out.println("There are no values over 40");
}
If using Java 8, you can print values less than the average very simply
lesserAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);
upperAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);

java : Sum of Vertical elements in a triangle

I want to calculate the sum of all vertical elements in an triangle for example, if the triangle is
Ex : Triangle size is 5
1
2 2
5 2 2
2 0 5 8
8 7 9 4 5
Then the sum should be
Sum1 = 1+2+5+2+8 = 18 (Sum of vertical elements from the first column)
Sum2 = 2+2+0+7 = 11
Sum3 = 2+5+9 = 16
Sum4 = 8+4= 12
Sum5 = 5 = 5
Note : The triangle size will vary, also the elements will be random.
Program I wrote, but it's only calculating the first row how do i calculate and store the 2nd, 3rd and upto the last ?
public class fsdhs
{
public static void main(String args[])
{
int arr[]={1,2,2,5,2,2,2,0,5,8,8,7,9,4,5};
int x,y,count=0,size=5,sum=0;
boolean flag=false;
for(x=0;x<size;x++)
{
for(y=0;y<=x;y++)
{
if(flag==false)
{
sum=sum+arr[count];
flag=true;
}
System.out.print(arr[count]+" ");
count++;
}
System.out.print("\n");
flag=false;
}
System.out.print("\nSum1="+sum);
}
}
You can simplify your code and calculate col sums using the following formula to get index of array by index of i-th row in triangle and j-th column (j<=i, zero-based):
index = i*(i+1)/2 + j
For example, in given triangle at row i=3, column j=2 value is 5, so
index = 3*4/2 + 2 = 8, arr[8] is also 5
A more intuitive approach may be to use a multidimensional jagged array to store the triangle data. This way you can reason over the coordinates directly without needing to calculate row based offsets:
int arr[][]={{1},{2,2},{5,2,2},{2,0,5,8},{8,7,9,4,5}};
int size=5;
for(int x=0; x < size; x++)
{
int sum = 0;
for(int y=x; y < size; y++)
{
sum += arr[y][x];
}
System.out.println("Column " + x + " Sum=" + sum + "\n");
}
You just need to be wary of the uneven row sizes of the jagged array
IdeOne Demo
int SIZE = 5; // The size of your triangle
int arr[]={1,2,5,2,8,2,2,0,7,2,5,9,8,4,5}; // Array of triangle items
int[] sums = new int[SIZE];
for (int i = 0; i < arr.length; i += SIZE, SIZE--) {
for(int j = i; j < i + SIZE; j++) {
sums[sums.length - SIZE] += arr[j];
}
}
// Show items
for (int i = 0; i < sums.length; i++) {
System.out.println("item " + i + ": " + sums[i]);
}

Static methods and Jagged Arrays

I am trying to write a static method that returns an integer, takes a 2-dimensional array of integers as a parameter and return the index of the row in the 2-d array (jagged arrays) that has the largest sum of all its elements. Something went wrong along the line and im still trying to figure out. Help please?
Here is the code:
public static int findMaxRow(int[][] maxRows){
newI= 0;
newJ= 0;
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
`` if( newI > newJ){
return newI;
else {
}
}
}
}
You never define the type for newI or newJ, that can be fixed by preceding their declaration with their intended type (i.e int). You also have two " ` " before your if statement, and your missing a closing bracket " } " before your else statement. But those are just syntactical errors. Once you fix those errors you're going to notice that your method is not returning the desired results.
Looking at your code, specifically the for loops.
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
// other stuff
}
}
Let's say that maxRows.length equals 3. That means the outer loop is going to run from 0 to 2, so newI will equal 3. Meanwhile for each iteration the outer loop makes, the inner loop iterates 3 times. So newJ will end up equalling 9. Which is not the right way to go about summing the elements of an array. A better way to go about it, is to iterate over the arrays in the outer loop and sum the elements in the inner loop, then make a comparison completing the outer loop. Like so:
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
Here is an example of what you're trying to accomplish.
public class RowSums {
public static void main(String[] args) {
int[][] test = { {1, 5, 7, 0, 9} , {2, 4, 5, 6, 7} , {9, 2, 0, 12, 8, 3} };
System.out.println(printRows(test));
System.out.println("The row with the largest sum is row "
+ findMaxRow(test));
}
public static int findMaxRow(int[][] maxRows){
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
}
public static String printRows(int[][] rows) {
StringBuilder s = new StringBuilder("Rows and their sums:\n");
int sum;
for(int x = 0; x < rows.length; x++) {
s.append("Row [" + x + "] = [ ");
sum = 0;
for(int y = 0; y < rows[x].length; y++) {
s.append(rows[x][y] + " ");
sum += rows[x][y];
}
s.append("]\n");
s.append("Row [" + x + "]'s sum is " + sum + "\n");
}
return s.toString();
}
}
Output:
Rows and their sums:
Row [0] = [ 1 5 7 0 9 ]
Row [0]'s sum is 22
Row [1] = [ 2 4 5 6 7 ]
Row [1]'s sum is 24
Row [2] = [ 9 2 0 12 8 3 ]
Row [2]'s sum is 34
The row with the largest sum is row 2
Modifying your program, the following example will return the index of the row that has the largest sum of elements in it.
Let us suppose our array to be passed is:
int [][] maxRows = {{1,2,3}, {1,2,3,4,5}, {9,9,9,9}, {1,2}};
passing this array in the method
public static int findMaxRow(int[][] maxRows){
int sum = Integer.MIN_VALUE;
int biggestIndex= 0;
for(int i = 0; i<maxRows.length; i++){
int temp = 0;
for(int ir : maxRows[i]){
temp+=ir;
}
if(temp>sum){
sum = temp;
biggestIndex = i;
}
}
return biggestIndex;
}
The above program will return the index of the inner array which has the largest sum of elements, in above case, it will return 2 .

Categories