Backtracking algorithm to maximize number of boxes in two rooms - java

We have two rooms of certain sizes(lets call it volume). We have a number of boxes that we have to fit in the two rooms. The boxes have certain sizes, and we cannot stack any boxes on top of each other. Our goal is to maximize the number of boxes in the two rooms using backtracking algorithm. Any suggestions please?

I guess my suggestion would be to think of this as a searching problem in a tree or graph structure. What you need to do is continue to try different paths and save the "best solution". However, this could end up trying all of the possibilies and be O(n!). Therefore, I advise you use some sort of pruning or logic so that this isn't the case. i.e. Alpha-Beta or don't persue paths once they exceed some specifications.

Related

Calculating winning odds - Poker bot

I am trying to build a poker bot in java. I have written the hand evaluation class and I am about to start feeding a neural network but I face a problem. I need the winning odds of every hand for every step: preflop, flop, turn, river.
My problem is that, there are 52 cards and the combinations of 5 cards are 2,598,960. So I need to store 2,598,960 odds for each possible hand. The number is huge and these are only the odds I need for the river.
So I have two options:
Find the odds for every possible hand and every possible deck and every time I start my application load them and kill my memory.
Calculate the odds on the fly and lack processing power.
Is there a 3rd better option to deal with this problem?
3rd option is use the disk... but my first choice would be to calculate odds as you need them.
Why do you need to calculate all combinations of 5 cards, a lot of these hands are worth the same, as there are 4 suits there is repetition between hands.
Personally I would rank your hand based on how many hands beat your hand and how many hands your hand beats. From this you can compute your probability of winning the table by multiplying by number of active hands.
What about ignoring the colors? From 52 possible values, you drop to 13. You only have 6175 options remaining. Of course, colors are important for a flush - but here, it is pretty much binary - are all the colors the same or not? So we are at 12350 (including some impossible combinations, in fact it is 7462 as in the others, a number is contained more than once, so the color must differ).
If the order is important (e.g. starting hand, flip, flop, river or how is it called), it will be a lot more, but it is still less than your two millions. Try simplifying your problems and you'll realize they can be solved.

Creating simple city streets

I am trying to create an algorithm for creating a simple 2D city road system. Its not even going to be procedural, just confined to a small grid.
By simple, I mean something like this:
I have thought to just shoot random length lines from the edges but that doesn't give me the connected-ness look that I want.
I also tried randomly placing nodes and connecting them with L shaped lines but that didn't produce good results either.
Any links to resources, theory, or sample code would be highly appreciated!
P.S It can be in any language. I just need to know the concept behind this.
When generating terrain, e.g. mountain ranges, fractal structures are often used, so perhaps a similar idea could be used here. Do a Google search for "fractal terrain generation" to read more. For the case of generating a street layout, you could try the following algorithm (this is just off the top of my head, so no guarantees that this will actually look nice):
Start with a rectangular area.
Put a small, random number of streets spanning from one edge to another at random locations. Randomness ensures variation in the layout. An example of this single iteration could look like the example you give in the question but simpler, I'd guess 1-4 lines would be reasonable.
The streets you just created divide your area into rectangular blocks. Apply the same division algorithm recursively to each block, of course choosing different random numbers each time.
After 3 or 4 iterations you should have a reasonably complex street network. You can make streets created in subsequent iterations somewhat narrower so that you have a few main streets in the city, some more major streets and a whole lot of minor streets.
I would create random blocks with different sizes and than add these together with leaving a space between each block which represent the streets.
In detail I would make an 2d array. Put the first random block for example in one corner and set all the fields covered by the block with an id for non-street tile. Surround the whole block with street tile. And than repeat the process with the next block by putting it next to the street tiles from the first block. Do this till all fields in the array are either non street tiles or street tiles.

How to improve the perfomance of my A* path finder?

So basically I coded an A* pathfinder that can find paths through obstacles and move diagnolly. I basically implemented the pseudocode from Link into real code and also used a binary heap method to add and delete items from the openlist.
Using binary heap led to significant performance boost , about 500 times faster than the insert sorting algorithm I used before.
the problem is that it still takes around on average 1.5 million nanoseconds which is around .0015 of a second.
So the question is, my plan is to make a tower defense game where the pathfinding for each mob needs to update everytime I add a tower to the map. If I were to have around a maximum of 50ish mobs on the map, that means it will take around .0015 * 50 = .075 seconds to update all paths for the entire mob. The game basically ticks( all the ingame stuff updates) every 1/60 seconds which is .016 of a second, so the problem is that it takes longer to update the paths than it takes to tick, which will lead to massive lag. So how should I go about this? DO I need to find a better algorithm for sorting the openlist or somehow divide the pathfinding tasks so that each tick only does X number of pathfinding tasks as opposed to all of them.
Rather than searching from each enemy to the checkpoint, search outwards from the checkpoint to every enemy at once. This way, rather than doing 50 searches, you only need to do one.
More specifically, just do a breadth-first search (or djikstra's, if your graph is weighted) from the player outwards, until every enemy has been reached.
You could alter this strategy to work with A* by changing your heuristic EstimatedDistanceToEnd (aka h(x)) to be the minimum estimate to any enemy, but with a lot of enemies this may end up being slower than the simpler option. The heuristic must be consistent for this to work.
Additionally, make sure you are using the correct tie-breaking criteria.
Also, and most importantly, remember that you don't need to run your pathfinder every single frame for most games - often you can get away with only once or twice a second, or even less, depending on the game.
If that is still too slow, you could look into using D* lite to reuse information between subsequent searches. But, I would bet money that running a single breadth-first search will be more than fast enough.
(copied from my answer to a similar question on gamedev)
Have you considered the Floyd-Warshall algorithm?
Essentially, A* is for path-finding from a single source to one or more destinations. However, in tower defense (depending on your rules of course), it is about multiple sources navigating around a map.
So for this, Floyd's algorithm seems more optimal. However, you could have your A* algorithm find paths for unit groups instead of individual units, which should optimize your calculation times.
Presumably, you can back-search from the exit towards all the creeps, so you need to explore your maze only once.

What kind of algorithm is this? Box packing/Knapsack?

I was working on an application last night and came across a particular problem which I'm sure probably has an efficient algorithm to solve it. Could anyone suggest?
Problem:
TL;DR: Maybe a picture will help: http://www.custom-foam-inserts.com/ . I have lots of items which fit in a range of compartments: and I want to minimise the number of cases I need to take.
.
I have a set of N items of expensive electronic equipment which I want to pack into specially designed protective boxes. These boxes each have many compartments which can each fit a single item: some of which are designed specially to fit a particular item (ie, a camera shaped hole) and some of which are generic (a rectangular hole). I know in advance that there are C different sizes of compartment and what sizes these are.
These boxes come in L different layouts, each with at least one compartment. A layout might be ‘two large rectangular compartments and 4 small circular compartments’.
Each compartment size is present on at least one layout, but I have items which don’t suit any compartment size. Each item fits at least one compartment and may fit into multiple different compartments: for example, my DSLR camera might be a tight fit in a ‘medium rectangle’ compartment, a loose fit in a ‘large rectangle’ and a perfect fit in a ‘DSLR camera compartment’, but won’t fit in a ‘small circle’. To this end I’ve made a list of which compartments are suitable for each item.
The items are moderately heterogeneous – for example there may be 50 items of one size and 20 items of another size.
Each box has two costs Volume and Dollars (however D ~proportional to V). I need to minimise one or both of these costs whilst fitting ALL of my items into the boxes. Due to the layouts of the boxes, the optimal solution may contain unused compartments. If two solutions have equal volume, select the one with the most unused compartments. Because each compartment is present on at least one layout and each item fits in at least one compartment, there is always a solution which fits all items.
Number of items: <=2000, average case 150.
Number of compartments: <= 1000.
Number of layouts: <= 1000.
Any ideas on this one? I've looked a bit at Knapsack and Bin Packing algorithms and I'm not sure they're the way to go. Help much appreciated.
From the problem description this does indeed seem to be knapsack problem since you have to maximise your space available while keeping in mind the weight of your options.
Depending on what you are after, you could also consider using a Genetic Algorithm. Since this problem is NP Complete the running time will eventually explode should you need to add more items, so I would go with this primarily if I need the best solution available irrelevant of the time it takes.
On the other hand, the Genetic Algorithm should be able to provide with some solution in a relatively small period of time, however, the solution it provides might not be as good as the one provided by the Knapsack algorithm, so I would choose a GA if I have restrictions on the time I need to provide some solution and I do not care if it is the not absolute best.

Find location using only distance and bearing?

Triangulation works by checking your angle to three KNOWN targets.
"I know the that's the Lighthouse of Alexandria, it's located here (X,Y) on a map, and it's to my right at 90 degrees." Repeat 2 more times for different targets and angles.
Trilateration works by checking your distance from three KNOWN targets.
"I know the that's the Lighthouse of Alexandria, it's located here (X,Y) on a map, and I'm 100 meters away from that." Repeat 2 more times for different targets and ranges.
But both of those methods rely on knowing WHAT you're looking at.
Say you're in a forest and you can't differentiate between trees, but you know where key trees are. These trees have been hand picked as "landmarks."
You have a robot moving through that forest slowly.
Do you know of any ways to determine location based solely off of angle and range, exploiting geometry between landmarks? Note, you will see other trees as well, so you won't know which trees are key trees. Ignore the fact that a target may be occluded. Our pre-algorithm takes care of that.
1) If this exists, what's it called? I can't find anything.
2) What do you think the odds are of having two identical location 'hits?' I imagine it's fairly rare.
3) If there are two identical location 'hits,' how can I determine my exact location after I move the robot next. (I assume the chances of having 2 occurrences of EXACT angles in a row, after I reposition the robot, would be statistically impossible, barring a forest growing in rows like corn). Would I just calculate the position again and hope for the best? Or would I somehow incorporate my previous position estimate into my next guess?
If this exists, I'd like to read about it, and if not, develop it as a side project. I just don't have time to reinvent the wheel right now, nor have the time to implement this from scratch. So if it doesn't exist, I'll have to figure out another way to localize the robot since that's not the aim of this research, if it does, lets hope it's semi-easy.
Great question.
The name of the problem you're investigating is localization, and it, together with mapping, are two of the most important and challenging problems in robotics at the moment. Put simply, localization is the problem of "given some sensor observations how do I know where I am?"
Landmark identification is one of the hidden 'tricks' that underpin so much of the practice of robotics. If it isn't possible to uniquely identify a landmark, you can end up with a high proportion of misinformation, particularly given that real sensors are stochastic (ie/ there will be some uncertainty associate with the result). Your choice of an appropriate localisation method, will almost certainly depend on how well you can uniquely identify a landmark, or associate patterns of landmarks with a map.
The simplest method of self-localization in many cases is Monte Carlo localization. One common way to implement this is by using particle filters. The advantage of this is that they cope well when you don't have great models of motion, sensor capability and need something robust that can deal with unexpected effects (like moving obstacles or landmark obscuration). A particle represents one possible state of the vehicle. Initially particles are uniformly distributed, as the vehicle moves and add more sensor observations are incorporated. Particle states are updated to move away from unlikely states - in the example given, particles would move away from areas where the range / bearings don't match what should be visible from the current position estimate. Given sufficient time and observations particles tend to clump together into areas where there is a high probability of the vehicle being located. Look up the work of Sebastian Thrun, particularly the book "probabilistic robotics".
What you're looking for is Monte Carlo localization (also known as a particle filter). Here's a good resource on the subject.
Or nearly anything from the probabilistic robotics crowd, Dellaert, Thrun, Burgard or Fox. If you're feeling ambitious, you could try to go for a full SLAM solution - a bunch of libraries are posted here.
Or if you're really really ambitious, you could implement from first principles using Factor Graphs.
I assume you want to start by turning on the robot inside the forest. I further assume that the robot can calculate the position of every tree using angle and distance.
Then you can identify the landmarks by iterating through the trees and calculating the distance to all its neighbours. In Matlab you can use pdist to get a list of all (unique) pairwise distances.
Then you can iterate through the trees to identify landmarks. For every tree, compare the distances to all its neighbours to the known distances between landmarks. Whenever you find a candidate landmark, you check its possible landmark neighbours for the correct distance signature. Since you say that you always should be able to see five landmarks at any given time, you will be trying to match 20 distances, so I'd say that the chance of false positives is not too high. If the candidate landmark and its candidate fellow landmarks do not match the complete relative distance pattern, you go check the next tree.
Once you have found all the landmarks, you simply triangulate.
Note that depending on how accurately you can measure angles and distances, you need to be able to see more landmark trees at any given time. My guess is that you need to space landmarks with sufficiently density that you can see at least three at a time if you have high measurement accuracy.
I guess you need only distance to two landmarks and the order of seeing them (i.e. from left to right you see point A and B)
(1) "Robotic mapping" and "perceptual aliasing".
(2) Two identical hits are inevitable. Since the robot can only distinguish between a finite number X of distinguishable tree configurations, even if the configurations are completely random, there is almost certainly at least one location that looks "the same" as some other location even if you encounter far fewer than X/2 different trees. Those are called "birthday paradox collisions". You may be lucky that the particular location you are at is in fact actually unique, but I wouldn't bet my robot on it.
So you:
(a) have a map of a large area with
some, but not all trees on it.
(b) a
robot somewhere in the actual forest
that, without looking at the map, has
looked at the nearby trees and
generated an internal map of a all
the trees in a tiny area and its
relative position to them
(c) To the
robot, every tree looks the same as
every other tree.
You want to find: Where is the robot on the large map?
If only each actual tree had a unique name written on it that the robot could read, and then (some of) those trees and their names were on the map, this would be trivial.
One approach is to attach a (not necessarily unique) "signature" to each tree that describes its position relative to nearby trees.
Then, as you travel along, the robot drives up to a tree and finds a "signature" for that tree, and you find all the trees on the map that "match" that signature.
If only one unique tree on the map matches, then the tree the robot is looking might be that tree on the map (yay, you know where the robot is) -- put down a weighty but tentative dot on the map at the robot's relative position to the matching tree -- the tree the robot is next to is certainly not any of the other trees on the map.
If several of the trees on the map match -- they all have the same non-unique signature -- then you could put some less-weighty tentative dots on the map at the robots position relative to each one of them.
Alas, even if find one or more matches, it is still possible that the tree the robot is looking at is not on the map at all, and the signature of that tree is coincidentally the same as one or more trees on the map, and so the robot could be anywhere on the map.
If none of the trees on the map matches, then the tree the robot is looking at is definitely not on the map. (Perhaps later on, once the robot knows exactly where it is, it should start adding these trees to the map?)
As you drive down the path, you push the dots in your estimated direction and speed of travel.
Then as you inspect other trees, possibly after driving down the path a little further, you eventually have lots of dots on the map, and hopefully one heavy, highly overlapping cluster at the actual position, and hopefully each other dot is an easily-ignored isolated coincidences.
The simplest signature is a list of distances from a particular tree to nearby trees.
A particular tree on the map is "matched" to a particular tree in the forest when, for each and every nearby tree on the map, there is a corresponding nearby tree in the forest at "the same" distance, as far as you can tell with your known distance and angular errors.
(By "nearby", I mean "close enough that the robot should be able to definitely confirm that the tree is actually there", although it's probably simpler to approximate this with something like "My robot can see all trees out to a range of R, so I'm only going to bother even trying to match trees that are within a circle of R*1/3 from my robot, and my list of distances only include trees that are within a circle of R*2/3 from the particular tree I'm trying to match").
If you know your north-south orientation even very roughly, you can create signatures that are "more unique", i.e., have fewer spurious matches on the map and (hopefully) in the real forest.
A "match" for the tree the robot is next to occurs when, for each nearby tree on the map, there is a corresponding tree in the forest at "the same" distance and direction, as far as you can tell with your known distance and angular errors.
Say you see that tree "Fred" on the map has another tree 10 meters in the N to W quadrant from it, but the robot is next to a tree that definitely doesn't have any trees at that distance in the N to W quadrant, but it has a tree 10 meters away to the South.
In that case, then (using a more complex signature) you can definitely tell the robot is not next to Fred, even though the simple signature would give a (false) match.
Another approach:
The "digital paper" solves a similar problem ... Can you plant a few trees in a pattern that is specifically designed to be easily recognized?

Categories