Search Results

Search found 1553 results on 63 pages for 'tail recursion'.

Page 9/63 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Tail recursion in Erlang

    - by dagda1
    Hi, I am really struggling to understand tail recursion in Erlang. I have the following eunit test: db_write_many_test() -> Db = db:new(), Db1 = db:write(francesco, london, Db), Db2 = db:write(lelle, stockholm, Db1), ?assertEqual([{lelle, stockholm},{francesco, london}], Db2). And here is my implementation: -module(db) . -include_lib("eunit/include/eunit.hrl"). -export([new/0,write/3]). new() -> []. write(Key, Value, Database) -> Record = {Key, Value}, [Record|append(Database)]. append([H|T]) -> [H|append(T)]; append([]) -> []. Is my implementation tail recursive and if not, how can I make it so? Thanks in advance

    Read the article

  • Change a Recursive function that has a for loop in it into an iterative function?

    - by Bill
    So I have this function that I'm trying to convert from a recursive algorithm to an iterative algorithm. I'm not even sure if I have the right subproblems but this seems to determined what I need in the correct way, but recursion can't be used you need to use dynamic programming so I need to change it to iterative bottom up or top down dynamic programming. The basic recursive function looks like this: Recursion(i,j) { if(i>j) return 0; else { //This finds the maximum value for all possible subproblems and returns that for this problem for(int x = i; x < j; x++) { if(some subsection i to x plus recursion(x+1,j) is > current max) max = some subsection i to x plus recursion(x+1,j) } } } This is the general idea, but since recursions typically don't have for loops in them I'm not sure exactly how I would convert this to iterative. Does anyone have any ideas?

    Read the article

  • Python: Pickling highly-recursive objects without using `setrecursionlimit`

    - by cool-RR
    I've been getting RuntimeError: maximum recursion depth exceeded when trying to pickle a highly-recursive tree object. Much like this asker here. He solved his problem by setting the recursion limit higher with sys.setrecursionlimit. But I don't want to do that: I think that's more of a workaround than a solution. Because I want to be able to pickle my trees even if they have 10,000 nodes in them. (It currently fails at around 200.) (Also, every platform's true recursion limit is different, and I would really like to avoid opening this can of worms.) Is there any way to solve this at the fundamental level? If only the pickle module would pickle using a loop instead of recursion, I wouldn't have had this problem. Maybe someone has an idea how I can cause something like this to happen, without rewriting the pickle module? Any other idea how I can solve this problem will be appreciated.

    Read the article

  • Deep recursion in WHM EasyApache software update causes out of memory

    - by Ernest
    I was trying to load some modules with EasyApache in a software update (WHM) cause I need to install Magento ecommerce. I did the first EasyApache update. However, one module I needed was not loaded. I loaded later but whenever I check Tomcat 5.5 in the profile builder I get: -- Begin opt 'Tomcat' -- -- Begin dryrun test 'Checking for v5' -- -- End dryrun test 'Checking for v5' -- -- Begin step 'Checking jdk' -- Deep recursion on subroutine "Cpanel::CPAN::Digest::MD5::File::_dir" at /usr/local/cpanel/Cpanel/CPAN/Digest/MD5/File.pm line 107. Out of memory! Out of memory! *** glibc detected *** realloc(): invalid next size: 0x09741188 *** Line 107 in question in the file.pm is the third one in this snippet: if(-d $full) { $hr->{ $short } = ''; _dir($full, $hr, $base, $type, $cc) or return; //line 107 } All my client sites are down and I don't know what to do to fix this.

    Read the article

  • Sorting a list in OCaml

    - by darkie15
    Hi All, Here is the code on sorting any given list: let rec sort lst = match lst with [] -> [] | head :: tail -> insert head (sort tail) and insert elt lst = match lst with [] -> [elt] | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;; [Source: Code However, I am getting an Unbound error: Unbound value tail # let rec sort lst = match lst with [] -> [] | head :: tail -> insert head (sort tail) and insert elt lst = match lst with [] -> [elt] | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;; Characters 28-29: | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;; ^ Error: Syntax error Can anyone please help me understand the issue here?? I did not find head or tail to be predefined anywhere nor in the code

    Read the article

  • Implement Negascout Algorithm with stack

    - by Dan
    I'm not familiar with how these stack exchange accounts work so if this is double posting I apologize. I asked the same thing on stackoverflow. I have added an AI routine to a game I am working on using the Negascout algorithm. It works great, but when I set a higher maximum depth it can take a few seconds to complete. The problem is it blocks the main thread, and the framework I am using does not have a way to deal with multi-threading properly across platforms. So I am trying to change this routine from recursively calling itself, to just managing a stack (vector) so that I can progress through the routine at a controlled pace and not lock up the application while the AI is thinking. I am getting hung up on the second recursive call in the loop. It relies on a returned value from the first call, so I don't know how to add these to a stack. My Working c++ Recursive Code: MoveScore abNegascout(vector<vector<char> > &board, int ply, int alpha, int beta, char piece) { if (ply==mMaxPly) { return MoveScore(evaluation.evaluateBoard(board, piece, oppPiece)); } int currentScore; int bestScore = -INFINITY; MoveCoord bestMove; int adaptiveBeta = beta; vector<MoveCoord> moveList = evaluation.genPriorityMoves(board, piece, findValidMove(board, piece, false)); if (moveList.empty()) { return MoveScore(bestScore); } bestMove = moveList[0]; for(int i=0;i<moveList.size();i++) { MoveCoord move = moveList[i]; vector<vector<char> > newBoard; newBoard.insert( newBoard.end(), board.begin(), board.end() ); effectMove(newBoard, piece, move.getRow(), move.getCol()); // First Call ****** MoveScore current = abNegascout(newBoard, ply+1, -adaptiveBeta, -max(alpha,bestScore), oppPiece); currentScore = - current.getScore(); if (currentScore>bestScore){ if (adaptiveBeta == beta || ply>=(mMaxPly-2)){ bestScore = currentScore; bestMove = move; }else { // Second Call ****** current = abNegascout(newBoard, ply+1, -beta, -currentScore, oppPiece); bestScore = - current.getScore(); bestMove = move; } if(bestScore>=beta){ return MoveScore(bestMove,bestScore); } adaptiveBeta = max(alpha, bestScore) + 1; } } return MoveScore(bestMove,bestScore); } If someone can please help by explaining how to get this to work with a simple stack. Example code would be much appreciated. While c++ would be perfect, any language that demonstrates how would be great. Thank You.

    Read the article

  • Stack Overflow Error

    - by dylanisawesome1
    I recently created a recursive cave algorithm, and would like to have more extensive caves, but get a stack overflow after re-cursing a couple times. Any advice? Here's my code: for(int i=0;i<100;i++) { int rand = new Random().nextInt(100); if(rand<=20) { if(curtile.bounds.y-40>500+new Random().nextInt(20)) digDirection(Direction.UP); } if(rand<=40 && rand>20) { if(curtile.bounds.y+40<m.height) digDirection(Direction.DOWN); } if(rand<=60 && rand>40) { if(curtile.bounds.x-40>0) digDirection(Direction.LEFT); } if(rand<=80 && rand>60) { if(curtile.bounds.x+40<m.width) digDirection(Direction.RIGHT); } } } public void digDirection(Direction d) { if(new Random().nextInt(100)<=10) { new Miner(curtile, map); // try { // Thread.sleep(2); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } //Tried this to avoid stack overflow. Didn't work. }

    Read the article

  • Can a recursive function have iterations/loops?

    - by Omega
    I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function). However, while surfing the web for examples (the 8-queens-recursive problem), I found this function: private boolean placeQueen(int rows, int queens, int n) { boolean result = false; if (row < n) { while ((queens[row] < n - 1) && !result) { queens[row]++; if (verify(row,queens,n)) { ok = placeQueen(row + 1,queens,n); } } if (!result) { queens[row] = -1; } }else{ result = true; } return result; } There is a while loop involved. ... so I'm a bit lost now. Can I use loops or not?

    Read the article

  • Is this the right strategy to convert an in-level order binary tree to a doubly linked list?

    - by Ankit Soni
    So I recently came across this question - Make a function that converts a in-level-order binary tree into a doubly linked list. Apparently, it's a common interview question. This is the strategy I had - Simply do a pre-order traversal of the tree, and instead of returning a node, return a list of nodes, in the order in which you traverse them. i.e return a list, and append the current node to the list at each point. For the base case, return the node itself when you are at a leaf. so you would say left = recursive_function(node.left) right = recursive_function(node.right) return(left.append(node.data)).append(right);` Is this the right approach?

    Read the article

  • Searching for a key in a multi dimensional array and adding it to another array [migrated]

    - by Moha
    Let's say I have two multi dimensional arrays: array1 ( stuff1 = array ( data = 'abc' ) stuff2 = array ( something = '123' data = 'def' ) stuff3 = array ( stuff4 = array ( data = 'ghi' ) ) ) array2 ( stuff1 = array ( ) stuff3 = array ( anything = '456' ) ) What I want is to search the key 'data' in array1 and then insert the key and value to array2 regardless of the depth. So wherever key 'data' exists in array1 it gets added to array2 with the exact depth (and key names) as in array1 AND without modifying any other keys. How can I do this recursively?

    Read the article

  • generate parent child relation from the array to print a multi-level menu?

    - by Karthick Selvam
    How to get parent child relation from this array to print a multi-level menu $menus = array ( 0 => array ( 'id'=>0, 'check' => 1, 'display' =>'Arete Home', 'ordering' => -10, 'parent' => none, ), 1 => array ( 'id'=>1, 'check' => 1, 'display' => 'Submit Paper', 'ordering' => -10, 'parent' => 2, 'subordering' => -10, ), 2 => array ( 'id'=>2, 'check' => 1, 'display' => 'Buy Now', 'ordering' => -10, 'parent' => 1, 'subordering' => -10, ), 1461 => array ( 'id'=>1461, 'check' => 1, 'display' => 'Where are We?', 'ordering' => -10, 'parent' => 2, 'subordering' => -10, ), 1463 => array ( 'id'=>1463, 'check' => 1, 'display' =>' About Me?', 'ordering' => -10, 'parent' => 2, 'subordering' => -10, ), 1464 => array ( 'id'=>1464, 'check' => 1, 'display' => 'About You?', 'ordering' => -10, 'parent' => 2, 'subordering' => -10, ), 1465 => array ( 'id'=>1465, 'check' => 1, 'display' => 'About who?', 'ordering' => -10, 'parent' => 1, 'subordering' => -10, ), ); code sample: foreach($menus as $id=>$values) { $values['parent']=isset($values['parent']) ? $values['parent'] : 0; $menus[$values['parent']]['childs'][$id]=$values; unset($menus[$id]); } foreach($menus as $id1=>$value2) { $value2['parent']=isset($value2['parent']) ? $value2['parent'] : 0; $menus[$value2['parent']]['childs'][$id1]=$value2; unset($menus[$id1]); }

    Read the article

  • Getting the relational table data into XML recursively

    - by Tom
    I have levels of tables (Level1, Level2, Level3, ...) For simplicity, we'll say I have 3 levels. The rows in the higher level tables are parents of lower level table rows. The relationship does not skip levels however. E.g. Row1Level1 is parent of Row3Level2, Row2Level2 is parent of Row4Level3. Level(n-1)'s parent is always be in Level(n). Given these tables with data, I need to come up with a recursive function that generates an XML file to represent the relationship and the data. E.g. <data> <level levelid = 1 rowid=1> <level levelid = 2 rowid=3 /> </level> <level levelid = 2 rowid=2> <level levelid = 3 rowid=4 /> </level> </data> I would like help with coming up with a pseudo-code for this setup. This is what I have so far: XElement GetXMLData(Table table, string identifier, XElement data) { XElement xmlData = data; if (table != null) { foreach (row in the table) { // Get subordinate table Table subordinateTable = GetSubordinateTable(table); // Get the XML Data for the children of current row xmlData += GetXMLData(subordinateTable, row.Identifier, xmlData); } } return xmlData; }

    Read the article

  • Trace code pascal [on hold]

    - by mghaffari
    I haven't worked with Pascal so far, and my problem is understanding the recursive aspects that prm assignment operators and how the final (correct) value is derived. Would someone please explain that line for me. Program test(output); FUNCTION prm(az:integer) : real; begin if az = 1 then prm := sqrt(12) else prm := sqrt(12*prm(az-1)); end; begin writeln(prm(30):0:2); end.

    Read the article

  • PHP - "tabulate" array - make levels from elements

    - by Moha
    If I have an array like this: Array ( [0] => field_schools [1] => und [2] => 0 [3] => field_school [4] => und [5] => 0 [6] => value ) How can I make an array like this from it? array ( [field_schools] => array ( [und] => array ( [0] => array ( [field_school] => array ( [und] => array ( [0] => array ( [value] => something ) ) ) ) ) ) ) I want to specify the 'value' myself.

    Read the article

  • SUM of metric for normalized logical hierarchy

    - by Alex254
    Suppose there's a following table Table1, describing parent-child relationship and metric: Parent | Child | Metric (of a child) ------------------------------------ name0 | name1 | a name0 | name2 | b name1 | name3 | c name2 | name4 | d name2 | name5 | e name3 | name6 | f Characteristics: 1) Child always has 1 and only 1 parent; 2) Parent can have multiple children (name2 has name4 and name5 as children); 3) Number of levels in this "hierarchy" and number of children for any given parent are arbitrary and do not depend on each other; I need SQL request that will return result set with each name and a sum of metric of all its descendants down to the bottom level plus itself, so for this example table the result would be (look carefully at name1): Name | Metric ------------------ name1 | a + c + f name2 | b + d + e name3 | c + f name4 | d name5 | e name6 | f (name0 is irrelevant and can be excluded). It should be ANSI or Teradata SQL. I got as far as a recursive query that can return a SUM (metric) of all descendants of a given name: WITH RECURSIVE temp_table (Child, metric) AS ( SELECT root.Child, root.metric FROM table1 root WHERE root.Child = 'name1' UNION ALL SELECT indirect.Child, indirect.metric FROM temp_table direct, table1 indirect WHERE direct.Child = indirect.Parent) SELECT SUM(metric) FROM temp_table; Is there a way to turn this query into a function that takes name as an argument and returns this sum, so it can be called like this? SELECT Sum_Of_Descendants (Child) FROM Table1; Any suggestions about how to approach this from a different angle would be appreciated as well, because even if the above way is implementable, it will be of poor performance - there would be a lot of iterations of reading metrics (value f would be read 3 times in this example). Ideally, the query should read a metric of each name only once.

    Read the article

  • Problem inserting pre-ordered values to quadtree

    - by Lucas Corrêa Feijó
    There's this string containing B, W and G (standing for black, white and gray). It defines the pre-ordered path of the quadtree I want to build. I wrote this method for filling the QuadTree class I also wrote but it doesn't work, it inserts correctly until it reaches a point in the algorithm it needs to "return". I use math quadrants convention order for insertion, such as northeast, northwest, southwest and southeast. A quadtree has all it's leafs black or white and all the other nodes gray The node used in the tree is called Node4T and has a char as data and 4 references to other nodes like itself, called, respectively NE, NW, SW, SE. public void insert(char val) { if(root==null) { root = new Node4T(val); } else { insert(root, val); } } public void insert(Node4T n, char c) { if(n.data=='G') // possible to insert { if(n.NE==null) { n.NE = new Node4T(c); return; } else { insert(n.NE,c); } if(n.NW==null) { n.NW = new Node4T(c); return; } else { insert(n.NW,c); } if(n.SW==null) { n.SW = new Node4T(c); return; } else { insert(n.SW,c); } if(n.SE==null) { n.SE = new Node4T(c); return; } else { insert(n.SE,c); } } else // impossible to insert { } } The input "GWGGWBWBGBWBWGWBWBWGGWBWBWGWBWBGBWBWGWWWB" is given a char at a time to the insert method and then the print method is called, pre-ordered, and the result is "GWGGWBWBWBWGWBWBW". How do I make it import the string correctly? Ignore the string reading process, suppose the method is called and it has to do it's job.

    Read the article

  • Using Python to traverse a parent-child data set

    - by user132748
    I have a dataset of two columns in a csv file. Th purpose of this dataset is to provide a linking between two different id's if they belong to the same person. e.g (2,3,5 belong to 1) e.g COLA COLB 1 2 ; 1 3 ; 1 5 ; 2 6 ; 3 7 ; 9 10 In the above example 1 is linked to 2,3,5 and 2 is the linked to 6 and 3 is linked to 7. What I am trying to achieve is to identify all records which are linked to 1 directly (2,3,5) or indirectly(6,7) and be able to say that these id's in column B belong to same person in column A and then either dedupe or add a new column to the output file which will have 1 populated for all rows that link to 1 e.g of expected output colA colB GroupField 1 2 1; 1 3 1; 1 5 1 ; 2 6 1 ;3 7 1; 9 10 9; 10 11 9 I am a newbie and so am not sure on how to approach this problem.Appreciate any inputs you'll can provide.

    Read the article

  • How to determine if a 3D voxel-based room is sealed, efficiently

    - by NigelMan1010
    I've been having some issues with efficiently determining if large rooms are sealed in a voxel-based 3D rooms. I'm at a point where I have tried my hardest to solve the problem without asking for help, but not tried enough to give up, so I'm asking for help. To clarify, sealed being that there are no holes in the room. There are oxygen sealers, which check if the room is sealed, and seal depending on the oxygen input level. Right now, this is how I'm doing it: Starting at the block above the sealer tile (the vent is on the sealer's top face), recursively loop through in all 6 adjacent directions If the adjacent tile is a full, non-vacuum tile, continue through the loop If the adjacent tile is not full, or is a vacuum tile, check if it's adjacent blocks are, recursively. Each time a tile is checked, decrement a counter If the count hits zero, if the last block is adjacent to a vacuum tile, return that the area is unsealed If the count hits zero and the last block is not a vacuum tile, or the recursive loop ends (no vacuum tiles left) before the counter is zero, the area is sealed If the area is not sealed, run the loop again with some changes: Checking adjacent blocks for "breathable air" tile instead of a vacuum tile Instead of using a decrementing counter, continue until no adjacent "breathable air" tiles are found. Once loop is finished, set each checked block to a vacuum tile. Here's the code I'm using: http://pastebin.com/NimyKncC The problem: I'm running this check every 3 seconds, sometimes a sealer will have to loop through hundreds of blocks, and a large world with many oxygen sealers, these multiple recursive loops every few seconds can be very hard on the CPU. I was wondering if anyone with more experience with optimization can give me a hand, or at least point me in the right direction. Thanks a bunch.

    Read the article

  • Storing hierarchical template into a database

    - by pduersteler
    If this title is ambiguous, feel free to change it, I don't know how to put this in a one-liner. Example: Let's assume you have a html template which contains some custom tags, like <text_field />. We now create a page based on a template containing more of those custom tags. When a user wants to edit the page, he sees a text field. he can input things and save it. This looks fairly easy to set up. You either have something like a template_positions table which stores the content of those fields. Case: I now have a bit of a blockade keeping things as simple as possible. Assume you have the same tag given in your example, and additionally, <layout> and <repeat> tags. Here's an example how they should be used: <repeat> <layout name="image-left"> <image /> <text_field /> </layout> <layout name="image-right"> <text_field /> <image /> </layout> </repeat> We now have a block which can be repeated, obviously. This means: when creting/editing a page containing such a template block, I can choose between a layout image-left and image-right which then gets inserted as content element (where content for <image /> and <text_field /> gets stored). And because this is inside a <repeat>, content elements from the given layouts can be inserted multiple times. How do you store this? Simply said, this could be stored with the same setup I've wrote in the example above, I just need to add a parent_id or something similiar to maintain a hierarchy. but I think I am missing something. At least the relation between an inserted content element and the origin/insertion point is missing. And what happens when I update the template file? Do I have to give every custom tag that acts as editable part of a template an identifier that matches an identifier in the template to substitue them correctly? Or can you think of a clean solution that might be better?

    Read the article

  • Java 8 Stream, getting head and tail

    - by lyomi
    Java 8 introduced a Stream class that resembles Scala's Stream, a powerful lazy construct using which it is possible to do something like this very concisely: def from(n: Int): Stream[Int] = n #:: from(n+1) def sieve(s: Stream[Int]): Stream[Int] = { s.head #:: sieve(s.tail filter (_ % s.head != 0)) } val primes = sieve(from(2)) primes takeWhile(_ < 1000) print // prints all primes less than 1000 I wondered if it is possible to do this in Java 8, so I wrote something like this: IntStream from(int n) { return IntStream.iterate(n, m -> m + 1); } IntStream sieve(IntStream s) { int head = s.findFirst().getAsInt(); return IntStream.concat(IntStream.of(head), sieve(s.skip(1).filter(n -> n % head != 0))); } IntStream primes = sieve(from(2)); PrimitiveIterator.OfInt it = primes.iterator(); for (int prime = it.nextInt(); prime < 1000; prime = it.nextInt()) { System.out.println(prime); } Fairly simple, but it produces java.lang.IllegalStateException: stream has already been operated upon or closed because both findFirst() and skip() is a terminal operation on Stream which can be done only once. I don't really have to use up the stream twice since all I need is the first number in the stream and the rest as another stream, i.e. equivalent of Scala's Stream.head and Stream.tail. Is there a method in Java 8 Stream that I can achieve this? Thanks.

    Read the article

  • A F# tail-recursive question

    - by ksharp
    Recently, I'm learning F#. I try to solve problem in different ways. Like this: (* [0;1;2;3;4;5;6;7;8] -> [(0,1,2);(3,4,5);(6,7,8)] *) //head-recursive let rec toTriplet_v1 list= match list with | a::b::c::t -> (a,b,c)::(toTriplet_v1 t) | _ -> [] //tail-recursive let toTriplet_v2 list= let rec loop lst acc= match lst with | a::b::c::t -> loop t ((a,b,c)::acc) | _ -> acc loop list [] //tail-recursive(???) let toTriplet_v3 list= let rec loop lst accfun= match lst with | a::b::c::t -> loop t (fun ls -> accfun ((a,b,c)::ls)) | _ -> accfun [] loop list (fun x -> x) let funs = [toTriplet_v1; toTriplet_v2; toTriplet_v3]; funs |> List.map (fun x -> x [0..8]) |> List.iteri (fun i x -> printfn "V%d : %A" (i+1) x) I thought the results of V2 and V3 should be the same. But, I get the result below: V1 : [(0, 1, 2); (3, 4, 5); (6, 7, 8)] V2 : [(6, 7, 8); (3, 4, 5); (0, 1, 2)] V3 : [(0, 1, 2); (3, 4, 5); (6, 7, 8)] Why the results of V2 and V3 are different?

    Read the article

  • Recursive function with for loop python

    - by user134743
    I have a question that should not be too hard but it has been bugging me for a long time. I am trying to write a function that searches in a directory that has different folders for all files that have the extension jpg and which size is bigger than 0. It then should print the sum of the size of the files that are in these categories. What I am doing right now is def myFuntion(myPath, fileSize): for myfile in glob.glob(myPath): if os.path.isdir(myFile): myFunction(myFile, fileSize) if (fnmatch.fnmatch(myFile, '*.jpg')): if (os.path.getsize(myFile) > 1): fileSize = fileSize + os.path.getsize(myFile) print "totalSize: " + str(fileSize) THis is not giving me the right result. It sums the sizes of the files of one directory but it does not keep suming the rest. For example if I have these paths C:/trial/trial1/trial11/pic.jpg C:/trial/trial1/trial11/pic1.jpg C:/trial/trial1/trial11/pic2.jpg and C:/trial/trial2/trial11/pic.jpg C:/trial/trial2/trial11/pic1.jpg C:/trial/trial2/trial11/pic2.jpg I will get the sum of the first three and the the size of the last 3 but I won´t get the size of the 6 together, if that makes sense. Thank you so much for your help!

    Read the article

  • pascal triangle in php (anything wrong with this solution?) [migrated]

    - by zhenka
    I saw that one of the interview questions could be building a pascal triangle. Is there anything wrong with this particular solution I came up with? function pascal_r($r){ $local = array(); if($r == 1){ return array(array(1)); } else { $previous = pascal_r($r - 1); array_push($local, 1); for($i = 0; $i < $r - 2 && $r > 2; $i++){ array_push($local, $previous[$r-2][$i] + $previous[$r-2][$i + 1]); } array_push($local, 1); } array_push($previous, $local); return $previous; } print_r(pascal_r(100));

    Read the article

  • Doubly linked lists

    - by user1642677
    I have an assignment that I am terribly lost on involving doubly linked lists (note, we are supposed to create it from scratch, not using built-in API's). The program is supposed to keep track of credit cards basically. My professor wants us to use doubly-linked lists to accomplish this. The problem is, the book does not go into detail on the subject (doesn't even show pseudo code involving doubly linked lists), it merely describes what a doubly linked list is and then talks with pictures and no code in a small paragraph. But anyway, I'm done complaining. I understand perfectly well how to create a node class and how it works. The problem is how do I use the nodes to create the list? Here is what I have so far. public class CardInfo { private String name; private String cardVendor; private String dateOpened; private double lastBalance; private int accountStatus; private final int MAX_NAME_LENGTH = 25; private final int MAX_VENDOR_LENGTH = 15; CardInfo() { } CardInfo(String n, String v, String d, double b, int s) { setName(n); setCardVendor(v); setDateOpened(d); setLastBalance(b); setAccountStatus(s); } public String getName() { return name; } public String getCardVendor() { return cardVendor; } public String getDateOpened() { return dateOpened; } public double getLastBalance() { return lastBalance; } public int getAccountStatus() { return accountStatus; } public void setName(String n) { if (n.length() > MAX_NAME_LENGTH) throw new IllegalArgumentException("Too Many Characters"); else name = n; } public void setCardVendor(String v) { if (v.length() > MAX_VENDOR_LENGTH) throw new IllegalArgumentException("Too Many Characters"); else cardVendor = v; } public void setDateOpened(String d) { dateOpened = d; } public void setLastBalance(double b) { lastBalance = b; } public void setAccountStatus(int s) { accountStatus = s; } public String toString() { return String.format("%-25s %-15s $%-s %-s %-s", name, cardVendor, lastBalance, dateOpened, accountStatus); } } public class CardInfoNode { CardInfo thisCard; CardInfoNode next; CardInfoNode prev; CardInfoNode() { } public void setCardInfo(CardInfo info) { thisCard.setName(info.getName()); thisCard.setCardVendor(info.getCardVendor()); thisCard.setLastBalance(info.getLastBalance()); thisCard.setDateOpened(info.getDateOpened()); thisCard.setAccountStatus(info.getAccountStatus()); } public CardInfo getInfo() { return thisCard; } public void setNext(CardInfoNode node) { next = node; } public void setPrev(CardInfoNode node) { prev = node; } public CardInfoNode getNext() { return next; } public CardInfoNode getPrev() { return prev; } } public class CardList { CardInfoNode head; CardInfoNode current; CardInfoNode tail; CardList() { head = current = tail = null; } public void insertCardInfo(CardInfo info) { if(head == null) { head = new CardInfoNode(); head.setCardInfo(info); head.setNext(tail); tail.setPrev(node) // here lies the problem. tail must be set to something // to make it doubly-linked. but tail is null since it's // and end point of the list. } } } Here is the assignment itself if it helps to clarify what is required and more importantly, the parts I'm not understanding. Thanks https://docs.google.com/open?id=0B3vVwsO0eQRaQlRSZG95eXlPcVE

    Read the article

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