Search Results

Search found 20065 results on 803 pages for 'practice problems'.

Page 58/803 | < Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >

  • Should I expect my peers to read or practice on a regular basis? [closed]

    - by Joshua Smith
    I've been debating asking this question for some time. Based several of the comments I read in this question I decided I had to ask. This feels like I'm stating the obvious, but I believe that regular reading (of books, blogs, StackOverflow, whatever) and/or practice are required just to stay current (let alone excel) in whichever stack you use to pay the bills, not to mention playing with things outside your comfort zone to learn new ways of doing things. Yet, I virtually never see this from many of my peers. Even when I go out of my way to point out useful (and almost always free) learning material, I quite often get a sense of total apathy from those I'm speaking to. I'd even go so far as to say that if someone doesn't try to improve (or at least stay current), they'll atrophy as technology advances and actually become less useful to the company. I don't expect people to spend hours a day studying or practicing. I have two young kids and hours of practice simply aren't feasible. Still, I find some time; perhaps on the train, at lunch, in bed for a few minutes, whatever. I'm willing to believe this is arrogance or naivete on my part, but I'd like to hear what the community has to say. So here's my question: Should I expect (and encourage) the same from my peers, or just keep my mouth shut and do my own thing?

    Read the article

  • Best Practice: What can be the hashCode() method implementation if custom field used in equals() method are null?

    - by goodspeed
    What is the best practice to return a value for hashCode() method if custom field used in equals are null ? I have a situation, where equals() override is implemented using custom fields. Usually it it is better to override hashCode() also using that custom fields used in equals(). But if all the custom fields used in equals() are null, then what would be the best implementation for hashCode()? Example: class Person { private String firstName; private String lastName; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } @Override public boolean equals(Object object) { boolean result = false; if (object == null || object.getClass() != getClass()) { result = false; } else { Person person = (Person) object; if (this.firstName == person.getFirstName() && this.lastName == tiger.getLastName()) { result = true; } } return result; } @Override public int hashCode() { int hash = 3; if(this.firstName == null || this.lastName == null) { // <b>What is the best practice here, </b> // <b>is return super.hashCode() better ?</b> } hash = 7 * hash + this.firstName.hashCode(); hash = 7 * hash + this.lastName.hashCode(); return hash; } } is it required to check for null in hashCode() ? If yes, what should be returned if custom values are null ?

    Read the article

  • Client side caching in GWT

    - by Silfverstrom
    We have a gwt-client, which recieves quite a lot of data from our servers. Logically, i want to cache the data on the client side, sparing the server from unnecessary requests. As of today i have let it up to my models to handle the caching of data, which doesn't scale very well. It's also become a problem since different developers in our team develop their own "caching" functionality, which floods the project with duplications. I'm thinking about how one could implement a "single point of entry", that handles all the caching, leaving the models clueless about how the caching is handled. Does anyone have any experience with client side caching in GWT? Is there a standard approach that can be implemented?

    Read the article

  • The subsets-sum problem and the solvability of NP-complete problems

    - by G.E.M.
    I was reading about the subset-sums problem when I came up with what appears to be a general-purpose algorithm for solving it: (defun subset-contains-sum (set sum) (let ((subsets) (new-subset) (new-sum)) (dolist (element set) (dolist (subset-sum subsets) (setf new-subset (cons element (car subset-sum))) (setf new-sum (+ element (cdr subset-sum))) (if (= new-sum sum) (return-from subset-contains-sum new-subset)) (setf subsets (cons (cons new-subset new-sum) subsets))) (setf subsets (cons (cons element element) subsets))))) "set" is a list not containing duplicates and "sum" is the sum to search subsets for. "subsets" is a list of cons cells where the "car" is a subset list and the "cdr" is the sum of that subset. New subsets are created from old ones in O(1) time by just cons'ing the element to the front. I am not sure what the runtime complexity of it is, but appears that with each element "sum" grows by, the size of "subsets" doubles, plus one, so it appears to me to at least be quadratic. I am posting this because my impression before was that NP-complete problems tend to be intractable and that the best one can usually hope for is a heuristic, but this appears to be a general-purpose solution that will, assuming you have the CPU cycles, always give you the correct answer. How many other NP-complete problems can be solved like this one?

    Read the article

  • IE8 window.opener problems

    - by fire
    Having problems with IE8... I have a button that onclick fires the showImageBrowser() function. function showImageBrowser(params) { var open = window.open('http://localhost/admin/browse?'+params,'newwin','toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width=950,height=500'); if (!open) { alert('Could not open the image browser, please disable your popup blocker.'); } } Now in the image browser when you click on an image it calls this function: function selectFile(url, el) { window.opener.replaceImage('Test_Image', url); window.close(); } Which is calling the replaceImage() function in the parent window, as expeted. This is the code: function replaceImage(el, url) { $('#'+el).html('<a href="'+url+'" target="_blank" class="image">'+basename(url)+'</a>'); $("input[name='"+el+"']").val(url); } Now if you click on the original showImageBrowser() button for the second time, IE will bring up the window but this time it freezes for a few seconds and then you get the alert "Could not open the image browser, please disable your popup blocker." This works fine in Firefox (obviously) but not in IE. I haven't even tried it in IE7/6 because if it doesn't work in 8 then I know I'm going to have problems. Any advice?

    Read the article

  • Problems with QDialog in Qt

    - by Martin
    I'm using Qt for Symbian. I have some problems with a QDialog that I open from a QMenu. The QDialog shows up fine and in the QDialog I have a QDialogButtonBox with a button to Close the QDialog. BUT if I close the QDialog and then open it from the QMenu again, it will show up but the button from the QDialogButtonBox will not show up. Instead the buttons from the QMainWindow will show but they are grayed out. How can I get the QDialog buttons to show every time? Maybe I have some problems with setting focus on the QDialog? I really can't see what I'm doing wrong here. It's not much code that I use, you can try it yourself. This is my code: In QMainWindow I use the following to create the menu: QAction *menuButton = new QAction("Menu", this); menuButton->setSoftKeyRole(QAction::PositiveSoftKey); QMenu *menu = new QMenu(this); menuButton->setMenu(menu); QAction *popup = new QAction("Show popup",this); connect(popup, SIGNAL(triggered()), this, SLOT(showPopup())); menu->addAction(popup); addAction(menuButton); This shows the QDialog: void MyMainWindow::showPopup(){ TestDialog *test = new TestDialog(this); test->setAttribute(Qt::WA_DeleteOnClose); test->show(); } This is the TestDialog: TestDialog::TestDialog(QWidget *parent) : QDialog(parent) { ui.setupUi(this); QDesktopWidget* desktopWidget = QApplication::desktop(); QRect rect = desktopWidget->availableGeometry(); this->setFixedWidth(rect.width()); }

    Read the article

  • Utility that helps in file locking - expert tips wanted

    - by maix
    I've written a subclass of file that a) provides methods to conveniently lock it (using fcntl, so it only supports unix, which is however OK for me atm) and b) when reading or writing asserts that the file is appropriately locked. Now I'm not an expert at such stuff (I've just read one paper [de] about it) and would appreciate some feedback: Is it secure, are there race conditions, are there other things that could be done better … Here is the code: from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN, LOCK_NB class LockedFile(file): """ A wrapper around `file` providing locking. Requires a shared lock to read and a exclusive lock to write. Main differences: * Additional methods: lock_ex, lock_sh, unlock * Refuse to read when not locked, refuse to write when not locked exclusivly. * mode cannot be `w` since then the file would be truncated before it could be locked. You have to lock the file yourself, it won't be done for you implicitly. Only you know what lock you need. Example usage:: def get_config(): f = LockedFile(CONFIG_FILENAME, 'r') f.lock_sh() config = parse_ini(f.read()) f.close() def set_config(key, value): f = LockedFile(CONFIG_FILENAME, 'r+') f.lock_ex() config = parse_ini(f.read()) config[key] = value f.truncate() f.write(make_ini(config)) f.close() """ def __init__(self, name, mode='r', *args, **kwargs): if 'w' in mode: raise ValueError('Cannot open file in `w` mode') super(LockedFile, self).__init__(name, mode, *args, **kwargs) self.locked = None def lock_sh(self, **kwargs): """ Acquire a shared lock on the file. If the file is already locked exclusively, do nothing. :returns: Lock status from before the call (one of 'sh', 'ex', None). :param nonblocking: Don't wait for the lock to be available. """ if self.locked == 'ex': return # would implicitly remove the exclusive lock return self._lock(LOCK_SH, **kwargs) def lock_ex(self, **kwargs): """ Acquire an exclusive lock on the file. :returns: Lock status from before the call (one of 'sh', 'ex', None). :param nonblocking: Don't wait for the lock to be available. """ return self._lock(LOCK_EX, **kwargs) def unlock(self): """ Release all locks on the file. Flushes if there was an exclusive lock. :returns: Lock status from before the call (one of 'sh', 'ex', None). """ if self.locked == 'ex': self.flush() return self._lock(LOCK_UN) def _lock(self, mode, nonblocking=False): flock(self, mode | bool(nonblocking) * LOCK_NB) before = self.locked self.locked = {LOCK_SH: 'sh', LOCK_EX: 'ex', LOCK_UN: None}[mode] return before def _assert_read_lock(self): assert self.locked, "File is not locked" def _assert_write_lock(self): assert self.locked == 'ex', "File is not locked exclusively" def read(self, *args): self._assert_read_lock() return super(LockedFile, self).read(*args) def readline(self, *args): self._assert_read_lock() return super(LockedFile, self).readline(*args) def readlines(self, *args): self._assert_read_lock() return super(LockedFile, self).readlines(*args) def xreadlines(self, *args): self._assert_read_lock() return super(LockedFile, self).xreadlines(*args) def __iter__(self): self._assert_read_lock() return super(LockedFile, self).__iter__() def next(self): self._assert_read_lock() return super(LockedFile, self).next() def write(self, *args): self._assert_write_lock() return super(LockedFile, self).write(*args) def writelines(self, *args): self._assert_write_lock() return super(LockedFile, self).writelines(*args) def flush(self): self._assert_write_lock() return super(LockedFile, self).flush() def truncate(self, *args): self._assert_write_lock() return super(LockedFile, self).truncate(*args) def close(self): self.unlock() return super(LockedFile, self).close() (the example in the docstring is also my current use case for this) Thanks for having read until down here, and possibly even answering :)

    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

  • Database Design Primay Key, ID vs String

    - by LnDCobra
    Hi, I am currently planning to develop a music streaming application. And i am wondering what would be better as a primary key in my tables on the server. An ID int or a Unique String. Methods 1: Songs Table: SongID(int), Title(string), Artist*(string), Length(int), Album*(string) Genre Table Genre(string), Name(string) SongGenre: SongID*(int), Genre*(string) Method 2 Songs Table: SongID(int), Title(string), ArtistID*(int), Length(int), AlbumID*(int) Genre Table GenreID(int), Name(string) SongGenre: SongID*(int), GenreID*(int) Key: Bold = Primary Key, Field* = Foreign Key I'm currently designing using method 2 as I believe it will speed up lookup performance and use less space as an int takes a lot less space then a string. Is there any reason this isn't a good idea? Is there anything I should be aware of?

    Read the article

  • C# - Which is more efficient and thread safe? static or instant classes?

    - by Soni Ali
    Consider the following two scenarios: //Data Contract public class MyValue { } Scenario 1: Using a static helper class. public class Broker { private string[] _userRoles; public Broker(string[] userRoles) { this._userRoles = userRoles; } public MyValue[] GetValues() { return BrokerHelper.GetValues(this._userRoles); } } static class BrokerHelper { static Dictionary<string, MyValue> _values = new Dictionary<string, MyValue>(); public static MyValue[] GetValues(string[] rolesAllowed) { return FilterForRoles(_values, rolesAllowed); } } Scenario 2: Using an instance class. public class Broker { private BrokerService _service; public Broker(params string[] userRoles) { this._service = new BrokerService(userRoles); } public MyValue[] GetValues() { return _service.GetValues(); } } class BrokerService { private Dictionary<string, MyValue> _values; private string[] _userRoles; public BrokerService(string[] userRoles) { this._userRoles = userRoles; this._values = new Dictionary<string, MyValue>(); } public MyValue[] GetValues() { return FilterForRoles(_values, _userRoles); } } Which of the [Broker] scenarios will scale best if used in a web environment with about 100 different roles and over a thousand users. NOTE: Feel free to sugest any alternative approach.

    Read the article

  • What are the pros and cons of using an in memeory DB rather than a ThreadLocal

    - by Pangea
    we have been using ThreadLocal so far to carry some data so as to not clutter the API. However below are some of issues of using thread local that which I dont like 1) over the years the data items being carried in thread local has increased 2) Since we started using threads (for some light weight processing), we have also migrating these data to the threads in the pool and copying them back again I am thinking of using an in memory DB for these (we doesnt want to add this to the API). I wondering if this approach is good. What r the pros and cons. thx in advance.

    Read the article

  • Django : proper way to use model, duplicates!

    - by llazzaro
    Hello, I have a question about the proper, best way to manage the model. I am relative newbie to django, so I think I need to read more docs, tutorials,etc (suggestions for this would be cool!). Anyway, this is my question : I have a python web crawler, that is "connected" with django model. Crawling is done once a day, so its really common to find "duplicates". To avoid duplicates I do this : cars = Car.Objects.filter(name=crawledItem['name']) if len(cars) 0: #object already exists, update it car = cars[0] else: car = Car() #some non-relevant code here car.save() I want to know, if this is the proper/correct way to do it or its any "automatic" way to do it. Its possible to put the logic inside the Car() constructor also, should I do that? Thanks a lot!

    Read the article

  • What are the pros and cons of using an in memory DB rather than a ThreadLocal

    - by Pangea
    We have been using ThreadLocal so far to carry some data so as to not clutter the API. However below are some of issues of using thread local that which I don't like: 1) Over the years the data items being carried in thread local has increased 2) Since we started using threads (for some light weight processing), we have also migrating these data to the threads in the pool and copying them back again I am thinking of using an in memory DB for these (we doesn't want to add this to the API). I wondering if this approach is good. What are the pros and cons? thx in advance.

    Read the article

  • Using COALESCE to avoid dynamic SQL ?

    - by krul
    I would like to use following sql to avoid constructing sql dynamically: SELECT CommentID, Comment, FROM Comments --if Author id is not null then filter upon author id otherwise get all comments (ignore author id) WHERE AuthorID LIKE COALESCE(@AuthorId, '%') --if comment type is present filter upon it, otherwise get all comments (ignore comment type condition) AND CommentType LIKE COALESCE(@CommentType, '%') I want to know is that safe way to approach this problem? EDIT: Here is final code that satisfy my need to ignore search parameter if is null and applied it if is present: SELECT CommentID, Comment, FROM Comments --if @AuthorId is not null then filter upon @AuthorId otherwise get all comments (ignore author id) WHERE AuthorID = COALESCE(@AuthorId, AuthorID) --if @CommentType is present filter upon it, otherwise get all comments (ignore comment type condition) AND CommentType = COALESCE(@CommentType, CommentType)

    Read the article

  • How do you do merges using Git, Eclipse and Egit

    - by PaulHurleyuk
    I, like many others, love Eclipse as my ide of choice, and because of the way I work (moving about, different places, different projects) want to use Git for CVS. There is a plugin for Git in Eclipse, Egit, which is now an official Eclipse project, and currently at version 0.7.1. As I've just started using it I'm interested in how others are using it, and what work arounds they are using. Currently Egit doesn't have support for merges, so these have to be done outside of Eclipse and then the workspace refreshed. So, How do you do this task ? (and any other tasks that Egit doesn't do right now)

    Read the article

  • Problems when data save on database by Hibernate

    - by alex
    Hi; I'm trying do save data to database by help of Hibernate , in Java. But when i run codes , i had lot of problems. Can anyone help me about that? Thanks... My code: package org.ultimania.model; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Test { public static void main(String[] args) { Session session = null; SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session = sessionFactory.openSession(); Transaction transaction = session.getTransaction(); BusinessCard card = new BusinessCard(); card.setId(1); card.setName("Özgür"); card.setDescription("Aciklama"); try{ transaction.begin(); session.save(card); transaction.commit(); } catch(Exception e){ e.printStackTrace(); } finally{ session.close(); } } } Problems : SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255) at org.hibernate.cfg.Configuration.(Configuration.java:152) at org.ultimania.model.Test.main(Test.java:14) Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 8 more

    Read the article

  • Problems running XNA game on 64-bit Windows 7

    - by Tesserex
    I'm having problems getting my game engine to run on my brother's machine, which is running 64-bit Windows 7. I'm developing on 32-bit XP SP2. My app uses XNA, FMOD.NET, and another dll I wrote entirely in C#. Everything is targeted to x86, not AnyCPU. I've read that this is required for XNA to work because there is no 64-bit xna framework. I recompiled FMOD.NET as x86 as well and made sure to be using the 32-bit version of the native dll. So I don't see any problems there. However when he tries to run my app, it gives an error which is mysterious, but not unheard of. A FileNotFoundException with an empty file name, and the top of the stack trace is in my main form constructor. The message is The specified module could not be found. (Exception from HRESULT: 0x8007007E) I found some threads online about this error, all with very vague, mixed, and fuzzy responses that don't really help me. Most remind people to target x86. Some say check that they have all the dlls necessary. I gave my brother Microsoft.Xna.Framework.dll, but does he need to install the entire XNA redistributable package? When I take everything I sent him and stick it in a random directory, it still runs fine for me. I developed the game in VS2008, not in game studio, using XNA 3.0 and a Windows Forms control that uses XNA drawing which I found in an msdn tutorial. I would also like to avoid requiring a full installer if possible. Any insight? Please?

    Read the article

  • (nested) user controls within a mvp pattern causing sporadic problems

    - by LLEA
    hi everyone, I have a serious problem with nested user controls (UCs) in WinForms while trying to implement the mvp pattern (passive view). The project consists of one model (designed as a singleton) and a set of different presenters with corresponding view interfaces. To avoid one huge view interface and therefore an overloaded main UI, I decided to make use of a set of different UCs. Each UC has one view interface and one presenter that can access the model. But there are nested UCs: meaning that one specialised UC implements sort of a basic UC. The main UI just represents a container for all those UCs. So far, so good (if not, please ask)?! There are two problems that I am facing now (but I guess both are of the same origin): From time to time it is not possible anymore to load the UCs and test them within the Visual Studio 2008 User Control Test Container. The error message just says that a project with an output type of class library cannot be started directly etc. I can "handle" that by unloading all UC projects and reloading them afterwards. (I guess the references to all mvp components and other UCs are then updated). Assuming that the implementation of my mvp pattern is okay and all those UCs are testable within the VS Test Container at a certain time - there is the biggest problem still left: I am not able to add any UC (even the basic and unnested ones) to a simple Form (UI). The error message: error message.jpg Could it be that my basic UC causes all these Problems?! It consists of two simple ComboBoxes and implements a basic presenter and basic view interface. Whenever I add this UC to a different UC the VS designer adds two references to the public getter methods of the UC as resources. I then manually remove those resources from the resx-file and commend the corresponding lines in the designer file. thx in advance

    Read the article

  • single line vs multi-line CSS formatting

    - by pixeltocode
    hi...though it's debatable, i've heard majority of CSS developers prefer multi-line because of the ease at which a property can be found within the CSS file. But doesn't this make the CSS file bigger and less readable on the whole? I think single-line lets you scan the CSS file much faster. Any thoughts?

    Read the article

  • Problems updating a textBox ASP.NET

    - by Roger Filipe
    Hello, I'm starting in asp.net and am having some problems that I do not understand. The problem is this, I am building a site for news. Every news has a title and body. I have a page where I can insert news, this page uses a textbox for each of the fields (title and body), after clicking the submit button everything goes ok and saves the values in the database. And o have another page where I can read the news, I use labels for each of the camps, these labels are defined in the Page_Load. Now I'm having problems on the page where I can edit the news. I am loading two textboxes (title and body) in the Page_Load, so far so good, but then when I change the text and I click the submit button, it ignores the changes that I made in the text and saves the text loaded in Page_Load. This code doesn't show any database connection but you can understand what i'm talking about. protected void Page_Load(object sender, EventArgs e) { textboxTitle.Text = "This is the title of the news"; textboxBody.Text = "This is the body of the news "; } I load the page, make the changes in the text , and then click submit. protected void btnSubmit_Click(object sender, EventArgs e) { String title = textboxTitle.Text; String body = textboxBody.Text; Response.Write("Title: " + title + " || "); Response.Write("Body: " + body ); } Nothing happens, the text in the textboxes is always the one I loaded in the page_load, how do I update the Text in the textboxes?

    Read the article

  • How do implement a breadth first traversal?

    - by not looking for answer
    //This is what I have. I thought pre-order was the same and mixed it up with depth first! import java.util.LinkedList; import java.util.Queue; public class Exercise25_1 { public static void main(String[] args) { BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 }); System.out.print("\nInorder: "); tree.inorder(); System.out.print("\nPreorder: "); tree.preorder(); System.out.print("\nPostorder: "); tree.postorder(); //call the breadth method to test it System.out.print("\nBreadthFirst:"); tree.breadth(); } } class BinaryTree { private TreeNode root; /** Create a default binary tree */ public BinaryTree() { } /** Create a binary tree from an array of objects */ public BinaryTree(Object[] objects) { for (int i = 0; i < objects.length; i++) { insert(objects[i]); } } /** Search element o in this binary tree */ public boolean search(Object o) { return search(o, root); } public boolean search(Object o, TreeNode root) { if (root == null) { return false; } if (root.element.equals(o)) { return true; } else { return search(o, root.left) || search(o, root.right); } } /** Return the number of nodes in this binary tree */ public int size() { return size(root); } public int size(TreeNode root) { if (root == null) { return 0; } else { return 1 + size(root.left) + size(root.right); } } /** Return the depth of this binary tree. Depth is the * number of the nodes in the longest path of the tree */ public int depth() { return depth(root); } public int depth(TreeNode root) { if (root == null) { return 0; } else { return 1 + Math.max(depth(root.left), depth(root.right)); } } /** Insert element o into the binary tree * Return true if the element is inserted successfully */ public boolean insert(Object o) { if (root == null) { root = new TreeNode(o); // Create a new root } else { // Locate the parent node TreeNode parent = null; TreeNode current = root; while (current != null) { if (((Comparable)o).compareTo(current.element) < 0) { parent = current; current = current.left; } else if (((Comparable)o).compareTo(current.element) > 0) { parent = current; current = current.right; } else { return false; // Duplicate node not inserted } } // Create the new node and attach it to the parent node if (((Comparable)o).compareTo(parent.element) < 0) { parent.left = new TreeNode(o); } else { parent.right = new TreeNode(o); } } return true; // Element inserted } public void breadth() { breadth(root); } // Implement this method to produce a breadth first // search traversal public void breadth(TreeNode root){ if (root == null) return; System.out.print(root.element + " "); breadth(root.left); breadth(root.right); } /** Inorder traversal */ public void inorder() { inorder(root); } /** Inorder traversal from a subtree */ private void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); System.out.print(root.element + " "); inorder(root.right); } /** Postorder traversal */ public void postorder() { postorder(root); } /** Postorder traversal from a subtree */ private void postorder(TreeNode root) { if (root == null) { return; } postorder(root.left); postorder(root.right); System.out.print(root.element + " "); } /** Preorder traversal */ public void preorder() { preorder(root); } /** Preorder traversal from a subtree */ private void preorder(TreeNode root) { if (root == null) { return; } System.out.print(root.element + " "); preorder(root.left); preorder(root.right); } /** Inner class tree node */ private class TreeNode { Object element; TreeNode left; TreeNode right; public TreeNode(Object o) { element = o; } } }

    Read the article

  • How does an interpreter switch scope?

    - by Dox
    I'm asking this because I'm relatively new to interpreter development and I wanted to know some basic concepts before reinventing the wheel. I thought of the values of all variables stored in an array which makes the current scope, upon entering a function the array is swapped and the original array put on some sort of stack. When leaving the function the top element of the "scope stack" is popped of and used again. Is this basically right? Isn't swapping arrays (which means moving around a lot of data) not very slow and therefore not used by modern interpreters?

    Read the article

  • When should we use private variables and when should we use properties.

    - by Shantanu Gupta
    In most of the cases we usually creates a private variable and its corresponding public properties and uses them for performing our functionalities. Everyone has different approach like some ppl uses properties every where and some uses private variables within a same class as they are private and opens it to be used by external environment by using properties. Suppose I takes a scenario say insertion in a database. I creates some parameters that need to be initialized. I creates 10 private variables and their corresp public properties which are given as private string name; public string Name { get{return name;} set{name=value;} } and so on. In these cases what should be used internally variables or properties. And in those cases like public string Name { get{return name;} set{name=value>5?5:0;} //or any action can be done. this is just an eg. } In such cases what should be done.

    Read the article

< Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >