I have a circular queue of ordered items. I want to know if an item with the value of "x" is in it.
What is the best way (algorithm) to do this?
If you can access each item by index, you can use a binary search.
If you can only see the first item, you need to pop them from the queue until the search key is lower than the key of the item you just popped. Since the queue is sorted, you can stop as soon as you know that the key can't be in the queue anymore.
[EDIT] Since you can access by index: Warp the circular queue in an object which maps it to an "array" (i.e. with a method get(index) where index runs from 0 to length-1 and which internally does ((index+start)%length).
That way, you can apply the binary search without thinking about the actual data layout.
"Best" is a subjective term and circular queues are rarely large enough to warrant binary searches so I'd opt for simplicity in the absence of information regarding queue size. The easiest way is just to start at the head and check each element until the tail (or you've passed beyond it in the order) to see if it exists.
Let's say your head variable points to the first item that will be removed and the tail points to the next place to put an item. Further assume that you're wasting an item slot to simplify the code (a trick to simplify the code and tell the difference between an empty and full queue). That means and empty queue is indicated by tail == head.
ptr = head
while ptr != tail:
if element[ptr] = searchvalue:
return true
if element[ptr] > searchvalue:
return false
ptr = (ptr + 1) % queuesize;
return false
can we traverse in the opposite direction? ie from tail to head. if so then we can design something that can utilize it. ie decide which way to proceed the search.
Since it is ordered we can guess about its position (just a guess or perhaps utilize statistics if available) and then start the full search only in direction which would get the result in less pulls
The OP I suspect, has a fixed sized circular buffer. Two search conditions occur.
One while the buffer is filling and one when the buffer is filled where wrap around has occurred and there is over writing of previous stores.
The first case is a linear search with the start 'slot' at zero and the end slot is presumably recorded/maintained.
The second case is trickier. The start slot circulates as previous stores are over written. The end slot also circulates, just one position following the start slot.
To do a linear search over these moving indexes a translation is needed to place the start slot at zero and the end slot at the buffer size.
How that algorithm works is yet to be determined.
Related
I am trying to validate my custom MPxEmitterNode attributes.
I have force_min and force_max attributes that are double3 typed in maya parlance, basically two objects containing double[3] data.
I want to ensure the force_min is less than force_max for each of its 3 components. I'd like to do this by just swapping the min and max around if someone enters a value on the attribute in the attribute editor, or calls mels setAttr for those attributes, which then fails the "min < max" check.
I have tried setting up ATTRIBUTE_AFFECTS relationships between force_min, force_max and their individual component x,y,z objects. That seems to cause a cyclic issue leading to Maya crashing. I have also tried editing the custom compute function for the derived MPxEmitterNode, so it sets the force_min and force_max values to swap. The force_* attributes are seemingly never computed in this case.
Any help would be much appreciated.
Generally the 'Maya' way to do this would be to let the output look wrong if the min and max are set incorrectly. You don't know who is going to set those attributes -- it could be as connection or a script, and it could even get reset in between frames of an animation -- and so it's better to let the dag evaluation flow through even if the result is nonsense. It's like setting a radius of zero on a sphere node --it's 'correct' even thought it's wrong.
You can however swap the values inside your compute() method to get the same effect as swapping the values without resetting the plug values themselves. Setting an input plug from inside compute is a bad idea, because it introduces a loop into the flow of the dag evaluation. Dag nodes must be acyclical (that's the "a" in dag: Directed Acyclic Graph)
My goal is to build a 5x5 grid of images. In the following code, row, col and rowcol were created as variables local to the sprite, and newcol, newrow and cats are global. (By the way, is it possible to tell which variables are local and which are global? It's easy to forget or make mistakes.)
The result is a 5x1 grid only, as seen here.
I am unclear as to the order of execution of these statements. Does when I start as a clone get called before or after add_cat gets called the second time? My tentative conclusion is that it gets called afterwards, yet the clone's global variables seem to contain their values from beforehand instead.
When I attempted to debug it with ask and say and wait commands, the results varied wildly. Adding such pauses in some places fixed the problem completely, resulting in a 5x5 grid. In other places, they caused a 1x5 grid.
The main question is: How to fix this so that it produces a 5x5 grid?
Explanation
Unfortunately, the execution order in Scratch is a little bizarre. Whenever you edit a script (by adding or removing blocks, editing inputs, or dragging the entire script to a new location in the editor), it gets placed at the bottom of the list (so it runs last).
A good way to test this out is to create a blank project with the following scripts:
When you click the green flag, the sprite will either say "script one" or "script two", depending on which runs first. Try clicking and dragging one of the when green flag clicked blocks. The next time you click the green flag, the sprite will say whichever message corresponds to the script you just dragged.
This crazy order can make execution incredibly unpredictable, especially when using clones.
The solution
The only real solution is to write code that has a definite execution order built-in (rather than relying on the whims of the editor). For simpler scripts, this generally means utilizing the broadcast and wait block to run particular events in the necessary order.
For your specific project, I see two main solutions:
Procedural Solution
This is the most straightforward script, and it's probably what I would choose to go with:
(row and col are both sprite-only variables)
Because clones inherit all sprite-only variable values when they are created, each clone will be guaranteed to have the correct row and col when it is created.
Recursive Solution
This solution is a bit harder to understand than the first, so I would probably avoid it unless you're just looking for the novelty:
I'm developing a simple game in swift, but using GamePlayer (on Cydia, a cheat-enginelike), I am able to locate, track and modify my score.
I was wondering how can I prevent this kind of cheats... I tried to create a new instance of the element whenever it changes, example:
score = Int(score + 1)
I also tried to reset the var to nil and re-assign it:
let tmp = score + 1
score = nil
score = tmp
But it is not working...
My first question is: Is it possible to change a variable's address in swift ? And will it prevent address tracking?
My second question is: Another thing that can work, encoding my score, but is it worth the work ?
You can put your score variable in a struct and use copy-on-write. Then, when you change a value, you get a fresh copy of the score. The possibilities and how copy-on-write works, is described here with examples: copy-on-write
Compared to the solution, were you actually encrypt the number it has advantages and disadvantages. Just some of them from the top of my head (I'm curious what your points are)
encryption needs more cpu power and therefore more battery. Whereas the copy-on-write is implemented deep on iOS level, where we can assume, that it is very well optimised.
The copy-on-write solution is less secure, as one might find the right address just at the beginning and can track it (now, that I think about it, not really...)
The copy-on-write adds more complexity to your source code as you need to trigger it on every change.
I'm implementing an FRP framework in Scala and I seem to have run into a problem. Motivated by some thinking, this question I decided to restrict the public interface of my framework so Behaviours could only be evaluated in the 'present' i.e.:
behaviour.at(now)
This also falls in line with Conal's assumption in the Fran paper that Behaviours are only ever evaluated/sampled at increasing times. It does restrict transformations on Behaviours but otherwise we find ourselves in huge problems with Behaviours that represent some input:
val slider = Stepper(0, sliderChangeEvent)
With this Behaviour, evaluating future values would be incorrect and evaluating past values would require an unbounded amount of memory (all occurrences used in the 'slider' event would have to be stored).
I am having trouble with the specification for the 'snapshot' operation on Behaviours given this restriction. My problem is best explained with an example (using the slider mentioned above):
val event = mouseB // an event that occurs when the mouse is pressed
val sampler = slider.snapshot(event)
val stepper = Stepper(0, sampler)
My problem here is that if the 'mouseB' Event has occurred when this code is executed then the current value of 'stepper' will be the last 'sample' of 'slider' (the value at the time the last occurrence occurred). If the time of the last occurrence is in the past then we will consequently end up evaluating 'slider' using a past time which breaks the rule set above (and your original assumption). I can see a couple of ways to solve this:
We 'record' the past (keep hold of all past occurrences in an Event) allowing evaluation of Behaviours with past times (using an unbounded amount of memory)
We modify 'snapshot' to take a time argument ("sample after this time") and enforce that that time >= now
In a more wacky move, we could restrict creation of FRP objects to the initial setup of a program somehow and only start processing events/input after this setup is complete
I could also simply not implement 'sample' or remove 'stepper'/'switcher' (but I don't really want to do either of these things). Has anyone any thoughts on this? Have I misunderstood anything here?
Oh I see what you mean now.
Your "you can only sample at 'now'" restriction isn't tight enough, I think. It needs to be a bit stronger to avoid looking into the past. Since you are using an environmental conception of now, I would define the behavior construction functions in terms of it (so long as now cannot advance by the mere execution of definitions, which, per my last answer, would get messy). For example:
Stepper(i,e) is a behavior with the value i in the interval [now,e1] (where e1 is the
time of first occurrence of e after now), and the value of the most recent occurrence of e afterward.
With this semantics, your prediction about the value of stepper that got you into this conundrum is dismantled, and the stepper will now have the value 0. I don't know whether this semantics is desirable to you, but it seems natural enough to me.
From what I can tell, you are worried about a race condition: what happens if an event occurs while the code is executing.
Purely functional code does not like to have to know that it gets executed. Functional techniques are at their finest in the pure setting, such that it does not matter in what order code is executed. A way out of this dilemma is to pretend that every change happened in one sensitive (internal, probably) piece of imperative code; pretend that any functional declarations in the FRP framework happen in 0 time so it is impossible for something to change during their declaration.
Nobody should ever sleep, or really do anything time sensitive, in a section of code that is declaring behaviors and things. Essentially, code that works with FRP objects ought to be pure, then you don't have any problems.
This does not necessarily preclude running it on multiple threads, but to support that you might need to reorganize your internal representations. Welcome to the world of FRP library implementation -- I suspect your internal representation will fluctuate many times during this process. :-)
I'm confused about your confusion. The way I see is that Stepper will "set" the behavior to a new value whenever the event occurs. So, what happens is the following:
The instant in which the event mouseB occurs, the value of the slider behavior will be read (snapshot). This value will be "set" into the behavior stepper.
So, it is true that the Stepper will "remember" values from the past; the point is that it only remembers the latest value from the past, not everything.
Semantically, it is best to model Stepper as a function like luqui proposes.
I am looking into how to write a paint program that supports undo and seeing that, most likely, a command pattern is what I want. Something still escapes me, though, and I'm hoping someone can provide a simple answer or confirmation.
Basically, if I am to embody the ability to undo a command, for instance stamping a solid circle on the screen, does this mean I need to essentially copy the frame buffer that the circle covers into memory, into this command object? I don't see any other way of being able to undo what might be, for instance, stamping over a bunch of random pixel colors.
I've heard that one approach is just to keep track of the forward actions and when an undo is performed, you simply start from step 1 and draw forwards to the step before the undo, but this seems unfeasible if you are to support a large undo stack.
Perhaps the solution is something in between where you keep a bitmap of every 15-20 actions and start from the last 'save' forwards.
Can someone provide any insight on what is the typical accepted approach in this case, either saving buffer rectangles in the commands, redo-ing every action forwards, or something I've altogether missed?
Update: Plenty of good responses. Thanks, everyone. I'm thinking from what I'm reading that I will approach this by saving out the buffer every N actions and when the user issues an undo command redo all commands from the most recent saved buffer. I can tweak N to as high a value as possible that doesn't noticeably bog down the user experience of needing responsive undo (in order to minimize memory usage), but I suspect without really knowing for sure at this point, that I should be able to get away with performing quite a few actions in one frame such that this isn't too bad. Hopefully this approach will let me quickly determine whether to turn the other direction and instead go with saving bitmap rects for the previous states for actions that require it.
First, beware overdesign: if your app isn't complex and your images small, you may find 'just store everything' to be quick, cheap and feasible. But assuming that's not so:
You are correct that it is not feasible to redraw the entire canvas from step 1 forward for each undo; unless your paint program is very simple some operations simply take too long. Also, an infinite undo buffer is probably not called for (and could be very space-consuming to store).
If your art program is complex, I'd actually start with a hybrid approach, to deal with the variety of operations. Save frame buffer every so often (the every 15-20 commands you suggest seems OK; I might start with 10 and adjust once I had it working) and go forward from last save. But don't make the 'every 15 operations' rigid, because it is likely that a few extra rules of thumb would make it seem much more fluid to the user.
For example, some time-consuming or tricky-to-reverse operations could always create a new save point:
- Any canvas resize (crop etc.)
- Any save. ("I just saved" is a very likely place for the user to undo back to.)
- Any operation which is extremely time-consuming should create a new save point after, not before, the operation; i.e. it should flag the next operation to save the buffer to undo. (Why? If the op takes 30 seconds, you don't want every undo in the stack afterwards to take an extra 30+ seconds.)
- Conversely, any operation which has an easily performed mathematical negative, or is self-inverting (like photonegative) need never bother to save frame buffer, and shouldn't count towards the next save.
All of this leaves out the question of layers; if your program has them it's obviously sufficient to save only those layers that change.
Definitely my highest-priority suggestion though: regardless of what method you use, you should always save frame buffer for the most recent operation performed. "Whoops, didn't mean that" is the most likely reason for undo, so you always want undo-one-step to be responsive. You can discard this buffer after the next command execution if it's not one you're keeping.
You'll also need to consider what constitutes one atomic undo operation. (For example, is a set of strokes with a single brush tool one operation or many? Both have advantages and drawbacks.)
Perhaps the solution is something in between where you keep a bitmap of every 15-20 actions and start from the last 'save' forwards.
I would go with something like this one. You have to bound your command stack at some point anyway, so you'll need a starting point if the user empties it.
You could get clever and save the buffer when you reach the bound and use that as your save point, since you have to drop a command from the stack anyway. Essentially, your save point buffer is the representation of the dropped actions, so as you're dropping actions from your undo stack, you just write them onto that buffer.
I've heard that one approach is just to keep track of the forward actions and when an undo is performed, you simply start from step 1 and draw forwards to the step before the undo
This isn't a very good idea. Users typically undo only a few recent actions and they expect it to be fast, so it's better to be able to revert immediately than redoing everything from the start.
Can someone provide any insight on what is the typical accepted approach in this case, either saving buffer rectangles in the commands, redo-ing every action forwards, or something I've altogether missed?
You don't have to store all commands in the same way. Depending on the type of operation, you can use one or more techniques, for example:
Drawing/painting operations generally can't be reverted directly, so you have no choice but to save the original image contents. You can however save space by storing only parts of the image that have changed instead of the entire image.
Some operations like inverting colours are inherently invertible, so in such cases, you only need to store the type of operation on the undo stack, and you can replay the operation in either direction.
If you probably won't draw gigantic bitmaps, your approach seems totally ok.
To simplify even more, write whole pictures to tmp directory onto disk, and see what it will be like for the users.
Don't overdesign at start-there are other issues that need to be adressed, no doubt.
From my understanding, the command pattern for implementing undo/redo sorts of systems just record the actions in a stack, not the actual results from those actions (since those will be recreated/removed in sequence). I think you alluded to this, but said you considered it unfeasible for a large undo stack. Can you be more specific? I believe it is possible.