简体   繁体   中英

How to check if an integer value is in a given array of ranges and which array element

Got a json file which loads some configurations array as below:

configs.json

[
  {
    "category":"A",
    "scoreMargins" : [[12], [9,11], [7,9], [5,6], [3,4]]
  },
  {
    "category":"B",
    "scoreMargins" : [[3,4], [5,6], [7,8], [9,10], [11, 12]]
  }
]

The scoreMargins are not in one exact format, so its de-serialized as an object at the moment. But number of ranges(or single value) are always 5.

CalculationValues.java

 public class StressTestCategoryCalculationValues {
   private String category;
   private Object scoreMargins;
 }

service:

List<CalculationValues> values = mapper.readValue(CalculationValues.class.getResourceAsStream('configs.json'),
            mapper.getTypeFactory().constructCollectionType(List.class, CalculationValues.class));

Optional<CalculationValues> configA = values.stream()
            .filter(p -> p.getCategory().equals("A"))
            .findFirst();

int sumA = xx;
if (configA.isPresent()) {
    // logic
}

I want to get which scoreMargins array element holds the range that sumA falls into..

Ex:

"scoreMargins" : [[3,4], [5,8], [8,11], [11,12], [12, 13]], 

 sumA = 7, result ??

 Desired result =  2 (3rd element)

What would be the easiest approach to do this?

I have a solution but when using json, it does not guarantee to retain array order when being passed around between apis, therefore there is no guarantee your index is in any way accurate without returning the exact input json as a string with your index...

Therefore this is more of an example of deserializing 2d arrays in json.

int getIndex(CalcValues cv, int sumA) {

    for (List<Integer> sm : cv.getScoreMargins()) {
        sm = sm.stream().sorted().collect(Collectors.toList());

        if (sm.get(0) == sumA) {
            return cv.getScoreMargins().indexOf(sm);
        }

        if (sm.size() > 1 && sm.get(0) <= sumA && sm.get(1) >= sumA) {
            return cv.getScoreMargins().indexOf(sm);
        }

    }

    return 0;
}

class CalcValues {

    private String category;
    private List<List<Integer>> scoreMargins;

    // getter and setter

}

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