How to identify logical contradiction in sorting conditions?

别来无恙 提交于 2021-02-11 07:09:51

问题


I have a list of strings along with conditions that determine how they should be sorted.

The conditions can be simplified to the form, X before Y or X after Y.

However, one (or more) of the conditions contradict the rest.

Given a bunch of such conditions, I need to determine which conditions contradict the most other conditions so that I can eliminate the fewest conditions necessary to make them consistent with each other.

Once this is done, I will be able to reverse-engineer the original sorted array (which is not known to me).

The conditions below are consistent, but for illustration can be made contradictory in a way that causes an incorrect sorting by simply adding 'Sam' before 'Sue', as shown in the comments.

Such a tiny contradiction in such a tiny example can be identified by hand in a minute. But my real life case involves a list of close to 100 strings, and a few hundred conditions.

I am seeking first an answer to the question, "Is it feasible to identify not just any contradiction, but the fewest contradictions possible that can be eliminated to leave consistent conditions?"

And second, hopefully some help in how to approach this.

The contradiction used as an example here is easy to identify. But imagine if the conditions included among them, 'Sam' before 'Sue', 'Sue' before 'Bob', and 'Bob' before 'Sam'. Then it would not be nearly so obvious that there is a circular chain of conditions.

'use strict';

const sorted = ['Sam', 'Sue', 'Bob', 'Dylan'];

const conditions = {
  Sam: {
    before: ['Sue', 'Bob', 'Dylan'],
    after: [],
  },
  Sue: {
    before: ['Bob', 'Dylan'], // adding 'Sam' causes incorrect sort
    // and contradiction, because it can't be both before 'Sam' and after 'Sam'
    after: ['Sam']
  },
  Bob: {
    before: ['Dylan'],
    after: ['Sam', 'Sue']
  },
  Dylan: {
    before: [],
    after: ['Sam', 'Sue', 'Bob'],
  }
};

const unsorted = ['Bob', 'Dylan', 'Sam', 'Sue'];

const resorted = [...unsorted].sort((a, b) => {
  if (conditions[a].before.includes(b)) return -1;
  if (conditions[b].after.includes(b)) return 1;
  return 0;
});

console.log(resorted); // [ 'Sam', 'Sue', 'Bob', 'Dylan' ]

When I first tried this with contradictory conditions, I had hoped that the .sort() method would enter an infinite loop as a way to tell me there was a contradiction. But it actually sorts them anyway, just not correctly.

Otherwise I could have used trial and error to identify which conditions crashed the sorting function.

来源:https://stackoverflow.com/questions/63237270/how-to-identify-logical-contradiction-in-sorting-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!