Home  >  Q&A  >  body text

java - How to better calculate the average of two Array data in the same format

There are two existing JSONArrays with the same format

One is newly added data

saveArray: [{"name":"name1","value":10},{"name":"name2","value":12},...,{}]

One is the average data

avgArray:[{"name":"name1","value":11},{"name":"name2","value":13},...,{}]

Know the number to calculate the average int num = 10;

Then based on the new data, after calculating the average value, update the existing average record:

Finally got:

newAvgArray: [{"name":"name 1","value":(10 x 11 10)/11},{"name":"name 2","value":(13 x 10 12) /11},...,{}]

The only way I can think of is:

for (int i = 0;i < avgArray.size();i++){
   avgObj = avgArray.get(i).get("value");
   addValue = saveArray.get(i).get("value");
   //然后计算新的值保存新的Array
}

Is there a better way to calculate

巴扎黑巴扎黑2675 days ago744

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-23 09:15:23

    No more.

    Algorithmically speaking, this is the most simplified. O(n)

    reply
    0
  • 为情所困

    为情所困2017-06-23 09:15:23

        public static void getNewArrayAvg(JSONArray add,JSONArray avg,int num){
            JSONArray res = new JSONArray();
            int size = add.size();
            int range = avg.size();
            for (int i = 0; i < size; i++) {
                String key = add.getJSONObject(i).getString("name");
                double avgNum = add.getJSONObject(i).getDoubleValue("value")/(num+1.0);
                for (int j = 0; j < range; j++) {
                    if (key.equals(avg.getJSONObject(j).getString("name"))) {
                        avgNum += avg.getJSONObject(j).getDoubleValue("value") * (num/(num+1.0));
                        JSONObject tmp = new JSONObject();
                        tmp.put("name", key);
                        tmp.put("value", avgNum);
                        res.add(tmp);
                        break;
                    }
                }
            }
            res.toString();
        }

    There should be a master who can use lambda to perform the arrogant operation, but as far as your requirements are concerned, you can only recalculate the value. In addition, you need to review the questions more.
    The following operation is not allowed. Make sure that the value of name can match.

       avgObj = avgArray.get(i).get("value");
       addValue = saveArray.get(i).get("value");

    reply
    0
  • Cancelreply