简体   繁体   中英

How to add, calculate and filter those elements that are less than average without using repetitive cycles

I am using the ( List ) java structure:

var nums = List.of( 3, 9, 7, 12, 20, 4, 11, 9, 21, 6, 8, 10 );

Through that use, I am performing the following program without the need to use repetitive cycles:

    package averagesumwithoutcycles;
    import java.util.*;
    import java.util.List;
    
    public class SumaSinCiclos {
        
        private static int suma = 0;
    
    public static void main(String[] args) {
        int[] nums = {3, 9, 7, 12, 20, 4, 11, 9, 21, 6, 8, 10};
        System.out.println(average(nums, 0));
    }
    
    public static float average(int n[], int pos){
        float resultado = (float)suma /(float)n.length;
        if(pos < n.length) {
            suma = suma + n[pos];
            average(n, pos + 1);
            System.out.println(resultado);
        }
        return resultado;
    }
        
    }

So far I have achieved the following:

  • Sum of the Array elements
  • Number of elements in the Array
  • Division Result (Average)

My question is the following, based on my code, how can I sum the elements ( array ), calculate the average, and filter those elements that are less than the average.

Note: It is important to obtain this data without using repetitive cycles

Here's the best possible answer in my opinion. It does use loops internally, but any possible solution to get the sum of an array requires a loop (iterative or recursive).

import java.util.Arrays;
import java.util.stream.IntStream;

class Main {  
    private static int suma = 0;

    public static void main(String[] args) {
        int[] nums = {3, 9, 7, 12, 20, 4, 11, 9, 21, 6, 8, 10};
        for (int num : nums) {
            System.out.println(num);
        }
        nums = filter(nums, average(nums));
        System.out.println("____________\n");
        for (int num : nums) {
            System.out.println(num);
        }
    }
    
    public static float average(int[] n){
        float suma = IntStream.of(n).sum();
        return suma / n.length;
    }
    
    public static int[] filter(int[] nums, float average) {
        return Arrays.stream(nums).filter(x -> x >= average).toArray();
    }
}

You can always do something like this (but it is cumbersome).

int[] vals = {10,2,8}; 
int sum = 0;
sum += vals[0];
sum += vals[1];
sum += vals[2];
double avg = (double)sum/vals.length;

List<Integer> lessThan = new ArrayList<>();
if (vals[0] < avg) {
  lessThan.add(vals[0]);
}
if (vals[1] < avg) {
  lessThan.add(vals[1]);
}
if (vals[2] < avg) {
  lessThan.add(vals[2]);
}
System.out.println(lessThan); // prints 2

var nums = List.of( 3, 9, 7, 12, 20, 4, 11, 9, 21, 6, 8, 10 );

int sum = 0;
for (int v : nums) {
   sum+=v;
}
double avg = (double)sum/v.size();

once you have the average you can find the ones smaller as follows.

vars lessThan = new ArrayList<>();
for (int v : nums) {
    // store the numbers that are less than avg in the list.
}
Then print them here.

Maybe I'm missing something, but it looks like you solved the problem. In your code, you have the sum of elements and the average, and you don't use an explicit loop.

The only issue is having those elements who who are smaller than the average. A possible solution may be using a dedicated recursive function from the point you finished your first recursion (pass all elements, and checking them against the average [you already have] one by one on recursion).

Maybe something like:

public static void main(String[] args) {
    int[] nums = {3, 9, 7, 12, 20, 4, 11, 9, 21, 6, 8, 10};
    System.out.println(average(nums, 0, nums)); // Added "nums" again
}

public static float average(int n[], int pos, int originalElements[]){
    float resultado = (float)suma /(float)n.length;
    if(pos < n.length) {
        suma = suma + n[pos];
        average(n, pos + 1, originalElements);
        System.out.println(resultado);
    } else {
        // you will get hete only ONCE, in case pos = n.length
        // note that in this state, "resultado" contains the original array's average
        checkSmallThanAverage(resultado, 0, originalElements);
    }
    return resultado;
}

public static void checkSmallThanAverage(float resultado, int pos, int originalElements[]) {
     if(pos < originalElements.length) {
         if (originalElements[pos] < resultado) {
             System.out.println("element " + originalElements[pos] + " is smaller than average");
         }
         checkSmallThanAverage(resultado, pos+1, originalElements);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM