简体   繁体   English

如何在不使用重复循环的情况下添加、计算和过滤那些低于平均值的元素

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

I am using the ( List ) java structure:我正在使用( List )java 结构:

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.我的问题如下,根据我的代码,我如何对元素( array )求和,计算平均值,并过滤那些小于平均值的元素。

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).一个可能的解决方案可能是从您完成第一次递归的那一刻起使用专用的递归 function(传递所有元素,并在递归时逐个检查它们与平均值 [你已经拥有])。

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);
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算数组的最大长度,使平均值小于给定值 - calculate the max length of an array such that average is less than given value 数组元素与平均值不同,小于数字 - Elements of array differ from average and less than number 使用低通滤波器来计算平均值? - Using a low pass filter to calculate average? 如何在不创建循环的情况下向有向无环图添加边 - How to add edges to a directed acyclic graph without creating cycles 如何计算文档数组外的字段与 MongoDB 和 Java 中的文档数组内的字段之间的平均值? - How can I calculate the average between fields outside a document array with those inside a documents array in MongoDB and Java? 如何计算大于平均值的数字的百分比。? - How to calculate the percentage of numbers that are greater than average.? Java中的正则表达式,用于“大于”或“小于”,而不使用方括号“ &lt;|&gt;” - Regex in Java for “greater than” or “less than” without using bracket “<|>” symbols Java如何计算某些元素随机删除的arrayList的平均值? - Java how to calculate average of an arrayList that some elements removed randomly? 所有页面都存在一个图标,如何在不使用重复代码的情况下进行编码? - An icon exists in all pages, how to code this without using repetitive code? 如何在logback.xml中添加小于(&lt;)和大于(&gt;) - How to add less than (<) and greater than (>) in logback.xml
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM