Search Results

Search found 1848 results on 74 pages for 'algorithms'.

Page 11/74 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • MATLAB: Best fitness vs mean fitness, initial range

    - by Sa Ta
    Based on the example of Rastrigin's function. At the plot function, if I chose 'best fitness', on the same graph 'mean fitness' will also be plotted. I understand well about 'best fitness' whereby it plots the best function value in each generation versus iteration number. It will reach value zero after some times. I don't understand about 'mean fitness'in the graph plotted. What do those 'mean fitness' values mean? How does the 'mean fitness' graph help to understand Rastrigin's function? What are the meaning of the term initial population, initial score and initial range? I wish to have a better understanding of these terms. The default value for initial range is [0,1]. Does it mean that 0 is the lower bound (lb) and 1 is the upper bound (ub)? Do these values interfere with the lb and ub values I set in the constraints? I try to better understand about lb and ub. If my lb is 0 and ub is 5, does it mean that my final point values will be within 0 and 5? If I know the lb and ub for my problem is between 0 and 5, do I just set the initial range as [0,5] at all times and may I assume that this is the best option for initial range, and I need not try it with any other values?

    Read the article

  • What is required for a scope in an injection framework?

    - by johncarl
    Working with libraries like Seam, Guice and Spring I have become accustomed to dealing with variables within a scope. These libraries give you a handful of scopes and allow you to define your own. This is a very handy pattern for dealing with variable lifecycles and dependency injection. I have been trying to identify where scoping is the proper solution, or where another solution is more appropriate (context variable, singleton, etc). I have found that if the scope lifecycle is not well defined it is very difficult and often failure prone to manage injections in this way. I have searched on this topic but have found little discussion on the pattern. Is there some good articles discussing where to use scoping and what are required/suggested prerequisites for scoping? I interested in both reference discussion or your view on what is required or suggested for a proper scope implementation. Keep in mind that I am referring to scoping as a general idea, this includes things like globally scoped singletons, request or session scoped web variable, conversation scopes, and others. Edit: Some simple background on custom scopes: Google Guice custom scope Some definitions relevant to above: “scoping” - A set of requirements that define what objects get injected at what time. A simple example of this is Thread scope, based on a ThreadLocal. This scope would inject a variable based on what thread instantiated the class. Here's an example of this: “context variable” - A repository passed from one object to another holding relevant variables. Much like scoping this is a more brute force way of accessing variables based on the calling code. Example: methodOne(Context context){ methodTwo(context); } methodTwo(Context context){ ... //same context as method one, if called from method one } “globally scoped singleton” - Following the singleton pattern, there is one object per application instance. This applies to scopes because there is a basic lifecycle to this object: there is only one of these objects instantiated. Here's an example of a JSR330 Singleton scoped object: @Singleton public void SingletonExample{ ... } usage: public class One { @Inject SingeltonExample example1; } public class Two { @Inject SingeltonExample example2; } After instantiation: one.example1 == two.example2 //true;

    Read the article

  • Find points whose pairwise distances approximate a given distance matrix

    - by Stephan Kolassa
    Problem. I have a symmetric distance matrix with entries between zero and one, like this one: D = ( 0.0 0.4 0.0 0.5 ) ( 0.4 0.0 0.2 1.0 ) ( 0.0 0.2 0.0 0.7 ) ( 0.5 1.0 0.7 0.0 ) I would like to find points in the plane that have (approximately) the pairwise distances given in D. I understand that this will usually not be possible with strictly correct distances, so I would be happy with a "good" approximation. My matrices are smallish, no more than 10x10, so performance is not an issue. Question. Does anyone know of an algorithm to do this? Background. I have sets of probability densities between which I calculate Hellinger distances, which I would like to visualize as above. Each set contains no more than 10 densities (see above), but I have a couple of hundred sets. What I did so far. I did consider posting at math.SE, but looking at what gets tagged as "geometry" there, it seems like this kind of computational geometry question would be more on-topic here. If the community thinks this should be migrated, please go ahead. This looks like a straightforward problem in computational geometry, and I would assume that anyone involved in clustering might be interested in such a visualization, but I haven't been able to google anything. One simple approach would be to randomly plonk down points and perturb them until the distance matrix is close to D, e.g., using Simulated Annealing, or run a Genetic Algorithm. I have to admit that I haven't tried that yet, hoping for a smarter way. One specific operationalization of a "good" approximation in the sense above is Problem 4 in the Open Problems section here, with k=2. Now, while finding an algorithm that is guaranteed to find the minimum l1-distance between D and the resulting distance matrix may be an open question, it still seems possible that there at least is some approximation to this optimal solution. If I don't get an answer here, I'll mail the gentleman who posed that problem and ask whether he knows of any approximation algorithm (and post any answer I get to that here).

    Read the article

  • How can I keep directories in sync

    - by Guillaume Boudreau
    I have a directory, dirA, that users can work in: they can create, modify, rename and delete files & sub-directores in dirA. I want to keep another directory, dirB, in sync with dirA. What I'd like, is a discussion on finding a working algorithm that would achieve the above, with the limitations listed below. Requirements: 1. Something asynchronous - I don't want to stop file operations in dirA while I work in dirB. 2. I can't assume that I can just blindly rsync dirA to dirB on regular interval - dirA could contain millions of files & directories, and terrabytes of data. Completely walking the dirA tree could take hours. Those two requirements makes this really difficult. Having it asynchronous means that when I start working on a specific file from dirA, it might have moved a lot since it appeared. And the second limitation means that I really need to watch dirA, and work on atomic file operations that I notice. Current (broken) implementation: 1. Log all file & directory operations in dirA. 2. Using a separate process, read that log, and 'repeat' all the logged operations in dirB. Why is it broken: echo 1 > dirA/file1 # Allow the 'log reader' process to create dirB/file1: log = "write dirA/file1"; action = cp dirA/file1 dirB/file1; result = OK echo 1 > dirA/file2 mv dirA/file1 dirA/file3 mv dirA/file2 dirA/file1 rm dirA/file3 # End result: file1 contains '1' # 'log reader' process starts working on the 4 above file operations: log = "write file2"; action = cp dirA/file2 dirB/file2; result = failed: there is no dirA/file2 log = "rename file1 file3"; action = mv dirB/file1 dirB/file3; result = OK log = "rename file2 file1"; action = mv dirB/file2 dirB/file1; result = failed: there is no dirB/file2 log = "delete file3"; action = rm dirB/file3; result = OK # End result in dirB: no more files! Another broken example: echo 1 > dirA/dir1/file1 mv dirA/dir1 dirA/dir2 # 'log reader' process starts working on the 2 above file operations: log = "write file1"; action = cp dirA/dir1/file1 dirB/dir1/file1; result = failed: there is no dirA/dir1/file1 log = "rename dir1 dir2"; action = mv dirB/dir1 dirB/dir2; result = failed: there is no dirA/dir1 # End result if dirB: nothing!

    Read the article

  • Building general programming skills?

    - by toleero
    Hello :) I currently am quite new to programming, I've had exposure to a few languages (C#, PHP, JavaScript, VB, and some others) and I'm quite new to OOP. I was just wondering what is the best way to build up general programming/problem solving skills without being language specific? I was thinking maybe of something like Project Euler but more geared towards newbies? Thanks! Edit: I am looking at getting into Game Scripting/Programming, I'm already in Games but in a different discipline :)

    Read the article

  • Which is the most practical way to add functionality to this piece of code?

    - by Adam Arold
    I'm writing an open source library which handles hexagonal grids. It mainly revolves around the HexagonalGrid and the Hexagon class. There is a HexagonalGridBuilder class which builds the grid which contains Hexagon objects. What I'm trying to achieve is to enable the user to add arbitrary data to each Hexagon. The interface looks like this: public interface Hexagon extends Serializable { // ... other methods not important in this context <T> void setSatelliteData(T data); <T> T getSatelliteData(); } So far so good. I'm writing another class however named HexagonalGridCalculator which adds some fancy pieces of computation to the library like calculating the shortest path between two Hexagons or calculating the line of sight around a Hexagon. My problem is that for those I need the user to supply some data for the Hexagon objects like the cost of passing through a Hexagon, or a boolean flag indicating whether the object is transparent/passable or not. My question is how should I implement this? My first idea was to write an interface like this: public interface HexagonData { void setTransparent(boolean isTransparent); void setPassable(boolean isPassable); void setPassageCost(int cost); } and make the user implement it but then it came to my mind that if I add any other functionality later all code will break for those who are using the old interface. So my next idea is to add annotations like @PassageCost, @IsTransparent and @IsPassable which can be added to fields and when I'm doing the computation I can look for the annotations in the satelliteData supplied by the user. This looks flexible enough if I take into account the possibility of later changes but it uses reflection. I have no benchmark of the costs of using annotations so I'm a bit in the dark here. I think that in 90-95% of the cases the efficiency is not important since most users wont't use a grid where this is significant but I can imagine someone trying to create a grid with a size of 5.000.000.000 X 5.000.000.000. So which path should I start walking on? Or are there some better alternatives? Note: These ideas are not implemented yet so I did not pay too much attention to good names.

    Read the article

  • Filling array with numbers from given range so that sum of adjacent numbers is square number

    - by REACHUS
    Problem: Fill all the cells using distinct numbers from <1,25 set, so that sum of two adjacent cells is a square number. (source: http://grymat.im.pwr.wroc.pl/etap1/zad1etp1213.pdf; numbers 20 and 13 have been given) I've already solved this problem analytically and now I would like to approach it using an algorithm. I would like to know how should I approach these kind of problems in general (not a solution, just a point for me to start).

    Read the article

  • What is the usage of Spaly Trees in the real world?

    - by Meena
    I decided to learn about Balance search trees, so I picked 2-3-4 and splay trees. I'm wondering what are the examples of splay trees usage in the real world? In this Cornell: http://www.cs.cornell.edu/courses/cs3110/2009fa/recitations/rec-splay.html I read that splay trees are 'A good example is a network router'. But from rest of the explanation seams like network routers use hash tables and not splay trees since the lookup time is constant instead of O(log n). thanks!

    Read the article

  • Permission Management Algorithm

    - by Emerald214
    I have 3 levels of permission to see the product: Brand - Allow/Deny Category - Allow/Deny Product - Allow/Deny For example, product A has: Category: Allow Product: Deny = product A cannot be seen because product A isn't allowed in Product level. if(allowForCategory == true) { if(allowForProduct == false) return false; if(allowForProduct == true) return true; } else { ... } This is not a good choice because it will become more complex if we add brand level. if() { if() { if() {} } } So is there any general algorithm to deal with the permission problem just like 777 solution in Linux?

    Read the article

  • Elo system behaves oddly in program I've created

    - by adc
    Alright, so I'm looking to build a small program (C# and XAML) that, essentially, does this: Generate array of players. Each player has a current rating and a true rating. I set current rating to 1200 as a starting point right now; I've also tried setting it to true rating and the average of the two. True rating is what their skill level actually is. Their true rating is calculated based on percentages from the current League of Legends rating system; generating an array of 970 thousand generates results very similar to the data from here: (removed due to URL limit - but trust me, the results are very similar). This array is of length specified by the user. If need be, sort the array from smallest to largest. Play X number of games, again specified by the user. This is done by taking the array of players (which is sorted by Current Rating after being created) and running through it in groups of 10. The first five are on team one, the second five are on team two. It then takes the True Rating of these players and calculates an expected chance to win using the Elo system. It generates a random double and compares it to the expected chance to win; if the number is lower, team one wins - otherwise team two wins. I then update the rating of the players via, again, the Elo system - giving the winning team a score of 1 and the losing team a score of 0. I use a K value of 36 (but have tried 12, 24, and even higher ones) and an F value of 400. After going through the entire loop of players (which I have conveniently forced to be a multiple of ten), it sorts the array - again via current rating. This, if my understanding of the Elo system is correct, runs properly. However, it doesn't seem to work. I have a running test telling me how many players of the full array are within 100 current rating of their true rating. I would expect some portion of the population to be outside this range (as probability is not always going to go in their favor), but a full 40-45% of the population is outside of this range. I also have it outputting the maximum difference between true and current rating - and I have never seen this drop below 500! It hovers between 550-600, occasionally going over or under. I'm at a loss as to what to change - I've fiddled with the K and F values, where I start all the players, etc. but nothing changes the fact that eventually a good 40% of the population is outside the range. And it isn't that I have it playing too few games - it's now run through over 60 thousand games and the problem never disappears or really fluctuates. The full C# code, including everything except the XAML file and the Player class (pastebin is being very slow and I can only post two links, so I can't link to the XAML file): http://pastebin.com/rFcZRL84 The Player class: http://pastebin.com/4cJTdTRu I guess my question is did I do anything wrong? Is there a problem with the way I implemented the system, or is it just that Riot uses a significantly modified Elo system? I don't think it's the latter, as that still wouldn't explain the massive true and current rating differences to me, however.

    Read the article

  • Async CTP Refresh for Visual Studio 2010 SP1 Released

    - by Reed
    The Visual Studio team today released an update to the Visual Studio Async CTP which allows it to be used with Visual Studio SP1.  This new CTP includes some very nice new additions over the previous CTP.  The main highlights of this release include: Compatibility with Visual Studio SP1 APIs for Windows Phone 7 Compatibility with non-English installations Compatibility with Visual Studio Express Edition More efficient Async methods due to a change in the API Numerous bug fixes New EULA which allows distribution in production environments Anybody using the Async CTP should consider upgrading to the new version immediately.  For details, visit the Visual Studio Asynchronous Programming page on MSDN.

    Read the article

  • Can this word search algorithm be made faster?

    - by Ashwin Singh
    Problem: Find a match of word S in text T Given: S and T are part of spoken and written English. Example: Match 'Math' in 'I love Mathematics' NOTE: Ignore CASES. My algorithm: STEP 1) Convert S, T to char[] STEP 2) for i=0, i < T.length , i++ STEP 3) for j=S.length-1, j>0 , j-- STEP 3 is the magic, instead of going about matching M,A,T,H, this matches M, H, T and finally A. This helps in eliminating a lot of possible partial matches. For example, if I go sequentially like M A as in Boyer Moore's method ... it can match Matter, Mass, Matchstick etc. using M _ _ H will bring down size of partial matches. STEP 4) if S[j]!=T[i] -> break; else if j==i -> PRINT MATCH

    Read the article

  • Algorithm to infer tag hierarchy

    - by Tom
    I'm looking for an algorithm to infer a hierarchy from a set of tagged items. E.g. if the following items have the tags: 1 a 2 a,b 3 a,c 4 a,c,e 5 a,b 6 a,c 7 d 8 d,f Then I can construct an undirected graph (or graphs) by tallying the node weights and edge weights: node weights edge weights a 6 a-b 2 b 2 a-c 3 c 3 c-e 1 d 2 a-e 1 <-- this edge is parallel to a-c and c-e and not wanted e 1 d-f 1 f 1 The first problem is how to drop any redundant edges to get to the simplified graph? Note that it's only appropriate to remove that redundant a-e edge in this case because something is tagged as a-c-e, if that wasn't the case and the tag was a-e, that edge would have to remain. I suspect that means the removal of edges can only happen during the construction of the graph, not after everything has been tallied up. What I'd then like to do is identify the direction of the edges to create a directed graph (or graphs) and pick out root nodes to hopefully create a tree (or trees): trees a d // \\ | b c f \ e It seems like it could be a string algorithm - longest common subsequences/prefixes - or a tree/graph algorithm, but I am a little stuck since I don't know the correct terminology to search for it.

    Read the article

  • Algorithm to match items be value into sets base on total

    - by Ben
    Given n sets of items. Each item has a value. The items in a set have similar values but vary by a small amount. The goal is to create new sets containing three items selected from the original sets such that the total of the values is within a given range. Only one item a source set can be selected. For example: If we have the following starting sets: Set A - { 4.0, 3.8, 4.2 } Set B - { 7.0, 6.8, 7.2 } Set C - { 1.0, 0.9, 1.1 } Set D - { 6.5, 6.4, 6.6 } Set E - { 2.5, 2.4, 2.6 } Goal is to create sets containing three elements such that the total is between 11.9 and 12.1. For example { 3.8, 7.2, 1.0 } There can be unused elements. Can someone suggest an algorithm for this problem?

    Read the article

  • Common mistakes made by new programmers without CS backgrounds [on hold]

    - by mblinn
    I've noticed that there seems to be a class of mistakes that new programmers without CS backgrounds tend to make, that programmers with CS backgrounds tend not to. I'm not talking about not understanding source control, or how to design large programs, or a whole host of other things that both freshly minted CS graduates and non-CS graduates tend to not understand, I'm talking about basic mistakes that having a CS background will prevent a programmer from making. One obvious and well trod example is that folks who don't have a basic understanding of formal languages will often try to parse arbitrary HTML or XML using regular expressions, and possibly summon Cthulu in the process. Another fairly common one that I've seen is using common data structures in suboptimal ways like using a vector and a search function as if it were a hash map. What sorts of other things along these lines would you look out for when on-boarding a batch of newly minted, non-CS programmers.

    Read the article

  • What is the best way to keep track of the median?

    - by Steven Mou
    I read a question in one book: Numbers are randomly generated and stored into an (expanding) array, How would you keep track of the median? There are two data structures can solve the problem. One is the balanced binary tree, the other is two heaps which keep trace of the biggest half and the smallest half of the elements. I think these two solutions has the same running time as O(n lg n), but I am not sure of my judgement. In your opinions, What is the best way to keep track of the median?

    Read the article

  • Given a string of letters from alphabet insert frequency of each character in the string.in O(n) time and O(1) space [on hold]

    - by learner
    Below is my attempt void str_freq(char *str, int len) { char c; int cnt=0; c=str[0]; int i,j=0; for(i=0;i<len;i++) { if(c==str[i]) { cnt++; } else { c = str[i]; // printf(" %d ",cnt); str[j] = str[i-1]; str[j+1] = (char)(((int)'0')+cnt); j++; cnt=0; } } str[j+1]='\0'; printf("%s",str); } int main() { char str[] = "aaabbccccdeffgggg"; int length=strlen(str); str_freq(str,length); } I am getting wrong answer abcdef1 instead of a3b2c4d1e1f2g4. Please let me know where I am going wrong.

    Read the article

  • I have a stacktrace and limit of 250 characters for a bug report

    - by George Duckett
    I'm developing an xbox indie game and as a last-resort I have a try...catch encompassing everything. At this point if an exception is raised I can get the user to send me a message through the xbox however the limit is 250 characters. How can I get the most value out of my 250 characters? I don't want to do any encoding / compressing at least initially. Any solution to this problem could be compressed if needed as a second step anyway. I'm thinking of doing things like turning this: at EasyStorage.SaveDevice.VerifyIsReady() at EasyStorage.SaveDevice.Save(String containerName, String fileName) into this (drop the repeated namespace/class and method parameter names): at EasyStorage.SaveDevice.VerifyIsReady() at ..Save(String, String) Or maybe even just including the inner-most method, then only line numbers up the stack etc. TL;DR: Given an exception with a stacktrace how would you get the most useful debugging infromation out of 250 characters? (It will be a .net exception/stacktrace)

    Read the article

  • Algorithm to reduce calls to mapping API

    - by aidan
    A random distribution of points lies on a map. This data lies behind an API, and I want to grab the complete set of points within a given bounding box. I can query the API with the bounding box and the API will return the set of points that fall within that box. The problem is that the API will limit the result set to 10 items, with no pagination and no indication if there are more points that have been omitted. So I made a recursive algorithm that takes a bounding box and requests the points that lie within it. If the result set is exactly 10 items, then I split the bounding box into four quadrants and recurse. It works fine but my question is this: if want to minimize the number of API calls, what is the optimal way to split the bounding box? Splitting it into quadrants was just an arbitrary decision. When there are a lot of points on the map, I have to drill down many levels before I start getting meaningful results. So I imagine it might be faster to split the box into, say, 9, 16, or more sections. But if I do that, then I eventually get to a point where a lot of requests are returning 0 results which isn't so efficient. Also, does the size of the limit on the results set affect the answer? (This is all assuming that I have no prior knowledge of nominal point density in the bounding box)

    Read the article

  • Algorithm for detecting windows in a room

    - by user2733436
    I am dealing with the following problem and i was looking to write a Pseudo-code for developing an algorithm that can be generic for such a problem. Here is what i have come up with thus far. STEP 1 In this step i try to get the robot where it maybe placed to the top left corner. Turn Left - If no window or Wall detected keep going forward 1 unit.. if window or wall detected -Turn right -- if no window or Wall detected keep going forward.. if window or wall detected then top left corner is reached. STEP 2 (We start counting windows after we get to this stage to avoid miscounting) I would like to declare a variable called turns as it will help me keep track if robot has gone around entire room. Turns = 4; Now we are facing north and placed on top left corner. while(turns0){ If window or wall detected (if window count++) Turn Right Turn--; While(detection!=wall || detection!=window){ move 1 unit forward Turn left (if window count++) Turn right } } I believe in doing so the robot will go around the entire room and count windows and it will stop once it has gone around the entire room as the turns get decremented. I don't feel this is the best solution and would appreciate suggestions on how i can improve my Pseudo-code. I am not looking for any code just a algorithm on solving such a problem and that is why i have not posted this in stack overflow. I apologize if my Pseudo-code is poorly written please make suggestions if i can improve that as i am new to this. Thanks.

    Read the article

  • Are there currently any modern, standardized, aptitude test for software engineering?

    - by Matthew Patrick Cashatt
    Background I am a working software engineer who is in the midst of seeking out a new contract for the next year or so. In my search, I am enduring several absurd technical interviews as indicated by this popular question I asked earlier today. Even if the questions I was being asked weren't almost always absurd, I would be tired nonetheless of answering them many times over for various contract opportunities. So this got me thinking that having a standardized exam that working software professionals could take would provide a common scorecard that could be referenced by interviewers in lieu of absurd technical interview questions (i.e. nerd hazing). Question Is there a standardized software engineering aptitude test (SEAT??) available for working professionals to take? If there isn't a such an exam out there, what questions or topics should be covered? An additional thought Please keep in mind, if suggesting a question or topic, to focus on questions or topics that would be relevant to contemporary development practices and realistic needs in the workforce as that would be the point of a standard aptitude test. In other words, no clown traversal questions.

    Read the article

  • Ways to dynamically render a real world 3d environment in Unity3D

    - by Jake M
    Using Unity3D and C# I am attempting to display a 3d version of a real world location. Inside my Unity3D app, the user will specify the GPS coordinates of a location, then my app will have to generate a 3d plane(anything doesn't have to be a plane) of that location. The plane will show a 500 metre by 500 metre 3d snapshot of that location. How would you suggest I achieve this in Unity3D? What methodology would you use to achieve this? NOTE: I understand that this is a very difficult endevour(to render real world locations dynamically in Unity3d) so I expect to perform many actions to achieve this. I just don't know of all the technologies out there and which would be best for my needs For example: Suggested methodology 1: Prompt user to specify GPS coords Use Google earth API and HTTP to programmatically obtain a .khm file describing that location(Not sure if google earth provides that capability does it?) Unzip the .khm so I have the .dae file Convert that file to a .3ds file using ??? third party converter(is there a converter that exists?) Import .3ds into Unity3D at runtime as a plane(is this possible)? Suggested methodology 2: Prompt user to specify GPS coords Use Google earth API and HTTP to programmatically obtain a .khm file describing that location(Not sure if google earth provides that capability does it?) Unzip the .khm so I have the .dae file Parse .dae file using my own C# parser I will write(do you think its possible to write a .dae parser that can parse the .dae into an array of Vector3 that describe the height map of that location?) Dynamically create a plane in Unity3D and populate it with my array/list of Vector3 points(is it possible to create a plane this way?) Maybe I am meant to create a mesh instead of a plane? Can you think of any other ways I could render a real world 3d environment in Unity3D?

    Read the article

  • Detect duplicate in a subset from a set of elements

    - by Abhinav Shrivastava
    I have a set of numbers say : 1 1 2 8 5 6 6 7 8 8 4 2... I want to detect the duplicate element in subsets(of given size say k) of the above numbers... For example : Consider the increasing subsets(for example consider k=3) Subset 1 :{1,1,2} Subset 2 :{1,2,8} Subset 3 :{2,8,5} Subset 4 :{8,5,6} Subset 5 :{5,6,6} Subset 6 :{6,6,7} .... .... So my algorithm should detect that subset 1,5,6 contains duplicates.. My approach : 1)Copy the 1st k elements to a temporary array(vector) 2) using #include file in C++ STL...using unique() I would determine if there's any change in size of vector.. Any other clue how to approach this problem..

    Read the article

  • Microsoft Interview Preparation

    - by Manish
    I have 8 years of java background. Need help in identifying topics I need to prepare for Microsoft interview. I need to know how many rounds Microsoft will have and what all things these rounds consist of. I have identified the following topics. Please let me know if I need to prepare anything else as well. Arrays Linked Lists Recursion Stacks Queue Trees Graph -- What all I should prepare here Dynamic Programming -- again what all I need to prepare Sorting, Searching String Algos

    Read the article

  • Indefinite loops where the first time is different

    - by George T
    This isn't a serious problem or anything someone has asked me to do, just a seemingly simple thing that I came up with as a mental exercise but has stumped me and which I feel that I should know the answer to already. There may be a duplicate but I didn't manage to find one. Suppose that someone asked you to write a piece of code that asks the user to enter a number and, every time the number they entered is not zero, says "Error" and asks again. When they enter zero it stops. In other words, the code keeps asking for a number and repeats until zero is entered. In each iteration except the first one it also prints "Error". The simplest way I can think of to do that would be something like the folloing pseudocode: int number = 0; do { if(number != 0) { print("Error"); } print("Enter number"); number = getInput(); }while(number != 0); While that does what it's supposed to, I personally don't like that there's repeating code (you test number != 0 twice) -something that should generally be avoided. One way to avoid this would be something like this: int number = 0; while(true) { print("Enter number"); number = getInput(); if(number == 0) { break; } else { print("Error"); } } But what I don't like in this one is "while(true)", another thing to avoid. The only other way I can think of includes one more thing to avoid: labels and gotos: int number = 0; goto question; error: print("Error"); question: print("Enter number"); number = getInput(); if(number != 0) { goto error; } Another solution would be to have an extra variable to test whether you should say "Error" or not but this is wasted memory. Is there a way to do this without doing something that's generally thought of as a bad practice (repeating code, a theoretically endless loop or the use of goto)? I understand that something like this would never be complex enough that the first way would be a problem (you'd generally call a function to validate input) but I'm curious to know if there's a way I haven't thought of.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >