开发者

Recursive Table/Row Generator

I'm having a tough time wrapping my head around the following situation. The best way to explain may be by example

I have a Map<Column,Se开发者_运维知识库t<Row>> object. Let's say it contains the following data:

ColumnA['abc','def']
ColumnB['efg','hij','klm']
ColumnC['nop']
ColumnD['qrs','tuv','wxy','zzz']

I am trying to generate the following output:

Row1[abc,efg,nop,qrs]
Row2[abc,efg,nop,tuv]
Row3[abc,efg,nop,wxy]
Row4[abc,efg,nop,zzz]
Row5[abc,hij,nop,qrs]
Row6[abc,hij,nop,wxy]
etc...

So in this case there would be 24 rows total.

However, the number of columns and rows are both dynamic. I feel like this needs to be recursively done somehow but I'm not sure where to start.

Any help would be appreciated.

Update - I made a Tree structure that seems to work.

    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    Set<DefaultMutableTreeNode> curNodes = new HashSet<DefaultMutableTreeNode>();
    curNodes.add(root);

    final Set<Column> keys = map.keySet();
    for (final Column key : keys) {
        final Set<Row> rowSet = map.get(key);
        Set<DefaultMutableTreeNode> tmpNodes = new HashSet<DefaultMutableTreeNode>();
        for (final Row row : rowSet) {
            DefaultMutableTreeNode curNode = new DefaultMutableTreeNode();
            curNode.setUserObject(row);
            tmpNodes.add(curNode);
            for (DefaultMutableTreeNode n : curNodes) {
                n.add(curNode);
            }
        }
        curNodes = tmpNodes;
    }


I hope this is not some student's homework.

First to keep the order of the map's keys the same, use a SortedMap, like TreeMap. Furthermore in your initial map every Row contains just a single value like 'abc'. Recursion here is a depth-first traversal. The hard thing is that a map has not a natural traversal. For the rest have todos/candidates and dones/result; do a step changing data and afterwards restore them.

Here I use the more known List, but a Stack would be nicer.

public List<Row> generateRows(SortedMap<Column, Set<Cell>> map) {
    List<Row> done = new ArrayList<Row>();
    List<Column> columnsToDo = new LinkedList<Column>(map.keySet());
    List<Cell> partialRow = new LinkedList<Cell>();
    generateRowsRec(map, columnsToDo, partialRow, done);
    return done;
}
void generateRowsRec(SortedMap<Column, Set<Cell>> map, List<Column> columnsToDo, List<Cell> partialRow, List<Row> done) {
    if (columnsToDo.isEmpty()) {
        done.add(new Row(partialRow));
        return;
    }
    Column firstColumn = columnsToDo.remove(0); // Step A
    for (Cell cell : map.get(firstColumn)) {
        partialRow.add(cell); // Step B
        generateRowsRec(map, columnsToDo, partialRow, done);
        partialRow.remove(partialRow.size() - 1); // Unstep B
    }
    columnsToDo.add(0, firstColumn); // Unstep A
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜