gpt4 book ai didi

java - 实现场景等规则的理想数据结构是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:46:25 24 4
gpt4 key购买 nike

考虑以下场景,其中 ID 定义的规则需要满足所有条件。

RULESID  Attribute1  Operator1  Value1   Attribute2  Operator2  Value1  ... And so on-------------------------------------------------------------------1    x            =          10         a         IN        5,10 2    x            =          20         a         IN        10,153    x            =          20         a         IN        25,20

The above means if(x=10) & if(a = 5 or a = 10} & ..., then ID = 1

In case of an incoming feed for the format [x, a, ...]

10, 5, ...10, 10, ...20, 20, ...

then IDs should be

113

I wish to check if there is a more easy and elegant way than the below solution and which data structure to be used.

What are the cons of the data structures & approach used in the below solution? (sure there could be)

Assumptions:

  1. The list of attributes is fixed for now but may change.
  2. The incoming feed format is fixed.
  3. Not on the lines of Java rules implementation.
  4. Algorithmic answer is accepted, Java 7 implementation is preferred.

My solution:

  1. The rule set is organized as Map<String, List<Criterion>>, where key is ID and Criterion contains attribute, operator and value as fields.

  2. The data is organized as List<Map<String, String>>, where key is the attribute (could be x or a etc.) and value as the actual value in the feed.

  3. For each entry in List<Map<String, String>, do below to find the ID

  4. Loop through each of the entries in Map<String, List<Criterion>> and invoke the below method. In case true is returned, I log the ID, which is the key and break the rule loop & proceeed to next data item.

    public boolean executeRules(List<Criterion> list,
    Map<String, String> dataItem) {
    boolean fullMatch = true;
    if(CollectionUtils.isNotEmpty(list)){
    for(Criterion rule : list) {
    switch (rule.getOperator()) {
    case EQUAL_TO: //Similar to EQUAL TO
    if(!rule.getValue().equals(dataItem.get(rule.getOperand()))){
    fullMatch = false;
    }
    break;
    case IN://Similar to IN
    List<String> inCriteria = null;
    if(rule.getValue() != null) {
    inCriteria = Arrays.asList(((String) rule.getValue()).split("\\s*,\\s*"));
    if(!inCriteria.contains(dataItem.get(rule.getOperand()))){
    fullMatch = false;
    }
    } else {
    fullMatch = false;
    }
    break;


    default:
    LOG.error("Invalid Operator: " + rule.getOperator());
    fullMatch = false;
    break;
    }
    if(!fullMatch) {
    return false;
    }

    }
    } else {
    LOG.error("No Rules found");
    return false;
    }

    return true;
    }

PS:不是作业;只是一些研究。

最佳答案

我认为您可以使用 SmartParam 库 ( http://smartparam.org/ )。它专为此类评估而设计,非常通用,因此即使与属性文件和数据库一起使用也可以使用

关于java - 实现场景等规则的理想数据结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21056457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com