Search Results

Search found 1552 results on 63 pages for 'homework'.

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

  • Array Vs. Linked List

    - by Onorio Catenacci
    I apologize--this question may be a bit open-ended but I think there are probably definite, quantifiable answers to it so I'll post it anyway. A person I know is trying to learn C++ and software development (+1 to him) and he asked me why someone would want to use a linked list in preference to an array. Coding a linked list is, no doubt, a bit more work than using an array and he wondered what would justify the additional effort. I gave him the answer I know: insertion of new elements is trivial in linked list but it's a major chore in an array. But then I got to thinking about it a bit more. Besides the ease of insertion of a new element into a linked list are there other advantages to using a linked list to store a set of data vs. storing it in an array? As I said, I'm not meaning to start a long and drawn-out discussion. I'm just looking for other reasons that a developer might prefer a linked list to an array.

    Read the article

  • Help to solve "Robbery Problem"

    - by peiska
    Hello, Can anybody help me with this problem in C or Java? The problem is taken from here: http://acm.pku.edu.cn/JudgeOnline/problem?id=1104 Inspector Robstop is very angry. Last night, a bank has been robbed and the robber has not been caught. And this happened already for the third time this year, even though he did everything in his power to stop the robber: as quickly as possible, all roads leading out of the city were blocked, making it impossible for the robber to escape. Then, the inspector asked all the people in the city to watch out for the robber, but the only messages he got were of the form "We don't see him." But this time, he has had enough! Inspector Robstop decides to analyze how the robber could have escaped. To do that, he asks you to write a program which takes all the information the inspector could get about the robber in order to find out where the robber has been at which time. Coincidentally, the city in which the bank was robbed has a rectangular shape. The roads leaving the city are blocked for a certain period of time t, and during that time, several observations of the form "The robber isn't in the rectangle Ri at time ti" are reported. Assuming that the robber can move at most one unit per time step, your program must try to find the exact position of the robber at each time step. Input The input contains the description of several robberies. The first line of each description consists of three numbers W, H, t (1 <= W,H,t <= 100) where W is the width, H the height of the city and t is the time during which the city is locked. The next contains a single integer n (0 <= n <= 100), the number of messages the inspector received. The next n lines (one for each of the messages) consist of five integers ti, Li, Ti, Ri, Bi each. The integer ti is the time at which the observation has been made (1 <= ti <= t), and Li, Ti, Ri, Bi are the left, top, right and bottom respectively of the (rectangular) area which has been observed. (1 <= Li <= Ri <= W, 1 <= Ti <= Bi <= H; the point (1, 1) is the upper left hand corner, and (W, H) is the lower right hand corner of the city.) The messages mean that the robber was not in the given rectangle at time ti. The input is terminated by a test case starting with W = H = t = 0. This case should not be processed. Output For each robbery, first output the line "Robbery #k:", where k is the number of the robbery. Then, there are three possibilities: If it is impossible that the robber is still in the city considering the messages, output the line "The robber has escaped." In all other cases, assume that the robber really is in the city. Output one line of the form "Time step : The robber has been at x,y." for each time step, in which the exact location can be deduced. (x and y are the column resp. row of the robber in time step .) Output these lines ordered by time . If nothing can be deduced, output the line "Nothing known." and hope that the inspector will not get even more angry. Output a blank line after each processed case.

    Read the article

  • Creating GUI for Bantumi game

    - by owca
    I've written backend for simple Bantumi game. Now I'd like to create a simple GUI for it, so that it would look like this : How to start ? What layout should I use, and what type of component each element should be? Classes : Basket Player Game Main Shared

    Read the article

  • Beginner problems with references to arrays in python 3.1.1

    - by Protean
    As part of the last assignment in a beginner python programing class, I have been assigned a traveling sales man problem. I settled on a recursive function to find each permutation and the sum of the distances between the destinations, however, I am have a lot of problems with references. Arrays in different instances of the Permute and Main functions of TSP seem to be pointing to the same reference. from math import sqrt class TSP: def __init__(self): self.CartisianCoordinates = [['A',[1,1]], ['B',[2,2]], ['C',[2,1]], ['D',[1,2]], ['E',[3,3]]] self.Array = [] self.Max = 0 self.StoredList = ['',0] def Distance(self, i1, i2): x1 = self.CartisianCoordinates[i1][1][0] y1 = self.CartisianCoordinates[i1][1][1] x2 = self.CartisianCoordinates[i2][1][0] y2 = self.CartisianCoordinates[i2][1][1] return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2)) def Evaluate(self): temparray = [] Data = [] for i in range(len(self.CartisianCoordinates)): Data.append([]) for i1 in range(len(self.CartisianCoordinates)): for i2 in range(len(self.CartisianCoordinates)): if i1 != i2: temparray.append(self.Distance(i1, i2)) else: temparray.append('X') Data[i1] = temparray temparray = [] self.Array = Data self.Max = len(Data) def Permute(self,varray,index,vcarry,mcarry): #Problem Class array = varray[:] carry = vcarry[:] for i in range(self.Max): print ('ARRAY:', array) print (index,i,carry,array[index][i]) if array[index][i] != 'X': carry[0] += self.CartisianCoordinates[i][0] carry[1] += array[index][i] if len(carry) != self.Max: temparray = array[:] for j in range(self.Max):temparray[j][i] = 'X' index = i mcarry += self.Permute(temparray,index,carry,mcarry) else: return mcarry print ('pass',mcarry) return mcarry def Main(self): out = [] self.Evaluate() for i in range(self.Max): array = self.Array[:] #array appears to maintain the same reference after each copy, resulting in an incorrect array being passed to Permute after the first iteration. print (self.Array[:]) for j in range(self.Max):array[j][i] = 'X' print('I:', i, array) out.append(self.Permute(array,i,[str(self.CartisianCoordinates[i][0]),0],[])) return out SalesPerson = TSP() print(SalesPerson.Main()) It would be greatly appreciated if you could provide me with help in solving the reference problems I am having. Thank you.

    Read the article

  • Proving that a function f(n) belongs to a Big-Theta(g(n))

    - by PLS
    Its a exercise that ask to indicate the class Big-Theta(g(n)) the functions belongs to and to prove the assertion. In this case f(n) = (n^2+1)^10 By definition f(n) E Big-Theta(g(n)) <= c1*g(n) < f(n) < c2*g(n), where c1 and c2 are two constants. I know that for this specific f(n) the Big-Theta is g(n^20) but I don't know who to prove it properly. I guess I need to manipulate this inequality but I don't know how

    Read the article

  • I'm working on Peano Axioms in Agda and I've hit a bit of a sticking point

    - by Schroedinger
    PA6 : ?{m n} -> m = n -> n = m is the axiom I am trying to solve and support, I've tried using a cong (from the core library) but am having troubles with the cong constructor PA6 = cong gets me nowhere, I know for cong I am required to supply a refl for equality and a type, but I'm, not sure what type I'm supposed to supply. Ideas? This is for a small assignment at University, so I'd rather someone demonstrate what I've missed rather than write the acutual answer, but I'd appreciate any degree of support.

    Read the article

  • polynomial multiplication using fastfourier transform

    - by mawia
    i am going through the above topic from CLRS(CORMEN) (page 834) and I got stuck at this point. Can anybody please explain how the following expression, A(x)=A^{[0]}(x^2) +xA^{[1]}(x^2) follows from, n-1 ` S a_j x^j j=0 Where, A^{[0]} = a_0 + a_2x + a_4a^x ... a_{n-2}x^{\frac{n}{2-1}} A^{[1]} = a_1 + a_3x + a_5a^x ... a_{n-1}x^{\frac{n}{2-1}} WITH REGARDS THANKS

    Read the article

  • How do you solve the 15-puzzle with A-Star or Dijkstra's Algorithm?

    - by Sean
    I've read in one of my AI books that popular algorithms (A-Star, Dijkstra) for path-finding in simulation or games is also used to solve the well-known "15-puzzle". Can anyone give me some pointers on how I would reduce the 15-puzzle to a graph of nodes and edges so that I could apply one of these algorithms? If I were to treat each node in the graph as a game state then wouldn't that tree become quite large? Or is that just the way to do it?

    Read the article

  • programming logic and design pleas friends i need a flowcharts or pseudocode

    - by alex
    ***the midvile park maintains records containing info about players on it's soccer teams . each record contain a players first name,last name,and team number . the team are team number team name 1 goal getters 2 the force 3 top gun 4 shooting stars 5 midfield monsters design a proggram that accept player data and creates a report that lists each** player a long with his or her team number and team name**

    Read the article

  • Converting Unicode strings to escaped ascii string

    - by Ali
    How can I convert this string: This string contains the unicode character Pi(p) into an escaped ascii string: This string contains the unicode character Pi(\u03a0) and vice versa ? The current Encoding available in C#, converts the p character into "?". I need to preserve that character.

    Read the article

  • Which knowledge base/rule-based inference engine to choose for real time Runway incursion prevention

    - by Piligrim
    Hello, we are designing a project that would listen to dialog between airport controllers and pilots to prevent runway incursions (eg. one airplane is taking off while other is crossing the runway). Our professor wants us to use Jena for knowledge base (or anything else but it should be some sort of rule-based engine). Inference is not the main thing in Jena and there's not much documentation and examples of this. So we need an engine that would get messages from pilots as input and output possible risks of incursion or any other error in message protocol. It should be easy to write rules, and should be easy to provide engine with real time data. I image it something like this: A pilot sends a message that he lands on some runway, the system remembers that the runway is busy and no one should cross it If someone is given an instruction to cross this runway, the engine should fire a rule that something is wrong When the pilot sends a message that he left the runway and goes to the gate, the system clears the runway and lets other planes to use it. So is Jena, or prolog or any other rules engine suitable for this? I mean it is suitable, but do we really need to use it? I asked the prof. if we could just keep state of the runway and use some simple checks based on messages we receive and he said that it is not scalable and we need the knowledge base. Can someone give me any advise on which approach to use for this system? If you recommend k.b., then which one should we use? The project is written in java. Thank you.

    Read the article

  • C++ help with getline function with ifstream

    - by John
    So I am writing a program that deals with reading in and writing out to a file. I use the getline() function because some of the lines in the text file may contain multiple elements. I've never had a problem with getline until now. Here's what I got. The text file looks like this: John Smith // Client name 1234 Hollow Lane, Chicago, IL // Address 123-45-6789 // SSN Walmart // Employer 58000 // Income 2 // Number of accounts the client has 1111 // Account Number 2222 // Account Number ifstream inFile("ClientInfo.txt"); if(inFile.fail()) { cout << "Problem opening file."; } else { string name, address, ssn, employer; double income; int numOfAccount; getline(inFile, name); getline(inFile, address); // I'll stop here because I know this is where it fails. When I debugged this code, I found that name == "John", instead of name == "John Smith", and Address == "Smith" and so on. Am I doing something wrong. Any help would be much appreciated.

    Read the article

  • Taking User Input in Java

    - by jdbeverly87
    I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `public class Palindrome { public static void main(String args[]) { String s=""; int i; int n=s.length(); String str=""; for(i=n-1;i>=0;i--) str=str+s.charAt(i); if(str.equals(s)) System.out.println(s+ " is a palindrome"); else System.out.println(s+ " is not a palindrome"); } }

    Read the article

  • Can't find how to import as one object or how to merge

    - by Aaron
    I need write a script in blender that creates some birds which fly around some obstacles. The problem is that I need to import a pretty large Collada model (a building) which consists of multiple objects. The import works fine, but the the building is not seen as 1 object. I need to resize and move this building, but I can only get the last object in the building (which is a camera)... Does anyone know how to merge this building in 1 object, group, variable... so I can resize and move it correctly? Part of the code I used: bpy.ops.wm.collada_import(filepath="C:\\Users\\me\\building.dae") building= bpy.context.object building.scale = (100, 100, 100) building.name = "building"

    Read the article

  • Why is my Pre to Postfix code not working?

    - by Anthony Glyadchenko
    For a class assignment, I have to use two stacks in C++ to make an equation to be converted to its left to right equivalent: 2+4*(3+4*8) -- 35*4+2 -- 142 Here is the main code: #include <iostream> #include <cstring> #include "ctStack.h" using namespace std; int main (int argc, char * const argv[]) { string expression = "2+4*2"; ctstack *output = new ctstack(expression.length()); ctstack *stack = new ctstack(expression.length()); bool previousIsANum = false; for(int i = 0; i < expression.length(); i++){ switch (expression[i]){ case '(': previousIsANum = false; stack->cmstackPush(expression[i]); break; case ')': previousIsANum = false; char x; while (x != '('){ stack->cmstackPop(x); output->cmstackPush(x); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': cout << "A number" << endl; previousIsANum = true; output->cmstackPush(expression[i]); break; case '+': previousIsANum = false; cout << "+" << endl; break; case '-': previousIsANum = false; cout << "-" << endl; break; case '*': previousIsANum = false; cout << "*" << endl; break; case '/': previousIsANum = false; cout << "/" << endl; break; default: break; } } char i = ' '; while (stack->ltopOfStack > 0){ stack->cmstackPop(i); output->cmstackPush(i); cout << i << endl; } return 0; } Here is the stack code (watch out!): #include <cstdio> #include <assert.h> #include <new.h> #include <stdlib.h> #include <iostream> class ctstack { private: long* lpstack ; // the stack itself long ltrue ; // constructor sets to 1 long lfalse ; // constructor sets to 0 // offset to top of the stack long lmaxEleInStack ; // maximum possible elements of stack public: long ltopOfStack ; ctstack ( long lnbrOfEleToAllocInStack ) { // Constructor lfalse = 0 ; // set to zero ltrue = 1 ; // set to one assert ( lnbrOfEleToAllocInStack > 0 ) ; // assure positive argument ltopOfStack = -1 ; // ltopOfStack is really an index lmaxEleInStack = lnbrOfEleToAllocInStack ; // set lmaxEleInStack to max ele lpstack = new long [ lmaxEleInStack ] ; // allocate stack assert ( lpstack ) ; // assure new succeeded } ~ctstack ( ) { // Destructor delete [ ] lpstack ; // Delete the stack itself } ctstack& operator= ( const ctstack& ctoriginStack) { // Assignment if ( this == &ctoriginStack ) // verify x not assigned to x return *this ; if ( this -> lmaxEleInStack < ctoriginStack . lmaxEleInStack ) { // if destination stack is smaller than delete [ ] this -> lpstack ; // original stack, delete dest and alloc this -> lpstack = // sufficient memory new long [ ctoriginStack . lmaxEleInStack ] ; assert ( this -> lpstack ) ; // assure new succeeded // reset stack size attribute this -> lmaxEleInStack = ctoriginStack . lmaxEleInStack ; } // copy original to destination stack for ( long i = 0 ; i < ctoriginStack . lmaxEleInStack ; i ++ ) *( this -> lpstack + i ) = *( ctoriginStack . lpstack + i ) ; this -> ltopOfStack = ctoriginStack . ltopOfStack ; // reset stack position attribute return *this ; } long cmstackPush (char lplaceInStack ) { // Push Method if ( ltopOfStack == lmaxEleInStack - 1 ) // stack is full can't add element return lfalse ; ltopOfStack ++ ; // acquire free slot *(lpstack + ltopOfStack ) = lplaceInStack ; // add element return ltrue ; // any number other than zero is true } long cmstackPop (char& lretrievedStackEle ) { // Pop Method if ( ltopOfStack < 0 ) { // stack has no elements lretrievedStackEle = -1 ; // dummy element return lfalse ; } lretrievedStackEle = *( lpstack + ltopOfStack ) ; // stack has element -- return it ltopOfStack -- ; // stack is pop'd return ltrue ; // any number other than zero is true } long cmstackLookAtTop (char& lretrievedStackEle ) { // Pop Method if ( ltopOfStack < 0 ) { // stack has no elements lretrievedStackEle = -1 ; // dummy element return lfalse ; } lretrievedStackEle = *( lpstack + ltopOfStack ) ; // stack has element -- return it return ltrue ; // any number other than zero is true } long cmstackHasAnEle (char& lretrievedTopOfStack ) { // Has element method lretrievedTopOfStack = ltopOfStack ; return ltopOfStack < 0 ? lfalse : ltrue ; // 0 - false stack does not have any ele } // 1 - true stack has at least one element long cmstackMaxNbrOfEle (char& lretrievedMaxStackEle ) { // Maximum element method lretrievedMaxStackEle = lmaxEleInStack ; // return stack size in reference var return ltrue ; // Return Maximum Size of Stack } } ; Thanks, Anthony.

    Read the article

  • Array: mathematical sequence

    - by VaioIsBorn
    An array of integers A[i] (i 1) is defined in the following way: an element A[k] ( k 1) is the smallest number greater than A[k-1] such that the sum of its digits is equal to the sum of the digits of the number 4* A[k-1] . You need to write a program that calculates the N th number in this array based on the given first element A[1] . INPUT: In one line of standard input there are two numbers seperated with a single space: A[1] (1 <= A[1] <= 100) and N (1 <= N <= 10000). OUTPUT: The standard output should only contain a single integer A[N] , the Nth number of the defined sequence. Input: 7 4 Output: 79 Explanation: Elements of the array are as follows: 7, 19, 49, 79... and the 4th element is solution. I tried solving this by coding a separate function that for a given number A[k] calculates the sum of it's digits and finds the smallest number greater than A[k-1] as it says in the problem, but with no success. The first testing failed because of a memory limit, the second testing failed because of a time limit, and now i don't have any possible idea how to solve this. One friend suggested recursion, but i don't know how to set that. Anyone who can help me in any way please write, also suggest some ideas about using recursion/DP for solving this problem. Thanks.

    Read the article

  • How to obtain dependency metrics from Java source code?

    - by Bram Schoenmakers
    For an assignment we have to extract some software metrics from the Hibernate project. We have to extract the afferent coupling and efferent coupling metrics (dependency fan-in, fan-out) from each revision of each package in Hibernate. Some tools were provided which are able to extract these metrics, such as ckjm and JDepend. Other tools I have checked were Sonar, javancss and AOP. There is also the Metrics Eclipse plugin which I didn't get to work either. What these tools have in common, as far as I can see, is that they all operate on bytecode (*.class files). This is a problem, because I have to build every revision from source in order to run, say, JDepend on it. Older revisions won't build because my development stack is too recent. What I would like to do is to do this kind of analysis on source files so that I don't have to build each revision. Is this possible? Or is there a good reason why all these tools only operate on bytecode?

    Read the article

  • Why isnt this returning the new string?

    - by Evan Kimia
    I have a recursive method that reversed a string (HW assignment, has to be recursive). I did it....but its only returning the value of the string after the first pass. By analyzing the output after each pass i can see it does do its job correctly. heres my code, and the output i get below it: String s = "Hello, I love you wont you tell me your name?"; int k=0; public String reverseThisString(String s) { if(k!=s.length()) { String first =s.substring(0,k)+s.charAt(s.length()-1); String end = ""+s.substring(k, s.length()-1); k++; s=first+end; System.out.println(s); this.reverseThisString(s); } return s; } output: ?Hello, I love you wont you tell me your name

    Read the article

  • Python-McNuggets problem

    - by challarao
    Hi! I am a student of IIIT.I am new to python.This question is one of the problems in my problem set.Please Help me writing program such as in what I should do it. Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 McNuggets, by finding solutions to the Diophantine equation. You can solve this in your head, using paper and pencil, or writing a program. However you chose to solve this problem, list the combinations of 6, 9 and 20 packs of McNuggets you need to buy in order to get each of the exact amounts. Given that it is possible to buy sets of 50, 51, 52, 53, 54 or 55 McNuggets by combinations of 6, 9 and 20 packs, show that it is possible to buy 56, 57,..., 65 McNuggets. In other words, show how, given solutions for 50-55, one can derive solutions for 56-65 6a + 9b + 20c = n

    Read the article

  • search a collection for a specific keyword

    - by icelated
    What i want to do is search a hashset with a keyword.. I have 3 classes... main() Library Item(CD, DVD,Book classes) In library i am trying to do my search of the items in the hashsets.. In Item class is where i have the getKeywords function.. here is the Items class... import java.io.PrintStream; import java.util.Collection; import java.util.*; class Item { private String title; private String [] keywords; public String toString() { String line1 = "title: " + title + "\n" + "keywords: " + Arrays.toString(keywords); return line1; } public void print() { System.out.println(toString()); } public Item() { } public Item(String theTitle, String... theKeyword) { this.title = theTitle; this.keywords = theKeyword; } public String getTitle() { return title; } public String [] getKeywords() { return keywords; } } class CD extends Item { private String artist; private String [] members; // private String [] keywords; private int number; public CD(String theTitle, String theBand, int Snumber, String... keywords) { super(theTitle, keywords); this.artist = theBand; this.number = Snumber; // this.keywords = keywords; } public void addband(String... member) { this.members = member; } public String getArtist() { return artist; } public String [] getMembers() { return members; } // public String [] getKeywords() // { // return keywords; //} public String toString() { return "-Music-" + "\n" + "band: " + artist + "\n" + "# songs: " + number + "\n" + "members: " + Arrays.toString(members) + "\n" + super.toString() // + "keywords: " + Arrays.toString(keywords) + "\n" + "\n" ; } public void print() { System.out.println(toString()); } } class DVD extends Item { private String director; private String [] cast; private int scenes; // private String [] keywords; public DVD(String theTitle, String theDirector, int nScenes, String... keywords) { super(theTitle, keywords); this.director = theDirector; this.scenes = nScenes; // this.keywords = keywords; } public void addmoviecast(String... members) { this.cast = members; } public String [] getCast() { return cast; } public String getDirector() { return director; } // public String [] getKeywords() // { // return keywords; // } public String toString() { return "-Movie-" + "\n" + "director: " + director + "\n" + "# scenes: " + scenes + "\n" + "cast: " + Arrays.toString(cast) + "\n" + super.toString() // + "keywords: " + Arrays.toString(keywords) + "\n" + "\n" ; } public void print() { System.out.println(toString()); } } class Book extends Item { private String author; private int pages; public Book(String theTitle, String theAuthor, int nPages, String... keywords) { super(theTitle, keywords); this.author = theAuthor; this.pages = nPages; // this.keywords = keywords; } public String getAuthor() { return author; } //public String [] getKeywords() // { // return keywords; //} public void print() { System.out.println(toString()); } public String toString() { return "-Book-" + "\n" + "Author: " + author + "\n" + "# pages " + pages + "\n" + super.toString() // + "keywords: " + Arrays.toString(keywords) + "\n" + "\n" ; } } I hope i didnt confuse you? I need help with the itemsForKeyword(String keyword) function.. the first keyword being passed in is "science fiction" and i want to search the keywords in the sets and return the matches.. What am i doing so wrong? Thank you

    Read the article

  • How can I write query to output this format in SQLite?

    - by GivenPie
    I would like to output in this format: e.EE_id e.FNAME e.LNAME SUPer_id s.FNAME s.LNAME --- --------- -------------- --- ------------- ------------------- 1 Ziqiao Li 2 Charlie Li 1 Ziqiao Li 3 George Pee 2 Charlie Li 4 Jason Dee 2 Charlie Li 5 Petey Wee 2 Charlie Li From this table created : I need to display the Primary key and foreign key in the same results while displaying the foreign key name values for the primary key names. Create table Employees( ee_id integer, fname varchar(20), lname varchar(20), super_id integer, Constraint emp_Pk Primary Key (ee_id), Constraint emp_Fk Foreign Key (super_id) references employees (ee_id) ); INSERT INTO Employees VALUES(1,'Charlie','Li',null); INSERT INTO Employees VALUES(2,'Ziqiao','Lee',1); INSERT INTO Employees VALUES(3,'George','Pee',2); INSERT INTO Employees VALUES(4,'Jason','Dee',2); INSERT INTO Employees VALUES(5,'Petey','Wee',2); Select ee_id, fname, lname, super_id from employees; ee_id fname lname super_id ---------- ---------- ---------- ---------- 1 Charlie Li 2 Ziqiao Lee 1 3 George Pee 2 4 Jason Dee 2 5 Petey Wee 2 Do I need to create a view?

    Read the article

  • adding nodes to a binary search tree randomly deletes nodes

    - by SDLFunTimes
    Hi, stack. I've got a binary tree of type TYPE (TYPE is a typedef of data*) that can add and remove elements. However for some reason certain values added will overwrite previous elements. Here's my code with examples of it inserting without overwriting elements and it not overwriting elements. the data I'm storing: struct data { int number; char *name; }; typedef struct data data; # ifndef TYPE # define TYPE data* # define TYPE_SIZE sizeof(data*) # endif The tree struct: struct Node { TYPE val; struct Node *left; struct Node *rght; }; struct BSTree { struct Node *root; int cnt; }; The comparator for the data. int compare(TYPE left, TYPE right) { int left_len; int right_len; int shortest_string; /* find longest string */ left_len = strlen(left->name); right_len = strlen(right->name); if(right_len < left_len) { shortest_string = right_len; } else { shortest_string = left_len; } /* compare strings */ if(strncmp(left->name, right->name, shortest_string) > 1) { return 1; } else if(strncmp(left->name, right->name, shortest_string) < 1) { return -1; } else { /* strings are equal */ if(left->number > right->number) { return 1; } else if(left->number < right->number) { return -1; } else { return 0; } } } And the add method struct Node* _addNode(struct Node* cur, TYPE val) { if(cur == NULL) { /* no root has been made */ cur = _createNode(val); return cur; } else { int cmp; cmp = compare(cur->val, val); if(cmp == -1) { /* go left */ if(cur->left == NULL) { printf("adding on left node val %d\n", cur->val->number); cur->left = _createNode(val); } else { return _addNode(cur->left, val); } } else if(cmp >= 0) { /* go right */ if(cur->rght == NULL) { printf("adding on right node val %d\n", cur->val->number); cur->rght = _createNode(val); } else { return _addNode(cur->rght, val); } } return cur; } } void addBSTree(struct BSTree *tree, TYPE val) { tree->root = _addNode(tree->root, val); tree->cnt++; } The function to print the tree: void printTree(struct Node *cur) { if (cur == 0) { printf("\n"); } else { printf("("); printTree(cur->left); printf(" %s, %d ", cur->val->name, cur->val->number); printTree(cur->rght); printf(")\n"); } } Here's an example of some data that will overwrite previous elements: struct BSTree myTree; struct data myData1, myData2, myData3; myData1.number = 5; myData1.name = "rooty"; myData2.number = 1; myData2.name = "lefty"; myData3.number = 10; myData3.name = "righty"; initBSTree(&myTree); addBSTree(&myTree, &myData1); addBSTree(&myTree, &myData2); addBSTree(&myTree, &myData3); printTree(myTree.root); Which will print: (( righty, 10 ) lefty, 1 ) Finally here's some test data that will go in the exact same spot as the previous data, but this time no data is overwritten: struct BSTree myTree; struct data myData1, myData2, myData3; myData1.number = 5; myData1.name = "i"; myData2.number = 5; myData2.name = "h"; myData3.number = 5; myData3.name = "j"; initBSTree(&myTree); addBSTree(&myTree, &myData1); addBSTree(&myTree, &myData2); addBSTree(&myTree, &myData3); printTree(myTree.root); Which prints: (( j, 5 ) i, 5 ( h, 5 ) ) Does anyone know what might be going wrong? Sorry if this post was kind of long.

    Read the article

  • How to spot empty parking spaces?

    - by mithila
    I want to do a final year B.Sc project on parking space detection. Can anybody give me some link related to it? Any text-book, tutorial or anything? What would be prerequisite for this project? What type of skills(programming/math) are needed? What are the initial steps to do? What type of readings(algorithms of image processing) are needed? Detail added in comments: i'm going to use camera, not infrared. i would like to use still images, or one camera which captures images from a parking lot. i think reak-time processing will be tough, at this moment i just need to start the project. so still images will work fine. but later it may b a real-time project

    Read the article

  • java recursion on array

    - by user69514
    I have to create a program that finds all the possible ways of filling a board of size 3xN You place a domino which takes up 2 spaces to completely fill the board. So far, this is my thought process on how it should be done based on what the teacher has said as well as my own thoughts. Get input and check if its even or odd If it's odd, the board can't be filled all the way and the program ends If it's even, place a domino horizontally in the top right corner of the board Test if you can place a domino vertically in that spot. Repeat those two steps as many times as possible. The problem is I don't know how to code it to the point where you can remember the placements of each domino. I can get it to where it fills the board completely once and maybe twice, but nothing past that. I also know that I'm supposed to use recursion to figure this out fwiw. Here is the code I started on so far. There is also a main method and I have the initial even/odd check working fine. This is the part I have no idea on. public void recurDomino(int row, int column) { if (Board[2][x - 1] != false) { } else if(Board[1][x-1]!=false) { } else { for (int n=0; n < x - 1; n++) { Board[row][column] = true; Board[row][column+1] = true; column++; counter++; } recurDomino(1, 0); recurDomino(2, 0); } } Thank you for any help you guys can give me.

    Read the article

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