I needed some help with a problem I'd been assigned in class. It's our introduction to for loops. Here is the problem:
Consider the following riddle.
This is all I have so far:
function pile = IslandBananas(numpeople, numbears)
for pilesize=1:10000000
end
I would really appreciate your input. Thank you!
I will help you, but you need to try harder than that. And also, you only need one for loop. First, think about how you would construct this algorithm. Well you know you have to use a for loop so that is a start. So let's think about what is going on in the problem.
1) You have a pile.
2) First night someone takes the pile and divides it into 3 and finds that one is left over, this means mod(pile,3) = 1.
3) But he discards the extra banana. This means (pile-1).
4) He takes a third of it, leaving two-thirds left. This means (2/3)*(pile-1).
5) In the morning they take the pile and divide it into 3 and find again that one is left over, so this means mod((2/3)*(pile-1),3) = 1.
6) But they discard the extra banana. This means (2/3)*(pile-1)-1.
7) Finally, they have to each have at least one banana if it is to be the smallest pile possible. Thus, the smallest pile must be such that (1/3)*((2/3)*(pile-1)-1) = 1.
I have essentially given you the answer, the rest you can write with the formula (1/3)*((2/3)*(pile-1)-1) and a simple if statement to test for the smallest possible integer which is 1. This can be done in four lines inside of your for loop.
Now, expanding this to any number of people and any number of bears requires two simple substitutions in that formula! If your teacher demands it, this can easily be split into two nested for loops.
Related
I want to solve a problem similar to N-Queens one, but:
all chess pieces are available
user inputs how many pieces of what kind are to be placed (e.g. 3 rooks, 4 knights, 1 bishop)
I'm lying on the floor for some time now, but can't come up with how to adjust the backtracking algorithm for this purpose. I will be very grateful for any kind of help.
In principle, the same approach as in the classical N-Queen problem should work:
Find an empty, non-attacked square where you can place your next piece
Search the new position recursively (or if you already placed all your pieces, output the solution)
Take back the last placed piece and repeat (goto step 1) until you have tried all squares where you can place the next piece
The only difference to the classical N-Queens problem is that the different pieces have different attack patterns. And some common optimizations might no longer work. For instance, if you have pawns, it breaks symmetry as they only attack the squares in front of them. (Though you still have one symmetry axis even with pawns.)
I would expect the backtracking algorithm to be more efficient if you start with placing the pieces first that cover the most squares: first queens, then rooks and bishops, then knights and kings, and finally pawns.
I am in the process of coding a simple Genetic Algorithm (GA). There are probably countless areas where I have unnecessarily used a for loop. I would like some tips on how to be more MATLAB efficient as well as an answer to my question. As far as I can tell I have succeeded but I am not sure. The area which this code defines is single-point crossover
Here is what I have tried...
crossPoints=randi([1 24],popSize/2,1);
for popNo=2:2:popSize
isolate=chromoParent(popNo-1:popNo,crossPoints(popNo/2,1)+1:end);
isolate([1 2],:)=isolate([2 1],:);
chromoParent(popNo-1:popNo,crossPoints(popNo/2,1)+1:end)=isolate;
end
chromoChild=chromoParent;
where, 'crossPoints' is the point at which single point crossover
between two binary encoded chromosomes is required.
'popSize' is the size of the population, required by my code to
be an even number
'isolate' defines the sections of 2 rows which are required to be swapped
with each other
'chromoParent' is the initial population which is required to be
changed by single-point crossover
'chromoChild' is the resulting population
Both 'chromoParent' and 'chromoChild' are represented by an array of
size, popSize x 25 binary characters
Can you spot an error in the way I am thinking about this problem? What's the most efficient way (in computational time) to achieve the same thing? It would help if you could be as broad as possible so that I could begin applying the principles I learn here to the rest of my code.
Thank you.
Your code looks fine. If you want, you can reduce the instructions in the loop to a single line by some very simple indexing:
chromoParent( popNo-1:popNo, crossPoints(popNo/2,1)+1:end) = ...
chromoParent(popNo:-1:popNo-1,crossPoints(popNo/2,1)+1:end);
This may be marginally faster, but as with any optimization, you should profile it first (My guess is that these line contribute very little to the overall CPU time).
So I have an array of numbers that look something like
1,708,234
2,802,532
11,083,432
5,098,123
5,777,111
I want to find out when two numbers are within a certain distance from each other (say 1,500,000) so I can group them into the same location and have just one UI element represent both for the level of zoom I am looking at. How would one go about doing this smartly or efficiently. I'm thinking I would just start with the first entry, loop through all the elements, and if one was close to another, flag those two and put it in a dictionary of some sort. That would be my brute force method, but I'm thinking there has to be a better way.
I'm coding in obj-c btw if that makes or breaks any design decisions.
How many numbers are we dealing with here? If it's small enough:
Sort the numbers (generally n-log-n)
Run through each number, n, and compare its bigger neighbor, n+1, to see if it's within your range.
Repeat for n+2, n+3, until the number is no longer within your range.
Your brute force method there is O((n/2)^2). This method will bring it to O(n + n log(n)), or O(n log n) on the average case.
I'm currently writing an optimization algorithm in MATLAB, at which I completely suck, therefore I could really use your help. I'm really struggling to find a good way of representing a graph (or well more like a tree with several roots) which would look more or less like this:
alt text http://img100.imageshack.us/img100/3232/graphe.png
Basically 11/12/13 are our roots (stage 0), 2x is stage1, 3x stage2 and 4x stage3. As you can see nodes from stageX are only connected to several nodes from stage(X+1) (so they don't have to be connected to all of them).
Important: each node has to hold several values (at least 3-4), one will be it's number and at least two other variables (which will be used to optimize the decisions).
I do have a simple representation using matrices but it's really hard to maintain, so I was wondering is there a good way to do it?
Second question: when I'm done with that representation I need to calculate how good each route (from roots to the end) is (like let's say I need to compare is 11-21-31-41 the best or is 11-21-31-42 better) to do that I will be using the variables that each node holds. But the values will have to be calculated recursively, let's say we start at 11 but to calcultate how good 11-21-31-41 is we first need to go to 41, do some calculations, go to 31, do some calculations, go to 21 do some calculations and then we can calculate 11 using all the previous calculations. Same with 11-21-31-42 (we start with 42 then 31->21->11). I need to check all the possible routes that way. And here's the question, how to do it? Maybe a BFS/DFS? But I'm not quite sure how to store all the results.
Those are some lengthy questions, but I hope I'm not asking you for doing my homework (as I got all the algorithms, it's just that I'm not really good at matlab and my teacher wouldn't let me to do it in java).
Granted, it may not be the most efficient solution, but if you have access to Matlab 2008+, you can define a node class to represent your graph.
The Matlab documentation has a nice example on linked lists, which you can use as a template.
Basically, a node would have a property 'linksTo', which points to the index of the node it links to, and a method to calculate the cost of each of the links (possibly with some additional property that describe each link). Then, all you need is a function that moves down each link, and brings the cost(s) with it when it moves back up.
I'm at the debugging/optimization phase with an iPhone app. I have one bottleneck left - the only place where the program has a noticeable lag, and it's in the following loop: (By the way, I've renamed the vars with letters and types. (The real names are much more human-readable in the actual app, but make little sense out of context, so I hope this is clear enough.) Here's the loop:
for(i=0;i<xLong; i+=yFloat*zShort){
aFloat=0.0;
for(int j=i;j<i+yFloat*zShort;j++){
aFloat=hArray[j]/kFloat;
}
bNSNumber = [NSNumber numberWithFloat:aFloat];
[cNSMutableArray addObject:bNSNumber];
}
All objection creation and clean-up is outside of this loop.
(It should be pretty straight forward what's happening here, but basically I have a very large array (in the millions) and I'm going through that array at chunks of yFloat*zShort length, adding all of the elements in that chunk, and inserting that final sum in another array. So if hArray is a million elements long, and my chunk length is 200, I'll sum the first 200 elements, insert that total in cNSMutableArray, and move on to the next 200 elements in hArray. In the end, cNSMutableArray will be 5000 elements long.)
When the outer loop is around 25k and the inner loop is around 200, this code takes about 4 seconds to run. I would sure like to get that down as much as possible, as in the real world, the outer loop might be quite a bit larger.
Any ideas how to quicken this up?
Thanks for any ideas you have!
Have you tried to make a C style float array instead of using a NSMutableArray? the overhead of creating that many wrappers (NSNumber) can add up.
First off, from your description it sounds like the inner loop should read:
for(int j=i;j<i+yFloat*zShort;j++){
aFloat+=hArray[j]/kFloat;
}
Anyway, since kFloat is not changing, you can move that out of the loop and do the division once:
for(int j=i;j<i+yFloat*zShort;j++){
aFloat+=hArray[j];
}
aFloat/=kFloat;
That said, this can affect the accuracy of the final value. Without knowing exactly what you are doing, I don't know if that will matter.
I see that you already got a nice speedup, but here's my two cents: Floating-point division is notoriously expensive; you could precompute
float invKFloat = 1.0f / kFloat;
and then mulitply by this instead of dividing by kFloat. This means you only have to do the division once, instead of every time in the outer loop.
This seems like the kind of calculation that should be spun off in a background thread.
You have several options- NSOperation is a viable alternative, but depending on your data structures it might be easier to use detachNewThreadSelector:toTarget:withObject:
You really want to avoid creating objects inside a tight loop. Every time you do that, you're allocating a new object on the heap, which involves a hash insert.