Search Results

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

Page 15/63 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Calculate shortest path through a grocery store

    - by Bart
    Hi, I'm trying to find a way to find the shortest path through a grocery store, visiting a list of locations (shopping list). The path should start at a specified startposition and can end at multiple endpositions (there are multiple checkout counters). Also, I have some predefined constraints on the path, such as "item x on the shopping list needs to be the last, second last, or third last item on the path". There is a function that will return true or false for a given path. Finally, this needs to be calculated with limited cpu power (on a smartphone) and within a second or so. If this isn't possible, then an approximation to the optimal path is also ok. Is this possible? So far I think I need to start by calculating the distance between every item on the list using something like A* or Dijkstra's. After that, should I treat it like the travelling salesman problem? Because in my problem there is a specified startnode, specified endnodes, and some constraints, which are not in the travelling salesman problem. Any help would be appreciated :)

    Read the article

  • Creating my own Stack

    - by Malaken
    I am creating my own stack for my data structures class. For our assignment we are using the assignment to convert a real-time infix equation into a postfix equation. I thought my program: took input determines if it was digit or number(operand) prints it out determines if input is operator (+,-,/,*) adds to stack or prints out, depending on stack precedence Instead it prints out the operands as expect, but I get this error when I enter an operator .../dorun.sh line 33: 4136 Segmentation fault sh "$" [code] #include using namespace std; class DishWell{ public: char ReturnEnd(){ return Well.back(); } void Push(char x){ Well.push_back(x); } void Pop(){ Well.pop_back(); } bool IsEmpty(){ return Well.empty(); } private: vector<char> Well; }; #include <iostream> bool Precidence(char Input, char Stack){ int InputPrecidence,StackPrecidence; switch (Input){ case '*': InputPrecidence = 4; break; case '/': InputPrecidence = 4; break; case '+': InputPrecidence = 3; break; case '-': InputPrecidence = 3; break; case '(': InputPrecidence = 2; break; default: InputPrecidence = 0; } switch (Stack){ case '*': StackPrecidence = 4; break; case '/': StackPrecidence = 4; break; case '+': StackPrecidence = 3; break; case '-': StackPrecidence = 3; break; case '(': StackPrecidence = 2; break; default: StackPrecidence = 0; } if(InputPrecidence>StackPrecidence) return true; else return false; } int main(int argc, char** argv) { DishWell DishTray; char Input; bool InputFlag; InputFlag = true; while(InputFlag){ cin>>Input; if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))|| (Input>='0'&&Input<='9')))//If Digit or Number cout<<Input; if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand if(Precidence(Input,DishTray.ReturnEnd())) DishTray.Push(Input); else if(!Precidence(Input,DishTray.ReturnEnd())) cout<<Input; } else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))|| (Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand InputFlag = false; } while(!DishTray.IsEmpty()){ cout<<DishTray.ReturnEnd(); DishTray.Pop(); } return 0; [code] My code is very length, I know, but I appreciate help. Especially any times for efficency or future coding. Thanks again P.S. Dr. Zemoudeh, this is your student Macaire

    Read the article

  • Some more multitasking java issues

    - by owca
    I had a task to write simple game simulating two players picking up 1-3 matches one after another until the pile is gone. I managed to do it for computer choosing random value of matches but now I'd like to go further and allow humans to play the game. Here's what I already have : http://paste.pocoo.org/show/200660/ Class Player is a computer player, and PlayerMan should be human being. Problem is, that thread of PlayerMan should wait until proper value of matches is given but I cannot make it work this way. When I type the values it sometimes catches them and decrease amount of matches but that's not exactly what I was up to :) Logics is : I check the value of current player. If it corresponds to this of the thread currently active I use scanner to catch the amount of matches. Else I wait one second (I know it's kinda harsh solution, but I have no other idea how to do it). Class Shared keeps the value of current player, and also amount of matches. By the way, is there any way I can make Player and Shared attributes private instead of public and still make the code work ? CONSOLE and INPUT-DIALOG is just for choosing way of inserting values. class PlayerMan extends Player{ static final int CONSOLE=0; static final int INPUT_DIALOG=1; private int input; public PlayerMan(String name, Shared data, int c){ super(name, data); input = c; } @Override public void run(){ Scanner scanner = new Scanner(System.in); int n = 0; System.out.println("Matches on table: "+data.matchesAmount); System.out.println("which: "+data.which); System.out.println("number: "+number); while(data.matchesAmount != 0){ if(number == data.which){ System.out.println("Choose amount of matches (from 1 to 3): "); n = scanner.nextInt(); if(data.matchesAmount == 1){ System.out.println("There's only 1 match left !"); while(n != 1){ n = scanner.nextInt(); } } else{ do{ n = scanner.nextInt(); } while(n <= 1 && n >= 3); } data.matchesAmount = data.matchesAmount - n; System.out.println(" "+ name+" takes "+n+" matches."); if(number != 0){ data.which = 0; } else{ data.which = 1; } } else{ try { Thread.sleep(1000); } catch(InterruptedException exc) { System.out.println("End of thread."); return; } } System.out.println("Matches on table: "+data.matchesAmount); } if(data.matchesAmount == 0){ System.out.println("Winner is player: "+name); stop(); } } }

    Read the article

  • Java textfile I/O problem

    - by KáGé
    Hello, I have to make a torpedo game for school with a toplist for it. I want to store it in a folder structure near the JAR: /Torpedo/local/toplist/top_i.dat, where the i is the place of that score. The files will be created at the first start of the program with this call: File f; f = new File(Toplist.toplistPath+"/top_1.dat"); if(!f.exists()){ Toplist.makeToplist(); } Here is the toplist class: package main; import java.awt.Color; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.prefs.Preferences; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; public class Toplist { static String toplistPath = "./Torpedo/local/toplist"; //I know it won't work this easily, it's only to get you the idea public static JFrame toplistWindow = new JFrame("Torpedó - [TOPLISTA]"); public static JTextArea toplist = new JTextArea(""); static StringBuffer toplistData = new StringBuffer(3000); public Toplist() { toplistWindow.setSize(500, 400); toplistWindow.setLocationRelativeTo(null); toplistWindow.setResizable(false); getToplist(); toplist.setSize(400, 400); toplist.setLocation(0, 100); toplist.setColumns(5); toplist.setText(toplistData.toString()); toplist.setEditable(false); toplist.setBackground(Color.WHITE); toplistWindow.setLayout(null); toplistWindow.setVisible(true); } public Toplist(Player winner) { //this is to be done yet, this will set the toplist at first and then display it toplistWindow.setLayout(null); toplistWindow.setVisible(true); } /** * Creates a new toplist */ public static void makeToplist(){ new File(toplistPath).mkdir(); for(int i = 1; i <= 10; i++){ File f = new File(toplistPath+"/top_"+i+".dat"); try { f.createNewFile(); } catch (IOException e) { JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista létrehozása", "Error", JOptionPane.ERROR_MESSAGE); } } } /** * If the score is a top score it inserts it into the list * * @param score - the score to be checked */ public static void setToplist(int score, Player winner){ BufferedReader input = null; PrintWriter output = null; int topscore; for(int i = 1; i <= 10; i++){ try { input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+",dat")); String s; topscore = Integer.parseInt(input.readLine()); if(score > topscore){ for(int j = 9; j >= i; j--){ input = new BufferedReader(new FileReader(toplistPath+"/top_"+j+".dat")); output = new PrintWriter(new FileWriter(toplistPath+"/top_"+(j+1)+".dat")); while ((s = input.readLine()) != null) { output.println(s); } } output = new PrintWriter(new FileWriter(toplistPath+"/top_"+i+".dat")); output.println(score); output.println(winner.name); if(winner.isLocal){ output.println(Torpedo.session.remote.name); }else{ output.println(Torpedo.session.remote.name); } output.println(Torpedo.session.mapName); output.println(DateUtils.now()); break; } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE); } finally { if (input != null) { try { input.close(); } catch (IOException e) { JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE); } } if (output != null) { output.close(); } } } } /** * This loads the toplist into the buffer */ public static void getToplist(){ BufferedReader input = null; toplistData = null; String s; for(int i = 1; i <= 10; i++){ try { input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+".dat")); while((s = input.readLine()) != null){ toplistData.append(s); toplistData.append('\t'); } toplistData.append('\n'); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE); } } } /** * * @author http://www.rgagnon.com/javadetails/java-0106.html * */ public static class DateUtils { public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; public static String now() { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); return sdf.format(cal.getTime()); } } } The problem is, that it can't access any of the files. I've tried adding them to the classpath and at least six different variations of file/path handling I found online but nothing worked. Could anyone tell me what do I do wrong? Thank you.

    Read the article

  • manuplating matrix operation(transpose, negation, addition, and mutipication) using functions in c

    - by user292489
    i was trying to manuplate matrices in my input file using functions. my input file is, A 3 3 1 2 3 4 5 6 7 8 9 B 3 3 1 0 0 0 1 0 0 0 1 C 2 3 3 5 8 -1 -2 -3 D 3 5 0 0 0 1 0 1 0 1 0 1 0 1 0 0 1 E 1 1 10 F 3 10 1 0 2 0 3 0 4 0 5 0 0 2 3 -1 -3 -4 -3 8 3 7 0 0 0 4 6 5 8 2 -1 10 i am having trouble in impementing the funcitons that i declared. i assumed my program will perform those operations: transpose, negate, add, and mutiply matices according to the users choise: /* once this program is compliled and excuted, it will perform the basic matrix operations: negation, transpose,a\ ddition, and multiplication. */ #include <stdio.h> #include <stdlib.h> #define MAX 10 int readmatrix(FILE *input, char martixname[6],int , mat[10][10], int i, int j); void printmatrix(char matrixname[6], int mat[10][10], int i, int j); void Negate(char matrixname[6], int mat[10][10], int i, int j); void add(char matrixname[6], int mat[10][10],int i, int k); void multiply(char matrixname[], int mat[][10], char A[], int i, int k); void transpose (char matrixname[], int mat[][10], char A[], int); void printT(int mat[][10], int); int selctoption(); char selectmatrix(); int main(int argc, char *argv[]) { char matrixtype[6]; int mat[][10]; FILE *filein; int size; int optionop; int matrixop; int option; if (argc != 2) { printf("Usage: excutable input.\n"); exit (0); } filein = fopen(argv[1], "r"); if (!filein) { printf("ERROR: input file not found.\n"); exit (0); } size = readmatrix (filein, matrixtype); printmatrix(matrix[][10], size); option = selectoption(); matrixtype = selectmatrix(); //printf("You have: %5.2f ", deposit); optionop = readmatrix(option, matrix[][10], size); if (choiceop == 6) { printf("Thanks for using the matrix operation program.\n"); exit(0); } printf("Please select from the following matrix operations:\n") printf("\t1. Print matrix\n"); printf("\t2. Negate matrix\n"); printf("\t3. Transpose matrix\n"); printf("\t4. Add matrices\n"); printf("\t5. Multiply matrices\n"); printf("\t6. Quit\n"); fclose(filein); return 0; } do { printf("Please select option(1-%d):", optionop); scanf("%d", &matrixop); }while(matrixop <= 0 || matrixop > optionop); void readmatrix (FILE *in, int mat[][10], char A[], int i, int j) { int i=0,j = 0; while (fscanf(in, "%d", &mat[i][j]) != EOF) return 0; } // i would apprtaite anyones feedback. //thank you!

    Read the article

  • C code autocomplete in Eclipse

    - by Ittai
    Hi, I'm a Java developer and I've downloaded the Eclipse for C (course purposes) and to my amazement the control+space shortcut (for autocomplete) did not work. I've created a new project and a new class using the wizzards and started to type "print" and then tried to find an autocomplete feature. After a bit of googling I arrived at C/C++-Editor-Content Assist-Advanced and there I verified that Help proposals,Parsing-based proposals and Template proposals options were checked. I then went over to the Keys preferences page using the link at that page and entered a binding for all relevant content assist from before C\C++ Content Assist (type...) and chose in the When box the C\C++ Editor option. But alas no autocompletion was offered. Can someone please point me to the right direction? Thanks, Ittai

    Read the article

  • Attempting to convert an if statement to assembly

    - by Malfist
    What am I doing wrong? This is the assmebly I've written: char encode(char plain){ __asm{ mov al, plain ;check for y or z status cmp al, 'y' je YorZ cmp al, 'z' je YorZ cmp al, 'Y' je YorZ cmp al, 'Z' je YorZ ;check to make sure it is in the alphabet now mov cl, al sub cl, 'A' cmp cl, 24 jl Other sub cl, '6' ;there are six characters between 'Z' and 'a' cmp cl, 24 jl Other jmp done ;means it is not in the alphabet YorZ: sub al, 24 jmp done Other: add al, 2 jmp done done: leave ret } } and this is the C code it's supposed to replace, but doesn't char encode(char plain){ char code; if((plain>='a' && plain<='x') || (plain>='A' && plain <='X')){ code = plain+2; }else if(plain == 'y' || plain=='z' || plain=='Y' || plain == 'y'){ code = plain - 24; }else{ code = plain; } return code; } It seems to convert every character that isn't an y,z,Y,Z into a plus 2 equivalent instead of just A-Xa-x. Any ideas why?

    Read the article

  • How to embed html table into the bpdy of email

    - by Michael Mao
    Hi all: I am sending info to target email via PHP native mail() method right now. Everything else works fine but the table part troubles me the most. See sample output : Dear Michael Mao : Thank you for purchasing flight tickets with us, here is your receipt : Your tickets will be delivered by mail to the following address : Street Address 1 : sdfsdafsadf sdf Street Address 2 : N/A City : Sydney State : nsw Postcode : 2 Country : Australia Credit Card Number : *************1234 Your purchase details are recorded as : <table><tr><th class="delete">del?</th><th class="from_city">from</th><th class="to_city">to</th><th class="quantity">qty</th><th class="price">unit price</th><th class="price">total price</th></tr><tr class="evenrow" id="Sydney-Lima"><td><input name="isDeleting" type="checkbox"></td><td>Sydney</td><td>Lima</td><td>1</td><td>1030.00</td><td>1030</td></tr><tr class="oddrow" id="Sydney-Perth"><td><input name="isDeleting" type="checkbox"></td><td>Sydney</td><td>Perth</td><td>3</td><td>340.00</td><td>1020</td></tr><tr class="totalprice"><td colspan="5">Grand Total Price</td><td id="grandtotal">2050</td></tr></table> The source of table is directly taken from a webpage, exactly as the same. However, Gmail, Hotmail and most of other emails will ignore to render this as a table. So I am wondering, without using Outlook or other email sending agent software, how could I craft a embedded table for the PHP mail() method to send? Current code snippet corresponds to table generation : $purchaseinfo = $_POST["purchaseinfo"]; //if html tags are not to be filtered in the body of email $stringBuilder .= "<table>" .stripslashes($purchaseinfo) ."</table>"; //must send json response back to caller ajax request if(mail($email, 'Your purchase information on www.hardlyworldtravel.com', $emailbody, $headers)) echo json_encode(array("feedback"=>"successful")); else echo json_encode(array("feedback"=>"error")); Any hints and suggestions are welcomed, thanks a lot in advance.

    Read the article

  • How to judge the relative efficiency of algorithms given runtimes as functions of 'n'?

    - by Lopa
    Consider two algorithms A and B which solve the same problem, and have time complexities (in terms of the number of elementary operations they perform) given respectively by a(n) = 9n+6 b(n) = 2(n^2)+1 (i) Which algorithm is the best asymptotically? (ii) Which is the best for small input sizes n, and for what values of n is this the case? (You may assume where necessary that n0.) i think its 9n+6. guys could you please help me with whether its right or wrong?? and whats the answer for part b. what exactly do they want?

    Read the article

  • array of structs in C

    - by Hristo
    I'm trying to create an array of structs and also a pointer to that array. I don't know how large the array is going to be, so it should be dynamic. My struct would look something like this: typedef struct _stats_t { int hours[24]; int numPostsInHour; int days[7]; int numPostsInDay; int weeks[20]; int numPostsInWeek; int totNumLinesInPosts; int numPostsAnalyzed; } stats_t; ... and I need to have multiple of these structs for each file (unknown amount) that I will analyze. I'm not sure how to do this. I don't like the following approach because of the limit of the size of the array: # define MAX 10 typedef struct _stats_t { int hours[24]; int numPostsInHour; int days[7]; int numPostsInDay; int weeks[20]; int numPostsInWeek; int totNumLinesInPosts; int numPostsAnalyzed; } stats_t[MAX]; So how would I create this array? Also, would a pointer to this array would look something this? stats_t stats[]; stats_t *statsPtr = &stats[0]; Thanks, Hristo

    Read the article

  • trying to find a web service

    - by sbsp
    i am trying to find a web service that allows a user to send a company name (or better still will return a list of all company names, thus allowing the user to select one) and then get the share price, this will then feed in to another api - yahoo currency converter to work out the price of the share the issue i am having is that i cannot find a web service to get share info, google registration for theres does not seem to be working and as such i dont no what to do i am to be coding this in php if anyone could point me to a good web service i would appreciate it thanks edit : i did find this but am unsure if it is appropriate http://www.xignite.com/xGlobalQuotes.asmx?WSDL

    Read the article

  • C++ question on prime numbers.

    - by user278330
    Hello. I am trying to make a program that determines if the number is prime or composite. I have gotten thus far. Could you give me any ideas so that it will work? All primes will , however, because composites have values that are both r0 and r==0, they will always be classified as prime. How can I fix this? int main() { int pNumber, limit, x, r; limit = 0; x = 2; cout << "Please enter any positive integer: " ; cin >> pNumber; if (pNumber < 0) { cout << "Invalid. Negative Number. " << endl; return 0; } else if (pNumber == 0) { cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl; return 0; } else if (pNumber == 1) { cout << "Valid. However, one is neither prime nor composite" << endl; return 0; } else { while (limit < pNumber) { r = pNumber % x; x++; limit++; } if (r == 0) cout << "Your number is composite" << endl; else cout << "Your number is prime" << endl; } return 0; }

    Read the article

  • C++ question on prime numbers.

    - by user278330
    Hello. I am trying to make a program that determines if the number is prime or composite. I have gotten thus far. Could you give me any ideas so that it will work? All primes will , however, because composites have values that are both r0 and r==0, they will always be classified as prime. How can I fix this? int main() { int pNumber, limit, x, r; limit = 0; x = 2; cout << "Please enter any positive integer: " ; cin >> pNumber; if (pNumber < 0) { cout << "Invalid. Negative Number. " << endl; return 0; } else if (pNumber == 0) { cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl; return 0; } else if (pNumber == 1) { cout << "Valid. However, one is neither prime nor composite" << endl; return 0; } else { while (limit < pNumber) { r = pNumber % x; x++; limit++; } if (r == 0) cout << "Your number is composite" << endl; else cout << "Your number is prime" << endl; } return 0; }

    Read the article

  • Why is this an invalid Turing machine?

    - by Danny King
    Whilst doing exam revision I am having trouble answering the following question from the book, "An Introduction to the Theory of Computation" by Sipser. Unfortunately there's no solution to this question in the book. Explain why the following is not a legitimate Turing machine. M = { The input is a polynomial p over variables x1, ..., xn Try all possible settings of x1, ..., xn to integer values Evaluate p on all of these settings If any of these settings evaluates to 0, accept; otherwise reject. } This is driving me crazy! I suspect it is because the set of integers is infinite? Does this somehow exceed the alphabet's allowable size? Thanks!

    Read the article

  • read file in C++

    - by Amm Sokun
    I am trying to read a list of words from a file in C++. However, the last word is read twice. I cannot understand why it is so. Can someone help me out? int main () { ifstream fin, finn; vector<string> vin; vector<string> typo; string word; fin.open("F:\\coursework\\pz\\gattaca\\breathanalyzer\\file.in"); if (!fin.is_open()) cout<<"Not open\n"; while (fin) { fin >> word; cout<<word<<endl; vin.push_back(word); } fin.close(); }

    Read the article

  • Lock-Free, Wait-Free and Wait-freedom algorithms for non-blocking multi-thread synchronization.

    - by GJ
    In multi thread programming we can find different terms for data transfer synchronization between two or more threads/tasks. When exactly we can say that some algorithem is: 1)Lock-Free 2)Wait-Free 3)Wait-Freedom I understand what means Lock-free but when we can say that some synchronization algorithm is Wait-Free or Wait-Freedom? I have made some code (ring buffer) for multi-thread synchronization and it use Lock-Free methods but: 1) Algorithm predicts maximum execution time of this routine. 2) Therad which call this routine at beginning set unique reference, what mean that is inside of this routine. 3) Other threads which are calling the same routine check this reference and if is set than count the CPU tick count (measure time) of first involved thread. If that time is to long interrupt the current work of involved thread and overrides him job. 4) Thread which not finished job because was interrupted from task scheduler (is reposed) at the end check the reference if not belongs to him repeat the job again. So this algorithm is not really Lock-free but there is no memory lock in use, and other involved threads can wait (or not) certain time before overide the job of reposed thread. Added RingBuffer.InsertLeft function: function TgjRingBuffer.InsertLeft(const link: pointer): integer; var AtStartReference: cardinal; CPUTimeStamp : int64; CurrentLeft : pointer; CurrentReference: cardinal; NewLeft : PReferencedPtr; Reference : cardinal; label TryAgain; begin Reference := GetThreadId + 1; //Reference.bit0 := 1 with rbRingBuffer^ do begin TryAgain: //Set Left.Reference with respect to all other cores :) CPUTimeStamp := GetCPUTimeStamp + LoopTicks; AtStartReference := Left.Reference OR 1; //Reference.bit0 := 1 repeat CurrentReference := Left.Reference; until (CurrentReference AND 1 = 0)or (GetCPUTimeStamp - CPUTimeStamp > 0); //No threads present in ring buffer or current thread timeout if ((CurrentReference AND 1 <> 0) and (AtStartReference <> CurrentReference)) or not CAS32(CurrentReference, Reference, Left.Reference) then goto TryAgain; //Calculate RingBuffer NewLeft address CurrentLeft := Left.Link; NewLeft := pointer(cardinal(CurrentLeft) - SizeOf(TReferencedPtr)); if cardinal(NewLeft) < cardinal(@Buffer) then NewLeft := EndBuffer; //Calcolate distance result := integer(Right.Link) - Integer(NewLeft); //Check buffer full if result = 0 then //Clear Reference if task still own reference if CAS32(Reference, 0, Left.Reference) then Exit else goto TryAgain; //Set NewLeft.Reference NewLeft^.Reference := Reference; SFence; //Try to set link and try to exchange NewLeft and clear Reference if task own reference if (Reference <> Left.Reference) or not CAS64(NewLeft^.Link, Reference, link, Reference, NewLeft^) or not CAS64(CurrentLeft, Reference, NewLeft, 0, Left) then goto TryAgain; //Calcolate result if result < 0 then result := Length - integer(cardinal(not Result) div SizeOf(TReferencedPtr)) else result := cardinal(result) div SizeOf(TReferencedPtr); end; //with end; { TgjRingBuffer.InsertLeft } RingBuffer unit you can find here: RingBuffer, CAS functions: FockFreePrimitives, and test program: RingBufferFlowTest Thanks in advance, GJ

    Read the article

  • How web browser works ?

    - by Anil Namde
    I have tired to find good documentation of browsers using google but failed to get what i am looking for. Can some one guide me to location where i can actually see how browser functions. The whole purpose of the exercise is to get answers for following queries and more like these.... How images, css and js files are downloaded How js is executed How Ajax request is executed and many more like these..... Thanks all,

    Read the article

  • Basic Recursion, Check Balanced Parenthesis

    - by pws5068
    Greetings all, I've written software in the past that uses a stack to check for balanced equations, but now I'm asked to write a similar algorithm recursively to check for properly nested brackets and parenthesis. Good examples: () [] () ([]()[]) Bad examples: ( (] ([)] Suppose my function is called: isBalanced. Should each pass evaluate a smaller substring (until reaching a base case of 2 left)? Or, should I always evaluate the full string and move indices inward?

    Read the article

  • Implementing union of Set using basic java array

    - by lupindeterd
    Note: This is an assignment. Hi, Continuing with my Set implementation using Java basic array, I'm now struggling with the 3 to last function namely the union. import java.io.*; class Set { private int numberOfElements = 0; private String[] setElements = new String[5]; private int maxNumberOfElements = 5; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { int numberOfElements = numberOfE; String[] setElements = new String[setE]; int maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newtemparray = new String[x.getLength]; newtemparray = x.getMember; return x; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(1,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element six is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); setA.printSet(); Set setB = new Set(0,10,10); Set SetA = setA.union(setB,setA); } } Ok the method in question will be the implementation of union. As such this: Set union(Set x, Set y) { String[] newtemparray = new String[x.getLength]; newtemparray = x.getMember; return x; } I got this error: symbol : variable getLength location: class Set String[] newtemparray = new String[x.getLength]; ^ d:\javaprojects\Set.java:122: cannot find symbol symbol : variable getMember location: class Set newtemparray = x.getMember; ^ 2 errors My approach for union would be: *) create temporary array of string with size of the object x length. *) store object x members to temporary array by looping the object and calling the getMember *) loop object y members and check if element exist against temporary array. *) discard if it exist/add if it is not there *) return obj x with the union array. thanks, lupin

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >