Search Results

Search found 4490 results on 180 pages for 'binary trees'.

Page 7/180 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Finding the heaviest length-constrained path in a weighted Binary Tree

    - by Hristo
    UPDATE I worked out an algorithm that I think runs in O(n*k) running time. Below is the pseudo-code: routine heaviestKPath( T, k ) // create 2D matrix with n rows and k columns with each element = -8 // we make it size k+1 because the 0th column must be all 0s for a later // function to work properly and simplicity in our algorithm matrix = new array[ T.getVertexCount() ][ k + 1 ] (-8); // set all elements in the first column of this matrix = 0 matrix[ n ][ 0 ] = 0; // fill our matrix by traversing the tree traverseToFillMatrix( T.root, k ); // consider a path that would arc over a node globalMaxWeight = -8; findArcs( T.root, k ); return globalMaxWeight end routine // node = the current node; k = the path length; node.lc = node’s left child; // node.rc = node’s right child; node.idx = node’s index (row) in the matrix; // node.lc.wt/node.rc.wt = weight of the edge to left/right child; routine traverseToFillMatrix( node, k ) if (node == null) return; traverseToFillMatrix(node.lc, k ); // recurse left traverseToFillMatrix(node.rc, k ); // recurse right // in the case that a left/right child doesn’t exist, or both, // let’s assume the code is smart enough to handle these cases matrix[ node.idx ][ 1 ] = max( node.lc.wt, node.rc.wt ); for i = 2 to k { // max returns the heavier of the 2 paths matrix[node.idx][i] = max( matrix[node.lc.idx][i-1] + node.lc.wt, matrix[node.rc.idx][i-1] + node.rc.wt); } end routine // node = the current node, k = the path length routine findArcs( node, k ) if (node == null) return; nodeMax = matrix[node.idx][k]; longPath = path[node.idx][k]; i = 1; j = k-1; while ( i+j == k AND i < k ) { left = node.lc.wt + matrix[node.lc.idx][i-1]; right = node.rc.wt + matrix[node.rc.idx][j-1]; if ( left + right > nodeMax ) { nodeMax = left + right; } i++; j--; } // if this node’s max weight is larger than the global max weight, update if ( globalMaxWeight < nodeMax ) { globalMaxWeight = nodeMax; } findArcs( node.lc, k ); // recurse left findArcs( node.rc, k ); // recurse right end routine Let me know what you think. Feedback is welcome. I think have come up with two naive algorithms that find the heaviest length-constrained path in a weighted Binary Tree. Firstly, the description of the algorithm is as follows: given an n-vertex Binary Tree with weighted edges and some value k, find the heaviest path of length k. For both algorithms, I'll need a reference to all vertices so I'll just do a simple traversal of the Tree to have a reference to all vertices, with each vertex having a reference to its left, right, and parent nodes in the tree. Algorithm 1 For this algorithm, I'm basically planning on running DFS from each node in the Tree, with consideration to the fixed path length. In addition, since the path I'm looking for has the potential of going from left subtree to root to right subtree, I will have to consider 3 choices at each node. But this will result in a O(n*3^k) algorithm and I don't like that. Algorithm 2 I'm essentially thinking about using a modified version of Dijkstra's Algorithm in order to consider a fixed path length. Since I'm looking for heaviest and Dijkstra's Algorithm finds the lightest, I'm planning on negating all edge weights before starting the traversal. Actually... this doesn't make sense since I'd have to run Dijkstra's on each node and that doesn't seem very efficient much better than the above algorithm. So I guess my main questions are several. Firstly, do the algorithms I've described above solve the problem at hand? I'm not totally certain the Dijkstra's version will work as Dijkstra's is meant for positive edge values. Now, I am sure there exist more clever/efficient algorithms for this... what is a better algorithm? I've read about "Using spine decompositions to efficiently solve the length-constrained heaviest path problem for trees" but that is really complicated and I don't understand it at all. Are there other algorithms that tackle this problem, maybe not as efficiently as spine decomposition but easier to understand? Thanks.

    Read the article

  • C++ : Lack of Standardization at the Binary Level

    - by Nawaz
    Why ISO/ANSI didn't standardize C++ at the binary level? There are many portability issues with C++, which is only because of lack of it's standardization at the binary level. Don Box writes, (quoting from his book Essential COM, chapter COM As A Better C++) C++ and Portability Once the decision is made to distribute a C++ class as a DLL, one is faced with one of the fundamental weaknesses of C++, that is, lack of standardization at the binary level. Although the ISO/ANSI C++ Draft Working Paper attempts to codify which programs will compile and what the semantic effects of running them will be, it makes no attempt to standardize the binary runtime model of C++. The first time this problem will become evident is when a client tries to link against the FastString DLL's import library from a C++ developement environment other than the one used to build the FastString DLL. Are there more benefits Or loss of this lack of binary standardization?

    Read the article

  • C++ : Lack of Standardization at the Binary Level

    - by Nawaz
    Why ISO/ANSI didn't standardize C++ at the binary level? There are many portability issues with C++, which is only because of lack of it's standardization at the binary level. Don Box writes, (quoting from his book Essential COM, chapter COM As A Better C++) C++ and Portability Once the decision is made to distribute a C++ class as a DLL, one is faced with one of the fundamental weaknesses of C++, that is, lack of standardization at the binary level. Although the ISO/ANSI C++ Draft Working Paper attempts to codify which programs will compile and what the semantic effects of running them will be, it makes no attempt to standardize the binary runtime model of C++. The first time this problem will become evident is when a client tries to link against the FastString DLL's import library from a C++ developement environment other than the one used to build the FastString DLL. Are there more benefits Or loss of this lack of binary standardization?

    Read the article

  • Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket - (TOTD #185)

    - by arungupta
    The WebSocket API defines different send(xxx) methods that can be used to send text and binary data. This Tip Of The Day (TOTD) will show how to send and receive text and binary data using WebSocket. TOTD #183 explains how to get started with a WebSocket endpoint using GlassFish 4. A simple endpoint from that blog looks like: @WebSocketEndpoint("/endpoint") public class MyEndpoint { public void receiveTextMessage(String message) { . . . } } A message with the first parameter of the type String is invoked when a text payload is received. The payload of the incoming WebSocket frame is mapped to this first parameter. An optional second parameter, Session, can be specified to map to the "other end" of this conversation. For example: public void receiveTextMessage(String message, Session session) {     . . . } The return type is void and that means no response is returned to the client that invoked this endpoint. A response may be returned to the client in two different ways. First, set the return type to the expected type, such as: public String receiveTextMessage(String message) { String response = . . . . . . return response; } In this case a text payload is returned back to the invoking endpoint. The second way to send a response back is to use the mapped session to send response using one of the sendXXX methods in Session, when and if needed. public void receiveTextMessage(String message, Session session) {     . . .     RemoteEndpoint remote = session.getRemote();     remote.sendString(...);     . . .     remote.sendString(...);    . . .    remote.sendString(...); } This shows how duplex and asynchronous communication between the two endpoints can be achieved. This can be used to define different message exchange patterns between the client and server. The WebSocket client can send the message as: websocket.send(myTextField.value); where myTextField is a text field in the web page. Binary payload in the incoming WebSocket frame can be received if ByteBuffer is used as the first parameter of the method signature. The endpoint method signature in that case would look like: public void receiveBinaryMessage(ByteBuffer message) {     . . . } From the client side, the binary data can be sent using Blob, ArrayBuffer, and ArrayBufferView. Blob is a just raw data and the actual interpretation is left to the application. ArrayBuffer and ArrayBufferView are defined in the TypedArray specification and are designed to send binary data using WebSocket. In short, ArrayBuffer is a fixed-length binary buffer with no format and no mechanism for accessing its contents. These buffers are manipulated using one of the views defined by one of the subclasses of ArrayBufferView listed below: Int8Array (signed 8-bit integer or char) Uint8Array (unsigned 8-bit integer or unsigned char) Int16Array (signed 16-bit integer or short) Uint16Array (unsigned 16-bit integer or unsigned short) Int32Array (signed 32-bit integer or int) Uint32Array (unsigned 16-bit integer or unsigned int) Float32Array (signed 32-bit float or float) Float64Array (signed 64-bit float or double) WebSocket can send binary data using ArrayBuffer with a view defined by a subclass of ArrayBufferView or a subclass of ArrayBufferView itself. The WebSocket client can send the message using Blob as: blob = new Blob([myField2.value]);websocket.send(blob); where myField2 is a text field in the web page. The WebSocket client can send the message using ArrayBuffer as: var buffer = new ArrayBuffer(10);var bytes = new Uint8Array(buffer);for (var i=0; i<bytes.length; i++) { bytes[i] = i;}websocket.send(buffer); A concrete implementation of receiving the binary message may look like: @WebSocketMessagepublic void echoBinary(ByteBuffer data, Session session) throws IOException {    System.out.println("echoBinary: " + data);    for (byte b : data.array()) {        System.out.print(b);    }    session.getRemote().sendBytes(data);} This method is just printing the binary data for verification but you may actually be storing it in a database or converting to an image or something more meaningful. Be aware of TYRUS-51 if you are trying to send binary data from server to client using method return type. Here are some references for you: JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) TOTD #183 - Getting Started with WebSocket in GlassFish TOTD #184 - Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark Subsequent blogs will discuss the following topics (not necessary in that order) ... Error handling Custom payloads using encoder/decoder Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API

    Read the article

  • Using recursion to to trim a binary tree based on a given min and max value

    - by Justin
    As the title says, I have to trim a binary tree based on a given min and max value. Each node stores a value, and a left/right node. I may define private helper methods to solve this problem, but otherwise I may not call any other methods of the class nor create any data structures such as arrays, lists, etc. An example would look like this: overallRoot _____[50]____________________ / \ __________[38] _______________[90] / \ / _[14] [42] [54]_____ / \ \ [8] [20] [72] \ / \ [26] [61] [83] trim(52, 65); should return: overallRoot [54] \ [61] My attempted solution has three methods: public void trim(int min, int max) { rootFinder(overallRoot, min, max); } First recursive method finds the new root perfectly. private void rootFinder(IntTreeNode node, int min, int max) { if (node == null) return; if (overallRoot.data < min) { node = overallRoot = node.right; rootFinder(node, min, max); } else if (overallRoot.data > max) { node = overallRoot = node.left; rootFinder(node, min, max); } else cutter(overallRoot, min, max); } This second method should eliminate any further nodes not within the min/max, but it doesn't work as I would hope. private void cutter(IntTreeNode node, int min, int max) { if (node == null) return; if (node.data <= min) { node.left = null; } if (node.data >= max) { node.right = null; } if (node.data < min) { node = node.right; } if (node.data > max) { node = node.left; } cutter(node.left, min, max); cutter(node.right, min, max); } This returns: overallRoot [54]_____ \ [72] / [61] Any help is appreciated. Feel free to ask for further explanation as needed.

    Read the article

  • Java Binary Tree. Priting InOrder traversal

    - by user69514
    I am having some problems printing an inOrder traversal of my binary tree. Even after inserting many items into the tree it's only printing 3 items. public class BinaryTree { private TreeNode root; private int size; public BinaryTree(){ this.size = 0; } public boolean insert(TreeNode node){ if( root == null) root = node; else{ TreeNode parent = null; TreeNode current = root; while( current != null){ if( node.getData().getValue().compareTo(current.getData().getValue()) <0){ parent = current; current = current.getLeft(); } else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){ parent = current; current = current.getRight(); } else return false; if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0) parent.setLeft(node); else parent.setRight(node); } } size++; return true; } /** * */ public void inOrder(){ inOrder(root); } private void inOrder(TreeNode root){ if( root.getLeft() !=null) this.inOrder(root.getLeft()); System.out.println(root.getData().getValue()); if( root.getRight() != null) this.inOrder(root.getRight()); } }

    Read the article

  • Getting zeros between data while reading a binary file in C

    - by indiajoe
    I have a binary data which I am reading into an array of long integers using a C programme. hexdump of the binary data shows, that after first few data points , it starts again at a location 20000 hexa adresses away. hexdump output is as shown below. 0000000 0000 0000 0000 0000 0000 0000 0000 0000 * 0020000 0000 0000 0053 0000 0064 0000 006b 0000 0020010 0066 0000 0068 0000 0066 0000 005d 0000 0020020 0087 0000 0059 0000 0062 0000 0066 0000 ........ and so on... But when I read it into an array 'data' of long integers. by the typical fread command fread(data,sizeof(*data),filelength/sizeof(*data),fd); It is filling up with all zeros in my data array till it reaches the 20000 location. After that it reads in data correctly. Why is it reading regions where my file is not there? Or how will I make it read only my file, not anything inbetween which are not in file? I know it looks like a trivial problem, but I cannot figure it out even after googling one night.. Can anyone suggest me where I am doing it wrong? Other Info : I am working on a gnu/linux machine. (slax-atma distro to be specific) My C compiler is gcc.

    Read the article

  • A deque based on binary trees

    - by Greg Ros
    This is a simple immutable deque based on binary trees. What do you think about it? Does this kind of data structure, or possibly an improvement thereof, seem useful? How could I improve it, preferably without getting rid of its strengths? (Not in the sense of more operations, in the sense of different design) Does this sort of thing have a name? Red nodes are newly instantiated; blue ones are reused. Nodes aren't actually red or anything, it's just for emphasis.

    Read the article

  • Dynamic Quad/Oct Trees

    - by KKlouzal
    I've recently discovered the power of Quadtrees and Octrees and their role in culling/LOD applications, however I've been pondering on the implementations for a Dynamic Quad/Oct Tree. Such tree would not require a complete rebuild when some of the underlying data changes (Vertex Data). Would it be possible to create such a tree? What would that look like? Could someone point me in the correct direction to get started? The application here would, in my scenario, be used for a dynamically changing spherical landscape with over 10,000,000 verticies. The use of Quad/Oct Trees is obvious for Culling & LOD as well as the benefits from not having to completely recompute the tree when the underlying data changes.

    Read the article

  • C++ print out a binary search tree

    - by starcorn
    Hello, Got nothing better to do this Christmas holiday, so I decided to try out making a binary search tree. I'm stuck with the print function. How should the logic behind it work? Since the tree is already inserting it in a somewhat sorted order, and I want to print the tree from smallest values to the biggest. So I need to travel to the furthest left branch of the tree to print the first value. Right, so after that how do I remember the way back up, do I need to save the previous node? A search in wikipedia gave me an solution which they used stack. And other solutions I couldn't quite understand how they've made it, so I'm asking here instead hoping someone can enlight me. I also wonder my insert function is OK. I've seen other's solution being smaller. void treenode::insert(int i) { if(root == 0) { cout << "root" << endl; root = new node(i,root); } else { node* travel = root; node* prev; while(travel) { if(travel->value > i) { cout << "travel left" << endl; prev = travel; travel = travel->left; } else { cout << "travel right" << endl; prev = travel; travel = travel->right; } } //insert if(prev->value > i) { cout << "left" << endl; prev->left = new node(i); } else { cout << "right" << endl; prev->right = new node(i); } } } void treenode::print() { node* travel = root; while(travel) { cout << travel->value << endl; travel = travel->left; } }

    Read the article

  • How to determine if binary tree is balanced?

    - by user69514
    It's been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I'm working on binary trees now, and I was wondering what would be the best way to determine if the tree is height-balanced. I was thinking of something along this: public boolean isBalanced(Node root){ if(root==null){ return true; //tree is empty } else{ int lh = root.left.height(); int rh = root.right.height(); if(lh - rh > 1 || rh - lh > 1){ return false; } } return true; } Is this a good implementation? or am I missing something?

    Read the article

  • C syntax or binary optimized syntax?

    - by Dpp
    Let's take an simple example of two lines supposedly doing the same thing: if (value = 96 || value < 0) ... or if (value & ~ 95) ... Say 'If's are costly in a loop of thousands of iterations, is it better to keep with the traditional C syntax or better to find a binary optimized one if possible?

    Read the article

  • C# TCP socket and binary data

    - by MD
    Hi @All How to send binary data (01110110 for exemple) with C# throught a TCP (using SSL) socket ? I'm using : SslStream.Write() and h[0] = (byte)Convert.ToByte("01110110"); isn't working Thanks.

    Read the article

  • convert a binary file in a list (python)

    - by beratch
    Hi all, I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ? Thanks !

    Read the article

  • Write binary stream to browser using PHP

    - by Dave Jarvis
    Background Trying to stream a PDF report written using iReport through PHP to the browser. The general problem is: how do you write binary data to the browser using PHP? Working Code The following code does the job, but (for many reasons) it is not as efficient as it should be (the code writes a file then sends the file contents the browser). // Load the MySQL database driver. // java( 'java.lang.Class' )->forName( 'com.mysql.jdbc.Driver' ); // Attempt a database connection. // $conn = java( 'java.sql.DriverManager' )->getConnection( "jdbc:mysql://localhost:3306/climate?user=$user&password=$password" ); // Extract parameters. // $params = new java('java.util.HashMap'); $params->put('DistrictCode', '101'); $params->put('StationCode', '0066'); $params->put('CategoryCode', '010'); // Use the fill manager to produce the report. // $fm = java('net.sf.jasperreports.engine.JasperFillManager'); $pm = $fm->fillReport($report, $params, $conn); header('Cache-Control: no-cache private'); header('Content-Description: File Transfer'); header('Content-Disposition: attachment, filename=climate-report.pdf'); header('Content-Type: application/pdf'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . strlen( $result ) ); $path = realpath( "." ) . "/output.pdf"; $em = java('net.sf.jasperreports.engine.JasperExportManager'); $result = $em->exportReportToPdfFile($pm,$path); readfile( $path ); $conn->close(); Non-working Code To remove the slight redundancy (i.e., write directly to the browser), the following code looks like it should work, but it does not: $em = java('net.sf.jasperreports.engine.JasperExportManager'); $result = $em->exportReportToPdf($pm); header('Content-Length: ' . strlen( $result ) ); echo $result; Content is sent to the browser, but the file is corrupt (it begins with the PDF header) and cannot be read by any PDF reader. Question How can I take out the middle step of writing to the file and write directly to the browser so that the PDF is not corrupted? Thank you!

    Read the article

  • reading binary datafile and writing into decimal no file

    - by swaroop b banerjee
    exp data is generated by my mc scaler card as a binary file with first 511 bytes as header and then 24 bit data followed by four bit roi data. i am not a expert in programming. i do understand a little. I would like to convert this file into a file (without header) decimal nos with first col as channel no (1 to 8191) then the data (24 bit) then the Roi data (4 bit). I am looking for source code in c or qbasic. thanks

    Read the article

  • Free-as-in-beer binary file format inspector

    - by fbrereto
    I am looking for a utility that gives me the ability to specify a binary file format and then interpret a file of bytes according to that format. (Something along the lines of the 010 Editor, but infinitely more cost-effective). Something that runs on Mac OS X would be preferred, but I'm interested to see what all is out there in general (while more of a hassle I'd be willing to run a tool on Windows if it were superior.) What's your preference?

    Read the article

  • Binary to Date (C#) 64 Bit Format

    - by Veskechky
    We have a binary file from which we have identified the following dates (as Int64). We now the following facts about the Date/Time format; The 64 bit Date has a resolution to the microsecond The 64 bit Date has a range of 4095 years The Int64 9053167636875050944 (0x7DA34FFFFFFFFFC0) = 9th March 2010 The Int64 9053176432968073152 (0x7DA357FFFFFFFFC0) = 10th March 2010 The Int64 9053185229061095360 (0x7DA35FFFFFFFFFC0) = 11th March 2010 The Int64 9053194025154117568 (0x7DA367FFFFFFFFC0) = 12th March 2010 Any help on figuring out a way to convert this to a valid C# Date/Time is appreciated.

    Read the article

  • Convert 64bit Binary to Long equivalent

    - by washtik
    How can we convert the following 64 bit binary into the long equivalent; 01111101 10100011 01001111 11111111 11111111 11111111 11111111 11000000 equals 7D A3 4F FF FF FF FF C0 HEX equals 9053167636875050944 << this is the value we want in a C# variable

    Read the article

  • C++ exceptions binary compatibility

    - by aaa
    hi. my project uses 2 different C++ compilers, g++ and nvcc (cuda compiler). I have noticed exception thrown from nvcc object files are not caught in g++ object files. are C++ exceptions supposed to be binary compatible in the same machine? what can cause such behavior?

    Read the article

  • Binary file reading problem

    - by ScReYm0
    Ok i have problem with my code for reading binary file... First i will show you my writing code: void book_saving(char *file_name, struct BOOK *current) { FILE *out; BOOK buf; out = fopen(file_name, "wb"); if(out != NULL) { printf_s("Writting to file..."); do { if(current != NULL) { strcpy(buf.catalog_number, current->catalog_number); strcpy(buf.author, current->author); buf.price = current->price; strcpy(buf.publisher, current->publisher); strcpy(buf.title, current->title); buf.price = current->year_published; fwrite(&buf, sizeof(BOOK), 1, out); } current = current->next; }while(current != NULL); printf_s("Done!\n"); fclose(out); } } and here is my "version" for reading it back: int book_open(struct BOOK *current, char *file_name) { FILE *in; BOOK buf; BOOK *vnext; int count; int i; in = fopen("west", "rb"); printf_s("Reading database from %s...", file_name); if(!in) { printf_s("\nERROR!"); return 1; } i = fread(&buf,sizeof(BOOK), 1, in); while(!feof(in)) { if(current != NULL) { current = malloc(sizeof(BOOK)); current->next = NULL; } strcpy(current->catalog_number, buf.catalog_number); strcpy(current->title, buf.title); strcpy(current->publisher, buf.publisher); current->price = buf.price; current->year_published = buf.year_published; fread(&buf, 1, sizeof(BOOK), in); while(current->next != NULL) current = current->next; fclose(in); } printf_s("Done!"); return 0; } I just need to save my linked list in binary file and to be able to read it back ... please help me. The program just don't read it or its crash every time different situation ...

    Read the article

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