【问题标题】:Sorting a list based on instructions in Javascript根据 Javascript 中的指令对列表进行排序
【发布时间】:2019-12-23 04:15:33
【问题描述】:

简而言之,我希望能够根据提供的指令输出排序数组,但只能在给定时间输出。我正在寻找一个 Javascript 实现,它或多或少类似于下面的示例。

简而言之,我希望能够根据提供的指令输出排序后的数组,而不是之前基于指令的输出。以下面的 Javascript 为例:

const list = new SortedListMechanism() // our object for processing instructions

list.insert({item: 'one'})
list.insert({item: 'four', after: 'one'})
list.insert({item: 'three', before: 'four', after:'two'})
list.insert({item:'two', after: 'one'})

list.compile() 
// returns ['one', 'two', 'three', 'four']

现在,我知道这是一个排序问题,但我不太确定我正在寻找什么样的排序问题,甚至不知道该叫什么。我确定存在支持此功能的 NPM 包,但老实说,我不知道要寻找什么。

作为背景,这是受到 Ruby on Rails 中使用的 ActiveSupport::Callback 机制的启发。

【问题讨论】:

  • 这需要确定性吗?如果您没有通过第“三”项,您会期望先“四”还是先“二”
  • 确实需要确定性。我希望“四”在“二”之前,因为它是先添加的。
  • 你尝试过什么,到底有什么问题?
  • 这看起来像topological sort。这应该会让你对 NPM 有所了解。
  • @AuxTaco Funny -- 就在今天 我开始阅读教科书中关于图算法的章节(Weiss, Data Structures and Algorithms in C++,第 9 章),并介绍了拓扑排序(9.2,第 382 页)。 wwahammy 如果您有兴趣实现它,这是一个很好的资源。

标签: javascript sorting computer-science


【解决方案1】:

AuxTaco 的想法是对的!是拓扑排序!

由于我不关心实现拓扑排序,我只使用 NPM 中的那个,特别是 @hapi/topo。

我是这样使用它的:

const Topo = require('@hapi/topo');

let list = new Topo()
let counter= 0
list.add('one', {group:'one'}) //this package requires adding the group name so we make it the same
list.add('four', {group: 'four', after: 'one', sort: counter++})
list.add('three', {group:'three', before: 'four', after:'two', sort: counter++})
list.add('two', {group: 'two', after: 'one', sort: counter++})

list.nodes
//returns ['one', 'two', 'three', 'four']

//example from Asthmatic's comment


list = new Topo()
counter = 0
list.add('one', {group:'one', sort: counter++}) //this package requires adding the group name so we make it the same
list.add('four', {group: 'four', after: 'one', sort: counter++})
list.add('two', {group: 'two', after: 'one', sort: counter++})

list.nodes
// returns ['one', 'four', 'two']

这似乎解决了这个问题。谢谢!

【讨论】:

    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2021-10-09
    • 2023-04-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多