当两个范围矛盾时需要帮助进行验证

时间:2019-09-20 12:30:25

标签: javascript arrays json reactjs object

我有一个对象名config,其中有“ from”和“ to”。

const config = {
  "0": {
    id: 0,
    from: 0,
    to: 10,
    hex: null
  },
  "1": {
    id: 1,
    from: 11,
    to: 20,
    hex: null
  },
  "2": {
    id: 2,
    from: 21,
    to: 30,
    hex: null
  },
  "3": {
    id: 3,
    from: 31,
    to: 40,
    hex: null
  },
  "4": {
    id: 4,
    from: 41,
    to: 50,
    hex: null
  }
};

我必须检查范围是否彼此矛盾,例如:form:0 => to:10 and from:5 => to:20 这里的第二个开始是矛盾的,因为5位于0到10之间

我已尝试关注但未完全满足我的要求

function found(conf) {
  let isFound = false;
  for (let obj in conf) {
    for (let x in conf) {
      if (
        conf[obj].id !== conf[x].id &&
        (conf[x].from >= conf[obj].from && conf[x].to <= conf[obj].from)
      ) {
        console.log(conf[obj], conf[x]);
        isFound = true;
        break;
      }
    }
    if (isFound) break;
  }
  return isFound;
}
console.log(found(config));

2 个答案:

答案 0 :(得分:1)

通过合并所有范围来创建单个数组

const arr = Object.entries(config).map(([a, b]) => b).flatMap(({from, to}) => RANGE(from, to))

其中RANGE是返回给定范围数组的方法:

const RANGE = (a,b) => Array.from((function*(x,y){
      while (x <= y) yield x++;
})(a,b));

然后使用以下函数在给定的arr中查找重复项:

function findDuplicate(array) { 
    var object = {};
    var result = [];
    array.forEach(function(item) {
      if (!object[item]) object[item] = 0;
      object[item] += 1;
    });
    for (var prop in object) {
      if (object[prop] >= 2) {
        result.push(prop);
      }
    }
    return result;
  }


const duplicates = findDuplicate(arr) 

然后最后检查duplicates.length

答案 1 :(得分:0)

尝试重命名变量,使它们有意义。

您的逻辑是:ID不匹配,并且内部在外部之后,但在外部之前。

在任何情况下都不会返回true。

23503
const config = {
  "0": { id: 0, from:  0, to: 10, hex: null },
  "1": { id: 1, from: 11, to: 20, hex: null },
  "2": { id: 2, from: 21, to: 30, hex: null },
  "3": { id: 3, from: 31, to: 40, hex: null },
  "4": { id: 4, from: 41, to: 50, hex: null }
};

console.log(found(config));

function found(conf) {
  for (let outer in conf) {
    for (let inner in conf) {
      let idsDontMatch = conf[outer].id !== conf[inner].id;
      let innerFromGteOuterFrom = conf[inner].from >= conf[outer].from;
      let innerToLteOuterFrom = conf[inner].to <= conf[outer].from;
      let innerAfterOuterButBeforeOuterFrom = innerFromGteOuterFrom && innerToLteOuterFrom;
      if (idsDontMatch && innerAfterOuterButBeforeOuterFrom) {
        console.log(conf[outer], conf[inner]);
        return true;
      }
    }
  }
  return false;
}