Search Results

Search found 17940 results on 718 pages for 'algorithm design'.

Page 22/718 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Lawler's Algorithm Implementation Assistance

    - by Richard Knop
    Here is my implemenation of Lawler's algorithm in PHP (I know... but I'm used to it): <?php $jobs = array(1, 2, 3, 4, 5, 6); $jobsSubset = array(2, 5, 6); $n = count($jobs); $processingTimes = array(2, 3, 4, 3, 2, 1); $dueDates = array(3, 15, 9, 7, 11, 20); $optimalSchedule = array(); foreach ($jobs as $j) { $optimalSchedule[] = 0; } $dicreasedCardinality = array(); for ($i = $n; $i >= 1; $i--) { $x = 0; $max = 0; // loop through all jobs for ($j = 0; $j < $i; $j++) { // ignore if $j already is in the $dicreasedCardinality array if (false === in_array($j, $dicreasedCardinality)) { // if the job has no succesor in $jobsSubset if (false === isset($jobs[$j+1]) || false === in_array($jobs[$j+1], $jobsSubset)) { // here I find an array index of a job with the maximum due date // amongst jobs with no sucessor in $jobsSubset if ($x < $dueDates[$j]) { $x = $dueDates[$j]; $max = $j; } } } } // move the job at the end of $optimalSchedule $optimalSchedule[$i-1] = $jobs[$max]; // decrease the cardinality of $jobs $dicreasedCardinality[] = $max; } print_r($optimalSchedule); Now the above returns an optimal schedule like this: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 3 [4] => 2 [5] => 6 ) Which doesn't seem right to me. The problem might be with my implementation of the algorithm because I am not sure I understand it correctly. I used this source to implement it: http://www.google.com/books?id=aSiBs6PDm9AC&pg=PA166&dq=lawler%27s+algorithm+code&lr=&hl=sk&cd=4#v=onepage&q=&f=false The description there is a little confusing. For example, I didn't quite get how is the subset D defined (I guess it is arbitrary). Could anyone help me out with this? I have been trying to find some sources with simpler explanation of the algorithm but all sources I found were even more complicated (with math proofs and such) so I am stuck with the link above. Yes, this is a homework, if it wasn't obvious. I still have few weeks to crack this but I have spent few days already trying to get how exactly this algorithm works with no success so I don't think I will get any brighter during that time.

    Read the article

  • Memento with optional state?

    - by Korey Hinton
    EDIT: As pointed out by Steve Evers and pdr, I am not correctly implementing the Memento pattern, my design is actually State pattern. Menu Program I built a console-based menu program with multiple levels that selects a particular test to run. Each level more precisely describes the operation. At any level you can type back to go back one level (memento). Level 1: Server Type? [1] Server A [2] Server B Level 2: Server environment? [1] test [2] production Level 3: Test type? [1] load [2] unit Level 4: Data Collection? [1] Legal docs [2] Corporate docs Level 4.5 (optional): Load Test Type [2] Multi TIF [2] Single PDF Level 5: Command Type? [1] Move [2] Copy [3] Remove [4] Custom Level 6: Enter a keyword [setup, cleanup, run] Design States PROBLEM: Right now the STATES enum is the determining factor as to what state is BACK and what state is NEXT yet it knows nothing about what the current memento state is. Has anyone experienced a similar issue and found an effective way to handle mementos with optional state? static enum STATES { SERVER, ENVIRONMENT, TEST_TYPE, COLLECTION, COMMAND_TYPE, KEYWORD, FINISHED } Possible Solution (Not-flexible) In reference to my code below, every case statement in the Menu class could check the state of currentMemo and then set the STATE (enum) accordingly to pass to the Builder. However, this doesn't seem flexible very flexible to change and I'm struggling to see an effective way refactor the design. class Menu extends StateConscious { private State state; private Scanner reader; private ServerUtils utility; Menu() { state = new State(); reader = new Scanner(System.in); utility = new ServerUtils(); } // Recurring menu logic public void startPromptingLoop() { List<State> states = new ArrayList<>(); states.add(new State()); boolean redoInput = false; boolean userIsDone = false; while (true) { // get Memento from last loop Memento currentMemento = states.get(states.size() - 1) .saveMemento(); if (currentMemento == null) currentMemento = new Memento.Builder(0).build(); if (!redoInput) System.out.println(currentMemento.prompt); redoInput = false; // prepare Memento for next loop Memento nextMemento = null; STATES state = STATES.values()[states.size() - 1]; // get user input String selection = reader.nextLine(); switch (selection) { case "exit": reader.close(); return; // only escape case "quit": nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); states.clear(); break; case "back": nextMemento = new Memento.Builder(previous(state), currentMemento, selection).build(); if (states.size() <= 1) { states.remove(0); } else { states.remove(states.size() - 1); states.remove(states.size() - 1); } break; case "1": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "2": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "3": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "4": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; default: if (state.equals(STATES.CATEGORY)) { String command = selection; System.out.println("Executing " + command + " command on: " + currentMemento.type + " " + currentMemento.environment); utility.executeCommand(currentMemento.nickname, command); userIsDone = true; states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else if (state.equals(STATES.KEYWORD)) { nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else { redoInput = true; System.out.println("give it another try"); continue; } break; } if (userIsDone) { // start the recurring menu over from the beginning for (int i = 0; i < states.size(); i++) { if (i != 0) { states.remove(i); // remove all except first } } reader = new Scanner(System.in); this.state = new State(); userIsDone = false; } if (!redoInput) { this.state.restoreMemento(nextMemento); states.add(this.state); } } } }

    Read the article

  • Shuffling algorithm with no "self-mapping"?

    - by OregonTrail
    To randomly shuffle an array, with no bias towards any particular permutation, there is the Knuth Fischer-Yeats algorithm. In Python: #!/usr/bin/env python import sys from random import randrange def KFYShuffle(items): i = len(items) - 1 while i > 0: j = randrange(i+1) # 0 <= j <= i items[j], items[i] = items[i], items[j] i = i - 1 return items print KFYShuffle(range(int(sys.argv[1]))) There is also Sattolo's algorithm, which produces random cycles. In Python: #!/usr/bin/env python import sys from random import randrange def SattoloShuffle(items): i = len(items) while i > 1: i = i - 1 j = randrange(i) # 0 <= j <= i-1 items[j], items[i] = items[i], items[j] return items print SattoloShuffle(range(int(sys.argv[1]))) I'm currently writing a simulation with the following specifications for a shuffling algorithm: The algorithm is unbiased. If a true random number generator was used, no permutation would be more likely than any other. No number ends up at its original index. The input to the shuffle will always be A[i] = i for i from 0 to N-1 Permutations are produced that are not cycles, but still meet specification 2. The cycles produced by Sattolo's algorithm meet specification 2, but not specification 1 or 3. I've been working at creating an algorithm that meets these specifications, what I came up with was equivalent to Sattolo's algorithm. Does anyone have an algorithm for this problem?

    Read the article

  • USE case to Class Diagram - How do I?

    - by 01010011
    Hi, I would like your guidance on how to create classes and their relationships (generalization, association, aggregation and composition) accurately from my USE case diagram (please see below). I am trying to create this class diagram so I can use it to create a simple online PHP application that allows the user to register an account, login and logout, and store, search and retrieve data from a MySQL database. Are my classes correct? Or should I create more classes? And if so, what classes are missing? What relationships should I use when connecting the register, login, logout, search_database and add_to_database to the users? I'm new to design patterns and UML class diagrams but from my understanding, the association relationship relates one object with another object; the aggregation relationship is a special kind of association that allows "a part" to belong to more than one "whole" (e.g. a credit card and its PIN - the PIN class can also be used in a debit card class); and a composition relationship is a special form of aggregation that allows each part to belong to only one whole at a time. I feel like I have left out some classes or something because I just can't seem to find the relationships from my understanding of relationships. Any assistance will be really appreciated. Thanks in advance. USE CASE DIAGRAM CLASS DIAGRAM

    Read the article

  • An implementation of Sharir's or Aurenhammer's deterministic algorithm for calculating the intersect

    - by RGrey
    The problem of finding the intersection/union of 'N' discs/circles on a flat plane was first proposed by M. I. Shamos in his 1978 thesis: Shamos, M. I. “Computational Geometry” Ph.D. thesis, Yale Univ., New Haven, CT 1978. Since then, in 1985, Micha Sharir presented an O(n log2n) time and O(n) space deterministic algorithm for the disc intersection/union problem (based on modified Voronoi diagrams): Sharir, M. Intersection and closest-pair problems for a set of planar discs. SIAM .J Comput. 14 (1985), pp. 448-468. In 1988, Franz Aurenhammer presented a more efficient O(n log n) time and O(n) space algorithm for circle intersection/union using power diagrams (generalizations of Voronoi diagrams): Aurenhammer, F. Improved algorithms for discs and balls using power diagrams. Journal of Algorithms 9 (1985), pp. 151-161. Earlier in 1983, Paul G. Spirakis also presented an O(n^2) time deterministic algorithm, and an O(n) probabilistic algorithm: Spirakis, P.G. Very Fast Algorithms for the Area of the Union of Many Circles. Rep. 98, Dept. Comput. Sci., Courant Institute, New York University, 1983. I've been searching for any implementations of the algorithms above, focusing on computational geometry packages, and I haven't found anything yet. As neither appear trivial to put into practice, it would be really neat if someone could point me in the right direction!

    Read the article

  • average case running time of linear search algorithm

    - by Brahadeesh
    Hi all. I am trying to derive the average case running time for deterministic linear search algorithm. The algorithm searches an element x in an unsorted array A in the order A[1], A[2], A[3]...A[n]. It stops when it finds the element x or proceeds until it reaches the end of the array. I searched on wikipedia and the answer given was (n+1)/(k+1) where k is the number of times x is present in the array. I approached in another way and am getting a different answer. Can anyone please give me the correct proof and also let me know whats wrong with my method? E(T)= 1*P(1) + 2*P(2) + 3*P(3) ....+ n*P(n) where P(i) is the probability that the algorithm runs for 'i' time (i.e. compares 'i' elements). P(i)= (n-i)C(k-1) * (n-k)! / n! Here, (n-i)C(k-1) is (n-i) Choose (k-1). As the algorithm has reached the ith step, the rest of k-1 x's must be in the last n-i elements. Hence (n-i)C(k-i). (n-k)! is the total number of ways of arranging the rest non x numbers, and n! is the total number of ways of arranging the n elements in the array. I am not getting (n+1)/(k+1) on simplifying.

    Read the article

  • Adaptive user interface/environment algorithm

    - by WowtaH
    Hi all, I'm working on an information system (in C#) that (while my users use it) gathers statistical data on what pieces of information (tables & records) each user is requesting the most, and what parts of the interface he/she uses most. I'm using this statistical data to make the application adaptive to the user's needs, both in the way the interface presents itself (eg: tab/pane-ordering) as in the way of using the frequently viewed information to (eg:) show higher in search results/suggestion-lists. What i'm looking for is an algorithm/formula to determine the current 'hotness'/relevance of these objects for a specific user. A simple 'hitcounter' for each object won't be sufficient because the user might view some information quite frequently for a period of time, and then moving on to the next, making the old information less relevant. So i think my algorithm also needs some sort of sliding/historical principle to account for the changing popularity of the objects in the application over time. So, the question is: Does anybody have some sort of algorithm that accounts for that 'popularity over time' ? Preferably with some explanation on the parameters :) Thanks! PS I've looked at other posts like http://stackoverflow.com/questions/32397/popularity-algorithm but i could't quite port it to my specific case. Any help is appreciated.

    Read the article

  • Separation of domain and ui layer in a composite

    - by hansmaad
    Hi all, i'm wondering if there is a pattern how to separate the domain logic of a class from the ui responsibilities of the objects in the domain layer. Example: // Domain classes interface MachinePart { CalculateX(in, out) // Where do we put these: // Draw(Screen) ?? // ShowProperties(View) ?? // ... } class Assembly : MachinePart { CalculateX(in, out) subParts } class Pipe : MachinePart { CalculateX(in, out) length, diamater... } There is an application that calculates the value X for machines assembled from many machine parts. The assembly is loaded from a file representation and is designed as a composite. Each concrete part class stores some data to implement the CalculateX(in,out) method to simulate behaviour of the whole assembly. The application runs well but without GUI. To increase the usability a GUi should be developed on top of the existing implementation (changes to the existing code are allowed). The GUI should show a schematic graphical representation of the assembly and provide part specific dialogs to edit several parameters. To achieve these goals the application needs new functionality for each machine part to draw a schematic representation on the screen, show a property dialog and other things not related to the domain of machine simulation. I can think of some different solutions to implement a Draw(Screen) functionality for each part but i am not happy with each of them. First i could add a Draw(Screen) method to the MachinePart interface but this would mix-up domain code with ui code and i had to add a lot of functionality to each machine part class what makes my domain model hard to read and hard to understand. Another "simple" solution is to make all parts visitable and implement ui code in visitors but Visitor does not belong to my favorite patterns. I could derive UI variants from each machine part class to add the UI implementation there but i had to check if each part class is suited for inheritance and had to be careful on changes to the base classes. My currently favorite design is to create a parallel composite hierarchy where each component stores data to define a machine part, has implementation for UI methods and a factory method which creates instances of the corresponding domain classes, so that i can "convert" a UI assembly to a domain assembly. But there are problems to go back from the created domain hierarchy to the UI hierarchy for showing calculation results in the drawing for example (imagine some parts store some values during the calculation i want to show in the schematic representation after the simluation). Maybe there are some proven patterns for such problems?

    Read the article

  • What should you do differently when designing websites for an embedded web server

    - by Roger Attrill
    When designing a website to be accessed from an embedded webserver such as KLone, what do you need to do differently compared to a 'standard' web server. I'm talking about considerations at the front end design stage, before the actual building and coding up. For example, typically in such situations, memory size is a premium, so I guess larger images are out, and maybe more attention should be focused on achieving a good look and feel using CSS/Javascript rather than bitmap images.

    Read the article

  • What is the greatest design flaw you have faced in any programming language?

    - by Anto
    All programming languages are having their design flaws simply because not a single language can be perfect, just as with most (all?) other things. That aside, which design fault in a programming language has annoyed you the most through your history as a programmer? Note that if a language is "bad" just because it isn't designed for a specific thing isn't a design flaw, but a feature of design, so don't list such annoyances of languages. If a language is illsuited for what it is designed for, that is of course a flaw in the design. Implementation specific things and under the hood things do not count either.

    Read the article

  • Development: SDK for Social Net

    - by loldop
    I have a task: development sdk for social networking service like facebook, twitter and etc. At now i'm developing facebook-extension-sdk which based on facebook-ios-sdk 3.0. But not all social networking services have good sdks. And all time i improved my facebook-extension-sdk, when i see ugly code :( Please, advise me good techniques to development these sdks (like design-patterns or your own experience or good books/sites). Thanks!

    Read the article

  • How do I write code that doesn't suck? [closed]

    - by Afnan
    My friends and I would like to write a C# desktop application, and would like some guidance on how to make sure the code base is professional and well-kept. Should we use classes or interfaces for our inheritance patterns (which is better)? What are the best practices for professional applications? How do we know what sloppy code looks like, and how do we avoid creating sloppy code? Are there any best practices regarding the design of Winforms applications?

    Read the article

  • How can you tell whether to use Composite Pattern or a Tree Structure, or a third implementation?

    - by Aske B.
    I have two client types, an "Observer"-type and a "Subject"-type. They're both associated with a hierarchy of groups. The Observer will receive (calendar) data from the groups it is associated with throughout the different hierarchies. This data is calculated by combining data from 'parent' groups of the group trying to collect data (each group can have only one parent). The Subject will be able to create the data (that the Observers will receive) in the groups they're associated with. When data is created in a group, all 'children' of the group will have the data as well, and they will be able to make their own version of a specific area of the data, but still linked to the original data created (in my specific implementation, the original data will contain time-period(s) and headline, while the subgroups specify the rest of the data for the receivers directly linked to their respective groups). However, when the Subject creates data, it has to check if all affected Observers have any data that conflicts with this, which means a huge recursive function, as far as I can understand. So I think this can be summed up to the fact that I need to be able to have a hierarchy that you can go up and down in, and some places be able to treat them as a whole (recursion, basically). Also, I'm not just aiming at a solution that works. I'm hoping to find a solution that is relatively easy to understand (architecture-wise at least) and also flexible enough to be able to easily receive additional functionality in the future. Is there a design pattern, or a good practice to go by, to solve this problem or similar hierarchy problems? EDIT: Here's the design I have: The "Phoenix"-class is named that way because I didn't think of an appropriate name yet. But besides this I need to be able to hide specific activities for specific observers, even though they are attached to them through the groups. A little Off-topic: Personally, I feel that I should be able to chop this problem down to smaller problems, but it escapes me how. I think it's because it involves multiple recursive functionalities that aren't associated with each other and different client types that needs to get information in different ways. I can't really wrap my head around it. If anyone can guide me in a direction of how to become better at encapsulating hierarchy problems, I'd be very glad to receive that as well.

    Read the article

  • Flags with deferred use

    - by Trenton Maki
    Let's say I have a system. In this system I have a number of operations I can do but all of these operations have to happen as a batch at a certain time, while calls to activate and deactivate these operations can come in at any time. To implement this, I could use flags like doOperation1 and doOperation2 but this seems like it would become difficult to maintain. Is there a design pattern, or something similar, that addresses this situation?

    Read the article

  • Associating an Object with other Objects and Properties of those Objects

    - by alzoid
    I am looking for some help with designing some functionality in my application. I already have something similar designed but this problem is a little different. Background: In my application we have different Modules. Data in each module can be associated to other modules. Each Module is represented by an Object in our application. Module 1 can be associated with Module 2 and Module 3. Currently I use a factory to provide the proper DAO for getting and saving this data. It looks something like this: class Module1Factory { public static Module1BridgeDAO createModule1BridgeDAO(int moduleid) { switch (moduleId) { case Module.Module2Id: return new Module1_Module2DAO(); case Module.Module3Id: return new Module1_Module3DAO(); default: return null; } } } Module1_Module2 and Module1_Module3 implement the same BridgeModule interface. In the database I have a Table for every module (Module1, Module2, Module3). I also have a bridge table for each module (they are many to many) Module1_Module2, Module1_Module3 etc. The DAO basically handles all code needed to manage the association and retrieve its own instance data for the calling module. Now when we add new modules that associate with Module1 we simply implement the ModuleBridge interface and provide the common functionality. New Development We are adding a new module that will have the ability to be associated with other Modules as well as specific properties of that module. The module is basically providing the user the ability to add their custom forms to our other modules. That way they can collect additional information along with what we provide. I want to start associating my Form module with other modules and their properties. Ie if Module1 has a property Category, I want to associate an instance From data with that property. There are many Forms. If a users creates an instance of Module2, they may always want to also have certain form(s) attached to that Module2 instance. If they create an instance of Module2 and select Category 1, then I may want additional Form(s) created. I prototyped something like this: Form FormLayout (contains the labels and gui controls) FormModule (associates a form with all instances of a module) Form Instance (create an instance of a form to be filled out) As I thought about it I was thinking about making a new FormModule table/class/dao for each Module and Property that I add. So I might have: FormModule1 FormModule1Property1 FormModule1Property2 FormModule1Property3 FormModule1Property4 FormModule2 FormModule3 FormModule3Property1 Then as I did previously, I would use a factory to get the proper DAO for dealing with all of these. I would hand it an array of ids representing different modules and properties and it would return all of the DAOs that I need to call getForms(). Which in turn would return all of the forms for that particular bridge. Some points This will be for a new module so I dont need to expand on the factory code I provided. I just wanted to show an example of what I have done in the past. The new module can be associated with: Other Modules (ie globally for any instance of that module data), Other module properties (ie only if the Module instance has a certian value in one of its properties) I want to make it easy for developers to add associations with other modules and properties easily Can any one suggest any design patterns or strategy's for achieving this? If anything is unclear please let me know. Thank you, Al

    Read the article

  • Algorithm for creating a school timetable.

    - by cand
    Hello all. I've been wondering if there are known solutions for algorithm of creating a school timetable. Basically, it's about optimizing "hour-dispersion" (both in teachers and classes case) for given class-subject-teacher associations. We can assume that we have sets of classes, lesson subjects and teachers associated with each other at the input and that timetable should fit between 8AM and 4PM. I guess that there is probably no accurate algorithm for that, but maybe someone knows a good approximation or hints for developing it. P.S. I know, there was http://stackoverflow.com/questions/1259686/school-timetable-generation-algorithm-closed , but unlike in that case, I'm not looking for actual implementation, rather for thoughts on how to do it or why it's impossible.

    Read the article

  • Algorithm to generate all possible letter combinations of given string down to 2 letters

    - by Alan
    Algorithm to generate all possible letter combinations of given string down to 2 letters Trying to create an Anagram solver in AS3, such as this one found here: http://homepage.ntlworld.com/adam.bozon/anagramsolver.htm I'm having a problem wrapping my brain around generating all possible letter combinations for the various lengths of strings. If I was only generating permutations for a fixed length, it wouldn't be such a problem for me... but I'm looking to reduce the length of the string and obtain all the possible permutations from the original set of letters for a string with a max length smaller than the original string. For example, say I want a string length of 2, yet I have a 3 letter string of “abc”, the output would be: ab ac ba bc ca cb. Ideally the algorithm would produce a complete list of possible combinations starting with the original string length, down to the smallest string length of 2. I have a feeling there is probably a small recursive algorithm to do this, but can't wrap my brain around it. I'm working in AS3. Thanks!

    Read the article

  • Algorithm for digit summing?

    - by Joe
    I'm searching for an algorithm for Digit summing. Let me outline the basic principle: Say you have a number: 18268. 1 + 8 + 2 + 6 + 8 = 25 2 + 5 = 7 And 7 is our final number. It's basically adding each number of the whole number until we get down to a single (also known as a 'core') digit. It's often used by numerologists. I'm searching for an algorithm (doesn't have to be language in-specific) for this. I have searched Google for the last hour with terms such as digit sum algorithm and whatnot but got no suitable results. Any help would be great, thanks.

    Read the article

  • Stable random color algorithm

    - by Olmo
    Here we have an interesting real-world algorithm requirement involving colors. 1) Nice random colors: In ordeeing to draw a beautifull chart (i.e: pie chart) we need to pick a random set of Colors that: a) are different enought b) Play nicely Doesnt Look hard. For example u fix bright and saturation and divide hue in steps of 360/Num_sectors 2) Stable: given Pie1 with sectors with labes ('A','B','C') and Pie2 with sector with labels ('B','C','D'), will be nice if color('B',pie1)= color('B',pie2) and the same for 'C' and so on, so people don't get crazy when seeing similar updated charts, even if some sectors appear some dissapeared or the number of sectors changed. The label is the only stable thing. 3) hard-coded colors: the algorithm allows hardcoded label-color relationships as an input but stills doing a good work (1 & 2) for the rest of free labels. I think this algorithm, even if it looks quite ad-hoc, will be usefull in more then one situation. Any ideas?

    Read the article

  • Efficient algorithm to generate all solutions of a linear diophantine equation with ai=1

    - by Ben
    I am trying to generate all the solutions for the following equations for a given H. With H=4 : 1) ALL solutions for x_1 + x_2 + x_3 + x_4 =4 2) ALL solutions for x_1 + x_2 + x_3 = 4 3) ALL solutions for x_1 + x_2 = 4 4) ALL solutions for x_1 =4 For my problem, there are always 4 equations to solve (independently from the others). There are a total of 2^(H-1) solutions. For the previous one, here are the solutions : 1) 1 1 1 1 2) 1 1 2 and 1 2 1 and 2 1 1 3) 1 3 and 3 1 and 2 2 4) 4 Here is an R algorithm which solve the problem. library(gtools) H<-4 solutions<-NULL for(i in seq(H)) { res<-permutations(H-i+1,i,repeats.allowed=T) resum<-apply(res,1,sum) id<-which(resum==H) print(paste("solutions with ",i," variables",sep="")) print(res[id,]) } However, this algorithm makes more calculations than needed. I am sure it is possible to go faster. By that, I mean not generating the permutations for which the sums is H Any idea of a better algorithm for a given H ?

    Read the article

  • Using Dijkstra's algorithm with negative edges?

    - by Riddler
    Most books explain the reason the algorithm doesn't work with negative edges as nodes are deleted from the priority queue after the node is arrived at since the algorithm assumes the shortest distance has been found. However since negative edges can reduce the distance, a future shorter distance might be found; but since the node is deleted it cannot be updated. Wouldn't an obvious solution to this be to not delete the node? Why not keep the node in the queue, so if a future shorter distance is found, it can be updated? If I am misunderstanding the problem, what is preventing the algorithm from being used with negative edges?

    Read the article

  • Should pathfinder in A* hold closedSet and openedSet or each object should hold its sets?

    - by Patryk
    I am about to implement A* pathfinding algorithm and I wonder how should I implement this - from the point of view of architecture. I have the pathfinder as a class - I think I will instantiate only one object of this class (or maybe make it a Singleton - this is not so important). The hardest part for me is whether the closedSet and openedSet should be attached to objects that can find the path for them or should be stored in pathfinder class ? I am opened to any hints and critique whatsoever. What is the best practice considering pathfinding in terms of design ?

    Read the article

  • What algorithm can I use to detect simple shapes in a 4x4 matrix?

    - by ion
    I'm working on a simple multiplayer game that receives a random 4x4 matrix from a server and extracts a shape from it. For example: XXOO OXOO XXOX XXOO XOOX and XOOO XXXX OXXX So in the first matrix the shape I want to parse is: oo o oo and the 2nd: oo oo ooo I know there must be an algorithm for this because I saw this kind of behavior on some puzzle games but I have no idea how to go about to detecting them or even where to start. So my question is: How do I detect what shape is in the matrix and how do I differentiate between multiple colors? (it doesn't come only in X and O, it comes in a maximum of 4). Additionally, the shape must be a minimum of 4 blocks.

    Read the article

  • Design Question - how do you break the dependency between classes using an interface?

    - by Seth Spearman
    Hello, I apologize in advance but this will be a long question. I'm stuck. I am trying to learn unit testing, C#, and design patterns - all at once. (Maybe that's my problem.) As such I am reading the Art of Unit Testing (Osherove), and Clean Code (Martin), and Head First Design Patterns (O'Reilly). I am just now beginning to understand delegates and events (which you would see if you were to troll my SO questions of recent). I still don't quite get lambdas. To contextualize all of this I have given myself a learning project I am calling goAlarms. I have an Alarm class with members you'd expect (NextAlarmTime, Name, AlarmGroup, Event Trigger etc.) I wanted the "Timer" of the alarm to be extensible so I created an IAlarmScheduler interface as follows... public interface AlarmScheduler { Dictionary<string,Alarm> AlarmList { get; } void Startup(); void Shutdown(); void AddTrigger(string triggerName, string groupName, Alarm alarm); void RemoveTrigger(string triggerName); void PauseTrigger(string triggerName); void ResumeTrigger(string triggerName); void PauseTriggerGroup(string groupName); void ResumeTriggerGroup(string groupName); void SetSnoozeTrigger(string triggerName, int duration); void SetNextOccurrence (string triggerName, DateTime nextOccurrence); } This IAlarmScheduler interface define a component that will RAISE an alarm (Trigger) which will bubble up to my Alarm class and raise the Trigger Event of the alarm itself. It is essentially the "Timer" component. I have found that the Quartz.net component is perfectly suited for this so I have created a QuartzAlarmScheduler class which implements IAlarmScheduler. All that is fine. My problem is that the Alarm class is abstract and I want to create a lot of different KINDS of alarm. For example, I already have a Heartbeat alarm (triggered every (int) interval of minutes), AppointmentAlarm (triggered on set date and time), Daily Alarm (triggered every day at X) and perhaps others. And Quartz.NET is perfectly suited to handle this. My problem is a design problem. I want to be able to instantiate an alarm of any kind without my Alarm class (or any derived classes) knowing anything about Quartz. The problem is that Quartz has awesome factories that return just the right setup for the Triggers that will be needed by my Alarm classes. So, for example, I can get a Quartz trigger by using TriggerUtils.MakeMinutelyTrigger to create a trigger for the heartbeat alarm described above. Or TriggerUtils.MakeDailyTrigger for the daily alarm. I guess I could sum it up this way. Indirectly or directly I want my alarm classes to be able to consume the TriggerUtils.Make* classes without knowing anything about them. I know that is a contradiction, but that is why I am asking the question. I thought about putting a delegate field into the alarm which would be assigned one of these Make method but by doing that I am creating a hard dependency between alarm and Quartz which I want to avoid for both unit testing purposes and design purposes. I thought of using a switch for the type in QuartzAlarmScheduler per here but I know it is bad design and I am trying to learn good design. If I may editorialize a bit. I've decided that coding (predefined) classes is easy. Design is HARD...in fact, really hard and I am really fighting feeling stupid right now. I guess I want to know if you really smart people took a while to really understand and master this stuff or should I feel stupid (as I do) because I haven't grasped it better in the couple of weeks/months I have been studying. You guys are awesome and thanks in advance for your answers. Seth

    Read the article

  • DB Design Pattern - Many to many classification / categorised tagging.

    - by Robin Day
    I have an existing database design that stores Job Vacancies. The "Vacancy" table has a number of fixed fields across all clients, such as "Title", "Description", "Salary range". There is an EAV design for "Custom" fields that the Clients can setup themselves, such as, "Manager Name", "Working Hours". The field names are stored in a "ClientText" table and the data stored in a "VacancyClientText" table with VacancyId, ClientTextId and Value. Lastly there is a many to many EAV design for custom tagging / categorising the vacancies with things such as Locations/Offices the vacancy is in, a list of skills required. This is stored as a "ClientCategory" table listing the types of tag, "Locations, Skills", a "ClientCategoryItem" table listing the valid values for each Category, e.g., "London,Paris,New York,Rome", "C#,VB,PHP,Python". Finally there is a "VacancyClientCategoryItem" table with VacancyId and ClientCategoryItemId for each of the selected items for the vacancy. There are no limits to the number of custom fields or custom categories that the client can add. I am now designing a new system that is very similar to the existing system, however, I have the ability to restrict the number of custom fields a Client can have and it's being built from scratch so I have no legacy issues to deal with. For the Custom Fields my solution is simple, I have 5 additional columns on the Vacancy Table called CustomField1-5. This removes one of the EAV designs. It is with the tagging / categorising design that I am struggling. If I limit a client to having 5 categories / types of tag. Should I create 5 tables listing the possible values "CustomCategoryItems1-5" and then an additional 5 many to many tables "VacancyCustomCategoryItem1-5" This would result in 10 tables performing the same storage as the three tables in the existing system. Also, should (heaven forbid) the requirements change in that I need 6 custom categories rather than 5 then this will result in a lot of code change. Therefore, can anyone suggest any DB Design Patterns that would be more suitable to storing such data. I'm happy to stick with the EAV approach, however, the existing system has come across all the usual performance issues and complex queries associated with such a design. Any advice / suggestions are much appreciated. The DBMS system used is SQL Server 2005, however, 2008 is an option if required for any particular pattern.

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >