多维数据查找

时间:2011-03-14 05:24:04

标签: data-structures

我有一组N值的元组。值可以是通配符(匹配任何值)或具体值。在不扫描整个集合并逐个测试项目的情况下,查找与特定元组匹配的集合中的所有元组的最佳方法是什么?

E.g。 1.2.3匹配1.*.3*.*.3,但不匹配1.2.4*.2.4

我在这里寻找什么数据结构?

1 个答案:

答案 0 :(得分:0)

我会使用trie来实现这一点。以下是我将如何构建trie:

数据结构如下:

Trie{
  Integer value
  Map<Integer, Trie> tries
}

要插入:

insert(tuple, trie){
  curTrie = trie
  foreach( number in tuple){
    nextTrie = curTrie.getTrie(number)
    //add the number to the trie if it isn't in there
    if(nextTrie == null){
      newTrie = new Trie(number)
      curTrie.setTrie(number, newTrie)          
    }
    curTrie = curTrie.getTrie(number)
  }
}

获取所有元组:

getTuples(tuple, trie){
  if(head(tuple) == "*"){
    allTuples = {}
    forEach(subTrie in trie){
      allTuples.union(getTuples(restOf(tuple), subTrie))
      forEach(partialTuple in allTuples){
        partialTuple = head(tuple)+partialTuple
      }
    }
    return allTuples
  }
  if(tuple == null)
    return {trie.value}

  if(trie.getTrie(head(tuple)) == null)
    raise error because tuple does not exist
  allTuples = {}
  allTuples.union(getTuples(restOf(tuple), trie.getTrie(head(tuple))
  forEach(partialTuple in allTuples){
    partialTuple = head(tuple)+partialTuple
  }
  return allTuples
}