I have the following nested data structure:
Node 1
|--- Node 11
|--- Node 111
|--- Node 12
|--- Node 121
|--- Node 122
|--- Node 123
|--- Node 13
|--- Node 131
Node 2
|--- Node 21
|--- Node 211
|--- Node 212
etc.
and I'm trying to write an algorithm that converts it into a "plain" 2D matrix, like this:
| 1 | 11 | 111 |
| 1 | 12 | 121 |
| 1 | 12 | 122 |
| 1 | 12 | 123 |
| 1 | 13 | 131 |
| 2 | 21 | 211 |
| 2 | 21 | 212 |
etc.
however, I'm having a bit of trouble doing it efficiently, since I can't just traverse the tree and fill the matrix: as you can see the matrix has more cells than the tree has nodes, due to redundant data in all columns except the last.
Note that, like in the example, all leaves of the tree will have the same number of parents, i.e.: the same "nesting depth", so I don't need to account for shorter branches.
I'm sure there's already an algorithm that does this properly, but I don't know how this particular problem is called, so I couldn't find it. Can anyone help me out?
I'm not sure there is any specific name for this, maybe "tree flattening", but I suppose there are several ways in which you could flatten a tree anyway. You can do it with something like this (pseudocode since there is no language tag):
proc flatten_tree(tree : Node<Int>) : List<List<Int>>
matrix := []
flatten_tree_rec(tree, [], matrix)
return matrix
endproc
proc flatten_tree_rec(tree : Node<Int>, current : List<Int>, matrix : List<List<Int>>)
current.append(tree.value)
if tree.is_leaf()
matrix.append(current.copy())
else
for child in tree.children()
flatten_tree(child, current, matrix)
loop
endif
current.remove_last()
endproc
If you need to produce an actual matrix that needs to be preallocated you would need two passes, one to count the number of leafs and depth and another to actually fill the matrix:
proc flatten_tree(tree : Node<Int>) : List<List<Int>>
leafs, depth := count_leafs_and_depth(tree, 0)
matrix := Matrix<Int>(leafs, depth)
flatten_tree_rec(tree, [], matrix, 0)
return matrix
endproc
proc count_leafs_and_depth(tree : Node<Int>, base_depth : Int) : Int
if tree.is_leaf()
return 1, base_depth + 1
else
leafs := 0
depth := 0
for child in tree.children()
c_leafs, c_depth := count_leafs_and_depth(child, base_depth + 1)
leafs += c_leafs
depth = max(c_depth, depth)
loop
return leafs, depth
endif
endproc
proc flatten_tree_rec(tree : Node<Int>, current : List<Int>, matrix : Matrix<Int>, index : Int)
current.append(tree.value)
if tree.is_leaf()
matrix[index] = current
index += 1
else
for child in tree.children()
index = flatten_tree(child, current, matrix, index)
loop
endif
current.remove_last()
return index
endproc
Related
The problem is like this:
Each vertex has value Value[i] at i-th step.
(This graph is just a demonstration, not related to later example's calculation)
+----+-----+------+------+-----+-----+-----+----+-----+---- +------+-------+
| | | | | | | | | | | | |
Value for V1| 2 | 1 | 6 | 4 | 3| 4 | 5 | 1 | 9 | 1 | 10 | 2 |
| | | | | | | | | | | | |
+----+-----+------+------+-----+-----+-----+----+-----+----+------+-------+
This step is global step. so when we go from step 1 to step 2, All vertices' value index in its array moves.
The purpose is to find maximum path to gain max values in N steps.
so for example:
we have vertices A,B,C
A value array: 1,4,5,2,3
B value array: 2,1,1,5,4
C value array 3,2,9,6,1
graph: A -> B; B ->C; C ->A
N: 5 (steps you have)
Optimal path:(start from A always)
A->B->C->C->A
Value: 20
because if we do
A->B->C->C->C value is only 18.
What is the good algorithm to do this?
Dijkstra seems not fit into this.
You can find an optimal subpath ending at a particular vertex, for every step.
On the first step, find, for every vertex, the subpath ending at this vertex and leading to the maximum value. On the next steps, start with these previous values and repeat. The subpath (and value) is very easy to find, if you store the predecessor of each vertex : just pick the predecessor that has the maximum value.
Example with your input (and reflexive edges) :
A values : 1, 4, 5, 2, 3
B values : 2, 1, 1, 5, 4
C values : 3, 2, 9, 6, 1
A successors : A, B
B successors : B, C
C successors : A, C
A predecessors : A, C
B predecessors : A, B
C predecessors : B, C
Starting at A and the value 1, the first step leads to :
A max : 5 (subpath A->A)
B max : 2 (subpath A->B)
C max : 0 (no subpath)
Second step :
A max : 10 (subpath A->A->A) <- the predecessors of A are A and C,
and the previous max value of A
is greater than that of C.
B max : 5 (subpath A->A->B)
C max : 11 (subpath A->B->C)
Third step :
A max : 13 (subpath A->B->C->A)
B max : 15 (subpath A->A->A->B)
C max : 17 (subpath A->B->C->C)
Fourth and final step :
A max : 20 (path A->B->C->C->A)
B max : 19 (path A->A->A->B->B)
C max : 18 (path A->B->C->C->C)
In Weiss 'Data Structures and Algorithms In Java", he explains the insert algorithm for binary heaps thusly
public void insert( AnyType x )
{
if( currentSize == array.length -1)
enlargeArray( array.length * 2 + 1);
// Percolate up
int hole = ++currentSize;
for(array[0] = x; x.compareTo( array[ hole / 2 ]) < 0; hole /=2 )
array[ hole ] = array[ hole / 2 ];
array[ hole ] = x;
}
I get the principle of moving a hole up the tree, but I don't understand how he's accomplishing it with this syntax in the for loop... What does the initializer array[0] = x; mean? It seems he's overwriting the root value? It seems like a very contrived piece of code. What's he doing ere?
First off, I got a response from Mark Weiss and his email basically said the code was correct (full response at the bottom of this answer).
He also said this:
Consequently, the minimum item is in array index 1 as shown in findMin. To do an insertion, you follow the path from the bottom to the root.
Index 1? Hmmm... I then had to go back and re-read larger portions of the chapter and when I saw figure 6.3 it clicked.
The array is 0-based, but the elements that are considered part of the heap is stored from index 1 and onwards. Illustration 6.3 looks like this:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | A | B | C | D | E | F | G | H | I | J | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9 10 11 12 13
The placing of the value at element 0 is a sentinel value to make the loop terminate.
Thus, with the above tree, let's see how the insert function works. H below marks the hole.
First we place x into the 0th element (outside the heap), and places the hole at the next available element in the array.
H
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| x | A | B | C | D | E | F | G | H | I | J | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Then we bubble up (percolate) the hole, moving the values up from "half the index" until we find the right spot to place the x.
If we look at figure 6.5 and 6.6, let's place the actual values into the array:
H/2 H
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| 14 | 13 | 21 | 16 | 24 | 31 | 19 | 68 | 65 | 26 | 32 | | | |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Notice that we placed 14, the value to insert, into index 0, but this is outside the heap, our sentinel value to ensure the loop terminates.
Then we compare the value x with the value at hole / 2, which now is 11/2 = 5. x is less than 31, so we move the value up and move the hole:
H/2 H <---------------------------
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| 14 | 13 | 21 | 16 | 24 | 31 | 19 | 68 | 65 | 26 | 32 | 31 | | |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
0 1 2 3 4 5 6 7 8 9 10 11 12 13
| ^
+--------- move 31 -----------+
We compare again, 14 is again less than 21 (5 / 2 = 2), so once more:
H/2 H <------------
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| 14 | 13 | 21 | 16 | 24 | 21 | 19 | 68 | 65 | 26 | 32 | 31 | | |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
0 1 2 3 4 5 6 7 8 9 10 11 12 13
| ^
+-- move 21 ---+
Now, however, 14 is not less than 13 (hole / 2 --> 2 / 1 = 1), so we've found the right spot for x:
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| 14 | 13 | 14 | 16 | 24 | 21 | 19 | 68 | 65 | 26 | 32 | 31 | | |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
0 1 2 3 4 5 6 7 8 9 10 11 12 13
^
x
As you can see, if you look at illustrations 6.6 and 6.7, this matches the expected behavior.
So while the code isn't wrong, you got one little snag that is perhaps outside of scope of the book.
If the type of x being inserted is a reference type, you will in the current heap have 2 references to the same object just inserted. If you then immediately delete the object from the heap, it looks (but look where looking like got us in the first place...) like the 0th element will still retain the reference, prohibiting the garbage collector from doing its job.
To make sure there's no hidden agenda here, here is the complete answer from Mark:
Hi Lasse,
The code is correct.
The binary heap is a complete binary tree in which on any path from a
bottom to the root, values never increase. Consequently the minimum
item is at the root. The array representation places the root at
index 1, and for any node at index i, the parent is at i/2 (rounded
down) (the left child is at 2i and the right child at 2i+1, but that
is not needed here).
Consequently, the minimum item is in array index 1 as shown in
findMin. To do an insertion, you follow the path from the bottom to
the root.
In the for loop:
hole /= 2 expresses the idea of moving the hole to the parent.
x.compareTo( array[ hole / 2 ]) < 0 expresses the idea that we stay in
the loop as long as x is smaller than the parent.
The problem is that if x is a new minimum, you never get out of the
loop safely (technically you crash trying to compare x and array[0]).
You could put in an extra test to handle the corner case.
Alternatively, the code gets around that by putting x in array[0] at
the start, and since the "parent" of node i is i/2, the "parent" of
the root which is in index 1 can be found in index 0. This guarantees
the loop terminates if x is the new minimum (and then places x, which
is the new minimum in the root at index 1).
A longer explanation is in the book... but the basic concept here is
that of using a sentinel (or dummy) value to avoid extra code for
boundary cases.
Regards,
Mark Weiss
The array initialiser looks wrong. If it were array[hole] = x;, then the whole thing makes perfect sense.
It first puts the value in the lowest rank of the tree (the entry after the current size), then it looks in the entry `above it' by looking at (int) hole/2.
It keeps moving it up until the comparator tells it to stop. I think that this is a slight misuse of the syntax of a for loop, since it feels like its really a while(x.compare(hole/2) < 0) type loop.
As example I have next arrays:
[100,192]
[235,280]
[129,267]
As intersect arrays we get:
[129,192]
[235,267]
Simple exercise for people but problem for creating algorithm that find second multidim array…
Any language, any ideas..
If somebody do not understand me:
I'll assume you wish to output any range that has 2 or more overlapping intervals.
So the output for [1,5], [2,4], [3,3] will be (only) [2,4].
The basic idea here is to use a sweep-line algorithm.
Split the ranges into start- and end-points.
Sort the points.
Now iterate through the points with a counter variable initialized to 0.
If you get a start-point:
Increase the counter.
If the counter's value is now 2, record that point as the start-point for a range in the output.
If you get an end-point
Decrease the counter.
If the counter's value is 1, record that point as the end-point for a range in the output.
Note:
If a start-point and an end-point have the same value, you'll need to process the end-point first if the counter is 1 and the start-point first if the counter is 2 or greater, otherwise you'll end up with a 0-size range or a 0-size gap between two ranges in the output.
This should be fairly simple to do by having a set of the following structure:
Element
int startCount
int endCount
int value
Then you combine all points with the same value into one such element, setting the counts appropriately.
Running time:
O(n log n)
Example:
Input:
[100, 192]
[235, 280]
[129, 267]
(S for start, E for end)
Points | | 100 | 129 | 192 | 235 | 267 | 280 |
Type | | Start | Start | End | Start | End | End |
Count | 0 | 1 | 2 | 1 | 2 | 1 | 0 |
Output | | | [129, | 192] | [235, | 267] | |
This is python implementation of intersection algorithm. Its computcomputational complexity O(n^2).
a = [[100,192],[235,280],[129,267]]
def get_intersections(diapasons):
intersections = []
for d in diapasons:
for check in diapasons:
if d == check:
continue
if d[0] >= check[0] and d[0] <= check[1]:
right = d[1]
if check[1] < d[1]:
right = check[1]
intersections.append([d[0], right])
return intersections
print get_intersections(a)
I'm designing an algorithm to test whether cells on a grid are adjacent or not.
The catch is that the cells are not on a flat grid. They are on a multi-level grid such as the one drawn below.
Level 1 (Top Level)
| - - - - - |
| A | B | C |
| - - - - - |
| D | E | F |
| - - - - - |
| G | H | I |
| - - - - - |
Level 2
| -Block A- | -Block B- |
| 1 | 2 | 3 | 1 | 2 | 3 |
| - - - - - | - - - - - |
| 4 | 5 | 6 | 4 | 5 | 6 | ...
| - - - - - | - - - - - |
| 7 | 8 | 9 | 7 | 8 | 9 |
| - - - - - | - - - - - |
| -Block D- | -Block E- |
| 1 | 2 | 3 | 1 | 2 | 3 |
| - - - - - | - - - - - |
| 4 | 5 | 6 | 4 | 5 | 6 | ...
| - - - - - | - - - - - |
| 7 | 8 | 9 | 7 | 8 | 9 |
| - - - - - | - - - - - |
. .
. .
. .
This diagram is simplified from my actual need but the concept is the same. There is a top level block with many cells within it (level 1). Each block is further subdivided into many more cells (level 2). Those cells are further subdivided into level 3, 4 and 5 for my project but let's just stick to two levels for this question.
I'm receiving inputs for my function in the form of "A8, A9, B7, D3". That's a list of cell Ids where each cell Id has the format (level 1 id)(level 2 id).
Let's start by comparing just 2 cells, A8 and A9. That's easy because they are in the same block.
private static RelativePosition getRelativePositionInTheSameBlock(String v1, String v2) {
RelativePosition relativePosition;
if( v1-v2 == -1 ) {
relativePosition = RelativePosition.LEFT_OF;
}
else if (v1-v2 == 1) {
relativePosition = RelativePosition.RIGHT_OF;
}
else if (v1-v2 == -BLOCK_WIDTH) {
relativePosition = RelativePosition.TOP_OF;
}
else if (v1-v2 == BLOCK_WIDTH) {
relativePosition = RelativePosition.BOTTOM_OF;
}
else {
relativePosition = RelativePosition.NOT_ADJACENT;
}
return relativePosition;
}
An A9 - B7 comparison could be done by checking if A is a multiple of BLOCK_WIDTH and whether B is (A-BLOCK_WIDTH+1).
Either that or just check naively if the A/B pair is 3-1, 6-4 or 9-7 for better readability.
For B7 - D3, they are not adjacent but D3 is adjacent to A9 so I can do a similar adjacency test as above.
So getting away from the little details and focusing on the big picture. Is this really the best way to do it? Keeping in mind the following points:
I actually have 5 levels not 2, so I could potentially get a list like "A8A1A, A8A1B, B1A2A, B1A2B".
Adding a new cell to compare still requires me to compare all the other cells before it (seems like the best I could do for this step
is O(n))
The cells aren't all 3x3 blocks, they're just that way for my example. They could be MxN blocks with different M and N for
different levels.
In my current implementation above, I have separate functions to check adjacency if the cells are in the same blocks, if they are in
separate horizontally adjacent blocks or if they are in separate
vertically adjacent blocks. That means I have to know the position of
the two blocks at the current level before I call one of those
functions for the layer below.
Judging by the complexity of having to deal with mulitple functions for different edge cases at different levels and having 5 levels of nested if statements. I'm wondering if another design is more suitable. Perhaps a more recursive solution, use of other data structures, or perhaps map the entire multi-level grid to a single-level grid (my quick calculations gives me about 700,000+ atomic cell ids). Even if I go that route, mapping from multi-level to single level is a non-trivial task in itself.
I actually have 5 levels not 2, so I could potentially get a list like "A8A1A, A8A1B, B1A2A, B1A2B".
Adding a new cell to compare still requires me to compare all the other cells before it (seems like the best I could do for this step is
O(n))
The cells aren't all 3x3 blocks, they're just that way for my example. They could be MxN blocks with different M and N for different
levels.
I don't see a problem with these points: if a cell is not adjacent at the highest level one then we can stop the computation right there and we don't have to compute adjacency at the lower levels. If there are only five levels then you'll do at most five adjacency computations which should be fine.
In my current implementation above, I have separate functions to check adjacency if the cells are in the same blocks, if they are in separate horizontally adjacent blocks or if they are in separate vertically adjacent blocks. That means I have to know the position of the two blocks at the current level before I call one of those functions for the layer below.
You should try to rewrite this. There should only be two methods: one that computes whether two cells are adjacent and one that computes whether two cells are adjacent at a given level:
RelativePosition isAdjacent(String cell1, String cell2);
RelativePosition isAdjacentAtLevel(String cell1, String cell2, int level);
The method isAdjacent calls the method isAdjacentAtLevel for each of the levels. I'm not sure whether cell1 or cell2 always contain information of all the levels but isAdjacent could analyze the given cell strings and call the appropriate level adjacency checks accordingly. When two cells are not adjacent at a particular level then all deeper levels don't need to be checked.
The method isAdjacentAtLevel should do: lookup M and N for the given level, extract the information from cell1 and cell2 of the given level and perform the adjacency computation. The computation should be the same for each level as each level, on its own, has the same block structure.
Calculate and compare the absolute x and y coordinate for the lowest level.
For the example (assuming int index0 = 0 for A, 1 for B, ... and index1 = 0...8):
int x = (index0 % 3) * 3 + index1 % 3;
int y = (index0 / 3) * 3 + index1 / 3;
In general, given
int[] WIDTHS; // cell width at level i
int[] HEIGHTS; // cell height at level i
// indices: cell index at each level, normalized to 0..WIDTH[i]*HEIGHT[i]-1
int getX (int[] indices) {
int x = 0;
for (int i = 0; i < indices.length; i++) {
x = x * WIDTHS[i] + indices[i] % WIDTHS[i];
}
return x;
}
int getY (int[] indices) {
int y = 0;
for (int i = 0; i < indices.length; i++) {
y = y * HEIGHTS[i] + indices[i] / WIDTHS[i];
}
return x;
}
You can use a space filling curve, for example a peano curve or z morton curve.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
You are given a set of blocks to build a panel using 3”×1” and 4.5”×1" blocks.
For structural integrity, the spaces between the blocks must not line up in adjacent rows.
There are 2 ways in which to build a 7.5”×1” panel, 2 ways to build a 7.5”×2” panel, 4 ways to build a 12”×3” panel, and 7958 ways to build a 27”×5” panel. How many different ways are there to build a 48”×10” panel?
This is what I understand so far:
with the blocks 3 x 1 and 4.5 x 1
I've used combination formula to find all possible combinations that the 2 blocks can be arranged in a panel of this size
C = choose --> C(n, k) = n!/r!(n-r)! combination of group n at r at a time
Panel: 7.5 x 1 = 2 ways -->
1 (3 x 1 block) and 1 (4.5 x 1 block) --> Only 2 blocks are used--> 2 C 1 = 2 ways
Panel: 7.5 x 2 = 2 ways
I used combination here as well
1(3 x 1 block) and 1 (4.5 x 1 block) --> 2 C 1 = 2 ways
Panel: 12 x 3 panel = 2 ways -->
2(4.5 x 1 block) and 1(3 x 1 block) --> 3 C 1 = 3 ways
0(4.5 x 1 block) and 4(3 x 1 block) --> 4 C 0 = 1 way
3 ways + 1 way = 4 ways
(This is where I get confused)
Panel 27 x 5 panel = 7958 ways
6(4.5 x 1 block) and 0(3 x 1) --> 6 C 0 = 1 way
4(4.5 x 1 block) and 3(3 x 1 block) --> 7 C 3 = 35 ways
2(4.5 x 1 block) and 6(3 x 1 block) --> 8 C 2 = 28 ways
0(4.5 x 1 block) and 9(3 x 1 block) --> 9 C 0 = 1 way
1 way + 35 ways + 28 ways + 1 way = 65 ways
As you can see here the number of ways is nowhere near 7958. What am I doing wrong here?
Also how would I find how many ways there are to construct a 48 x 10 panel?
Because it's a little difficult to do it by hand especially when trying to find 7958 ways.
How would write a program to calculate an answer for the number of ways for a 7958 panel?
Would it be easier to construct a program to calculate the result? Any help would be greatly appreciated.
I don't think the "choose" function is directly applicable, given your "the spaces between the blocks must not line up in adjacent rows" requirement. I also think this is where your analysis starts breaking down:
Panel: 12 x 3 panel = 2 ways -->
2(4.5 x 1 block) and 1(3 x 1 block)
--> 3 C 1 = 3 ways
0(4.5 x 1 block) and 4(3 x 1 block)
--> 4 C 0 = 1 way
3 ways + 1 way = 4 ways
...let's build some panels (1 | = 1 row, 2 -'s = 1 column):
+---------------------------+
| | | | |
| | | | |
| | | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
Here we see that there are 4 different basic row types, but none of these are valid panels (they all violate the "blocks must not line up" rule). But we can use these row types to create several panels:
+---------------------------+
| | | | |
| | | | |
| | | |
+---------------------------+
+---------------------------+
| | | | |
| | | | |
| | | |
+---------------------------+
+---------------------------+
| | | | |
| | | | |
| | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
...
But again, none of these are valid. The valid 12x3 panels are:
+---------------------------+
| | | | |
| | | |
| | | | |
+---------------------------+
+---------------------------+
| | | |
| | | | |
| | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
+---------------------------+
| | | |
| | | |
| | | |
+---------------------------+
So there are in fact 4 of them, but in this case it's just a coincidence that it matches up with what you got using the "choose" function. In terms of total panel configurations, there are quite more than 4.
Find all ways to form a single row of the given width. I call this a "row type". Example 12x3: There are 4 row types of width 12: (3 3 3 3), (4.5 4.5 3), (4.5 3 4.5), (3 4.5 4.5). I would represent these as a list of the gaps. Example: (3 6 9), (4.5 9), (4.5 7.5), (3 7.5).
For each of these row types, find which other row types could fit on top of it.
Example:
a. On (3 6 9) fits (4.5 7.5).
b. On (4.5 9) fits (3 7.5).
c: On (4.5 7.5) fits (3 6 9).
d: On (3 7.5) fits (4.5 9).
Enumerate the ways to build stacks of the given height from these rules. Dynamic programming is applicable to this, as at each level, you only need the last row type and the number of ways to get there.
Edit: I just tried this out on my coffee break, and it works. The solution for 48x10 has 15 decimal digits, by the way.
Edit: Here is more detail of the dynamic programming part:
Your rules from step 2 translate to an array of possible neighbours. Each element of the array corresponds to a row type, and holds that row type's possible neighbouring row types' indices.
0: (2)
1: (3)
2: (0)
3: (1)
In the case of 12×3, each row type has only a single possible neighbouring row type, but in general, it can be more.
The dynamic programming starts with a single row, where each row type has exactly one way of appearing:
1 1 1 1
Then, the next row is formed by adding for each row type the number of ways that possible neighbours could have formed on the previous row. In the case of a width of 12, the result is 1 1 1 1 again. At the end, just sum up the last row.
Complexity:
Finding the row types corresponds to enumerating the leaves of a tree; there are about (/ width 3) levels in this tree, so this takes a time of O(2w/3) = O(2w).
Checking whether two row types fit takes time proportional to their length, O(w/3). Building the cross table is proportional to the square of the number of row types. This makes step 2 O(w/3·22w/3) = O(2w).
The dynamic programming takes height times the number of row types times the average number of neighbours (which I estimate to be logarithmic to the number of row types), O(h·2w/3·w/3) = O(2w).
As you see, this is all dominated by the number of row types, which grow exponentially with the width. Fortunately, the constant factors are rather low, so that 48×10 can be solved in a few seconds.
This looks like the type of problem you could solve recursively. Here's a brief outline of an algorithm you could use, with a recursive method that accepts the previous layer and the number of remaining layers as arguments:
Start with the initial number of layers (e.g. 27x5 starts with remainingLayers = 5) and an empty previous layer
Test all possible layouts of the current layer
Try adding a 3x1 in the next available slot in the layer we are building. Check that (a) it doesn't go past the target width (e.g. doesn't go past 27 width in a 27x5) and (b) it doesn't violate the spacing condition given the previous layer
Keep trying to add 3x1s to the current layer until we have built a valid layer that is exactly (e.g.) 27 units wide
If we cannot use a 3x1 in the current slot, remove it and replace with a 4.5x1
Once we have a valid layer, decrement remainingLayers and pass it back into our recursive algorithm along with the layer we have just constructed
Once we reach remainingLayers = 0, we have constructed a valid panel, so increment our counter
The idea is that we build all possible combinations of valid layers. Once we have (in the 27x5 example) 5 valid layers on top of each other, we have constructed a complete valid panel. So the algorithm should find (and thus count) every possible valid panel exactly once.
This is a '2d bin packing' problem. Someone with decent mathematical knowledge will be able to help or you could try a book on computational algorithms. It is known as a "combinatorial NP-hard problem". I don't know what that means but the "hard" part grabs my attention :)
I have had a look at steel cutting prgrams and they mostly use a best guess. In this case though 2 x 4.5" stacked vertically can accommodate 3 x 3" inch stacked horizontally. You could possibly get away with no waste. Gets rather tricky when you have to figure out the best solution --- the one with minimal waste.
Here's a solution in Java, some of the array length checking etc is a little messy but I'm sure you can refine it pretty easily.
In any case, I hope this helps demonstrate how the algorithm works :-)
import java.util.Arrays;
public class Puzzle
{
// Initial solve call
public static int solve(int width, int height)
{
// Double the widths so we can use integers (6x1 and 9x1)
int[] prev = {-1}; // Make sure we don't get any collisions on the first layer
return solve(prev, new int[0], width * 2, height);
}
// Build the current layer recursively given the previous layer and the current layer
private static int solve(int[] prev, int[] current, int width, int remaining)
{
// Check whether we have a valid frame
if(remaining == 0)
return 1;
if(current.length > 0)
{
// Check for overflows
if(current[current.length - 1] > width)
return 0;
// Check for aligned gaps
for(int i = 0; i < prev.length; i++)
if(prev[i] < width)
if(current[current.length - 1] == prev[i])
return 0;
// If we have a complete valid layer
if(current[current.length - 1] == width)
return solve(current, new int[0], width, remaining - 1);
}
// Try adding a 6x1
int total = 0;
int[] newCurrent = Arrays.copyOf(current, current.length + 1);
if(current.length > 0)
newCurrent[newCurrent.length - 1] = current[current.length - 1] + 6;
else
newCurrent[0] = 6;
total += solve(prev, newCurrent, width, remaining);
// Try adding a 9x1
if(current.length > 0)
newCurrent[newCurrent.length - 1] = current[current.length - 1] + 9;
else
newCurrent[0] = 9;
total += solve(prev, newCurrent, width, remaining);
return total;
}
// Main method
public static void main(String[] args)
{
// e.g. 27x5, outputs 7958
System.out.println(Puzzle.solve(27, 5));
}
}