Search Results

Search found 196 results on 8 pages for 'compareto'.

Page 5/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • C# Extension Methods - To Extend or Not To Extend...

    - by James Michael Hare
    I've been thinking a lot about extension methods lately, and I must admit I both love them and hate them. They are a lot like sugar, they taste so nice and sweet, but they'll rot your teeth if you eat them too much.   I can't deny that they aren't useful and very handy. One of the major components of the Shared Component library where I work is a set of useful extension methods. But, I also can't deny that they tend to be overused and abused to willy-nilly extend every living type.   So what constitutes a good extension method? Obviously, you can write an extension method for nearly anything whether it is a good idea or not. Many times, in fact, an idea seems like a good extension method but in retrospect really doesn't fit.   So what's the litmus test? To me, an extension method should be like in the movies when a person runs into their twin, separated at birth. You just know you're related. Obviously, that's hard to quantify, so let's try to put a few rules-of-thumb around them.   A good extension method should:     Apply to any possible instance of the type it extends.     Simplify logic and improve readability/maintainability.     Apply to the most specific type or interface applicable.     Be isolated in a namespace so that it does not pollute IntelliSense.     So let's look at a few examples in relation to these rules.   The first rule, to me, is the most important of all. Once again, it bears repeating, a good extension method should apply to all possible instances of the type it extends. It should feel like the long lost relative that should have been included in the original class but somehow was missing from the family tree.    Take this nifty little int extension, I saw this once in a blog and at first I really thought it was pretty cool, but then I started noticing a code smell I couldn't quite put my finger on. So let's look:       public static class IntExtensinos     {         public static int Seconds(int num)         {             return num * 1000;         }           public static int Minutes(int num)         {             return num * 60000;         }     }     This is so you could do things like:       ...     Thread.Sleep(5.Seconds());     ...     proxy.Timeout = 1.Minutes();     ...     Awww, you say, that's cute! Well, that's the problem, it's kitschy and it doesn't always apply (and incidentally you could achieve the same thing with TimeStamp.FromSeconds(5)). It's syntactical candy that looks cool, but tends to rot and pollute the code. It would allow things like:       total += numberOfTodaysOrders.Seconds();     which makes no sense and should never be allowed. The problem is you're applying an extension method to a logical domain, not a type domain. That is, the extension method Seconds() doesn't really apply to ALL ints, it applies to ints that are representative of time that you want to convert to milliseconds.    Do you see what I mean? The two problems, in a nutshell, are that a) Seconds() called off a non-time value makes no sense and b) calling Seconds() off something to pass to something that does not take milliseconds will be off by a factor of 1000 or worse.   Thus, in my mind, you should only ever have an extension method that applies to the whole domain of that type.   For example, this is one of my personal favorites:       public static bool IsBetween<T>(this T value, T low, T high)         where T : IComparable<T>     {         return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;     }   This allows you to check if any IComparable<T> is within an upper and lower bound. Think of how many times you type something like:       if (response.Employee.Address.YearsAt >= 2         && response.Employee.Address.YearsAt <= 10)     {     ...     }     Now, you can instead type:       if(response.Employee.Address.YearsAt.IsBetween(2, 10))     {     ...     }     Note that this applies to all IComparable<T> -- that's ints, chars, strings, DateTime, etc -- and does not depend on any logical domain. In addition, it satisfies the second point and actually makes the code more readable and maintainable.   Let's look at the third point. In it we said that an extension method should fit the most specific interface or type possible. Now, I'm not saying if you have something that applies to enumerables, you create an extension for List, Array, Dictionary, etc (though you may have reasons for doing so), but that you should beware of making things TOO general.   For example, let's say we had an extension method like this:       public static T ConvertTo<T>(this object value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This lets you do more fluent conversions like:       double d = "5.0".ConvertTo<double>();     However, if you dig into Reflector (LOVE that tool) you will see that if the type you are calling on does not implement IConvertible, what you convert to MUST be the exact type or it will throw an InvalidCastException. Now this may or may not be what you want in this situation, and I leave that up to you. Things like this would fail:       object value = new Employee();     ...     // class cast exception because typeof(IEmployee) != typeof(Employee)     IEmployee emp = value.ConvertTo<IEmployee>();       Yes, that's a downfall of working with Convertible in general, but if you wanted your fluent interface to be more type-safe so that ConvertTo were only callable on IConvertibles (and let casting be a manual task), you could easily make it:         public static T ConvertTo<T>(this IConvertible value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This is what I mean by choosing the best type to extend. Consider that if we used the previous (object) version, every time we typed a dot ('.') on an instance we'd pull up ConvertTo() whether it was applicable or not. By filtering our extension method down to only valid types (those that implement IConvertible) we greatly reduce our IntelliSense pollution and apply a good level of compile-time correctness.   Now my fourth rule is just my general rule-of-thumb. Obviously, you can make extension methods as in-your-face as you want. I included all mine in my work libraries in its own sub-namespace, something akin to:       namespace Shared.Core.Extensions { ... }     This is in a library called Shared.Core, so just referencing the Core library doesn't pollute your IntelliSense, you have to actually do a using on Shared.Core.Extensions to bring the methods in. This is very similar to the way Microsoft puts its extension methods in System.Linq. This way, if you want 'em, you use the appropriate namespace. If you don't want 'em, they won't pollute your namespace.   To really make this work, however, that namespace should only include extension methods and subordinate types those extensions themselves may use. If you plant other useful classes in those namespaces, once a user includes it, they get all the extensions too.   Also, just as a personal preference, extension methods that aren't simply syntactical shortcuts, I like to put in a static utility class and then have extension methods for syntactical candy. For instance, I think it imaginable that any object could be converted to XML:       namespace Shared.Core     {         // A collection of XML Utility classes         public static class XmlUtility         {             ...             // Serialize an object into an xml string             public static string ToXml(object input)             {                 var xs = new XmlSerializer(input.GetType());                   // use new UTF8Encoding here, not Encoding.UTF8. The later includes                 // the BOM which screws up subsequent reads, the former does not.                 using (var memoryStream = new MemoryStream())                 using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))                 {                     xs.Serialize(xmlTextWriter, input);                     return Encoding.UTF8.GetString(memoryStream.ToArray());                 }             }             ...         }     }   I also wanted to be able to call this from an object like:       value.ToXml();     But here's the problem, if i made this an extension method from the start with that one little keyword "this", it would pop into IntelliSense for all objects which could be very polluting. Instead, I put the logic into a utility class so that users have the choice of whether or not they want to use it as just a class and not pollute IntelliSense, then in my extensions namespace, I add the syntactical candy:       namespace Shared.Core.Extensions     {         public static class XmlExtensions         {             public static string ToXml(this object value)             {                 return XmlUtility.ToXml(value);             }         }     }   So now it's the best of both worlds. On one hand, they can use the utility class if they don't want to pollute IntelliSense, and on the other hand they can include the Extensions namespace and use as an extension if they want. The neat thing is it also adheres to the Single Responsibility Principle. The XmlUtility is responsible for converting objects to XML, and the XmlExtensions is responsible for extending object's interface for ToXml().

    Read the article

  • 8-Puzzle Solution executes infinitely [migrated]

    - by Ashwin
    I am looking for a solution to 8-puzzle problem using the A* Algorithm. I found this project on the internet. Please see the files - proj1 and EightPuzzle. The proj1 contains the entry point for the program(the main() function) and EightPuzzle describes a particular state of the puzzle. Each state is an object of the 8-puzzle. I feel that there is nothing wrong in the logic. But it loops forever for these two inputs that I have tried : {8,2,7,5,1,6,3,0,4} and {3,1,6,8,4,5,7,2,0}. Both of them are valid input states. What is wrong with the code? Note For better viewing copy the code in a Notepad++ or some other text editor(which has the capability to recognize java source file) because there are lot of comments in the code. Since A* requires a heuristic, they have provided the option of using manhattan distance and a heuristic that calculates the number of misplaced tiles. And to ensure that the best heuristic is executed first, they have implemented a PriorityQueue. The compareTo() function is implemented in the EightPuzzle class. The input to the program can be changed by changing the value of p1d in the main() function of proj1 class. The reason I am telling that there exists solution for the two my above inputs is because the applet here solves them. Please ensure that you select 8-puzzle from teh options in the applet. EDITI gave this input {0,5,7,6,8,1,2,4,3}. It took about 10 seconds and gave a result with 26 moves. But the applet gave a result with 24 moves in 0.0001 seconds with A*. For quick reference I have pasted the the two classes without the comments : EightPuzzle import java.util.*; public class EightPuzzle implements Comparable <Object> { int[] puzzle = new int[9]; int h_n= 0; int hueristic_type = 0; int g_n = 0; int f_n = 0; EightPuzzle parent = null; public EightPuzzle(int[] p, int h_type, int cost) { this.puzzle = p; this.hueristic_type = h_type; this.h_n = (h_type == 1) ? h1(p) : h2(p); this.g_n = cost; this.f_n = h_n + g_n; } public int getF_n() { return f_n; } public void setParent(EightPuzzle input) { this.parent = input; } public EightPuzzle getParent() { return this.parent; } public int inversions() { /* * Definition: For any other configuration besides the goal, * whenever a tile with a greater number on it precedes a * tile with a smaller number, the two tiles are said to be inverted */ int inversion = 0; for(int i = 0; i < this.puzzle.length; i++ ) { for(int j = 0; j < i; j++) { if(this.puzzle[i] != 0 && this.puzzle[j] != 0) { if(this.puzzle[i] < this.puzzle[j]) inversion++; } } } return inversion; } public int h1(int[] list) // h1 = the number of misplaced tiles { int gn = 0; for(int i = 0; i < list.length; i++) { if(list[i] != i && list[i] != 0) gn++; } return gn; } public LinkedList<EightPuzzle> getChildren() { LinkedList<EightPuzzle> children = new LinkedList<EightPuzzle>(); int loc = 0; int temparray[] = new int[this.puzzle.length]; EightPuzzle rightP, upP, downP, leftP; while(this.puzzle[loc] != 0) { loc++; } if(loc % 3 == 0){ temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 1]; temparray[loc + 1] = 0; rightP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); rightP.setParent(this); children.add(rightP); }else if(loc % 3 == 1){ //add one child swaps with right temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 1]; temparray[loc + 1] = 0; rightP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); rightP.setParent(this); children.add(rightP); //add one child swaps with left temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 1]; temparray[loc - 1] = 0; leftP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); leftP.setParent(this); children.add(leftP); }else if(loc % 3 == 2){ // add one child swaps with left temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 1]; temparray[loc - 1] = 0; leftP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); leftP.setParent(this); children.add(leftP); } if(loc / 3 == 0){ //add one child swaps with lower temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 3]; temparray[loc + 3] = 0; downP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); downP.setParent(this); children.add(downP); }else if(loc / 3 == 1 ){ //add one child, swap with upper temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 3]; temparray[loc - 3] = 0; upP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); upP.setParent(this); children.add(upP); //add one child, swap with lower temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 3]; temparray[loc + 3] = 0; downP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); downP.setParent(this); children.add(downP); }else if (loc / 3 == 2 ){ //add one child, swap with upper temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 3]; temparray[loc - 3] = 0; upP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); upP.setParent(this); children.add(upP); } return children; } public int h2(int[] list) // h2 = the sum of the distances of the tiles from their goal positions // for each item find its goal position // calculate how many positions it needs to move to get into that position { int gn = 0; int row = 0; int col = 0; for(int i = 0; i < list.length; i++) { if(list[i] != 0) { row = list[i] / 3; col = list[i] % 3; row = Math.abs(row - (i / 3)); col = Math.abs(col - (i % 3)); gn += row; gn += col; } } return gn; } public String toString() { String x = ""; for(int i = 0; i < this.puzzle.length; i++){ x += puzzle[i] + " "; if((i + 1) % 3 == 0) x += "\n"; } return x; } public int compareTo(Object input) { if (this.f_n < ((EightPuzzle) input).getF_n()) return -1; else if (this.f_n > ((EightPuzzle) input).getF_n()) return 1; return 0; } public boolean equals(EightPuzzle test){ if(this.f_n != test.getF_n()) return false; for(int i = 0 ; i < this.puzzle.length; i++) { if(this.puzzle[i] != test.puzzle[i]) return false; } return true; } public boolean mapEquals(EightPuzzle test){ for(int i = 0 ; i < this.puzzle.length; i++) { if(this.puzzle[i] != test.puzzle[i]) return false; } return true; } } proj1 import java.util.*; public class proj1 { /** * @param args */ public static void main(String[] args) { int[] p1d = {1, 4, 2, 3, 0, 5, 6, 7, 8}; int hueristic = 2; EightPuzzle start = new EightPuzzle(p1d, hueristic, 0); int[] win = { 0, 1, 2, 3, 4, 5, 6, 7, 8}; EightPuzzle goal = new EightPuzzle(win, hueristic, 0); astar(start, goal); } public static void astar(EightPuzzle start, EightPuzzle goal) { if(start.inversions() % 2 == 1) { System.out.println("Unsolvable"); return; } // function A*(start,goal) // closedset := the empty set // The set of nodes already evaluated. LinkedList<EightPuzzle> closedset = new LinkedList<EightPuzzle>(); // openset := set containing the initial node // The set of tentative nodes to be evaluated. priority queue PriorityQueue<EightPuzzle> openset = new PriorityQueue<EightPuzzle>(); openset.add(start); while(openset.size() > 0){ // x := the node in openset having the lowest f_score[] value EightPuzzle x = openset.peek(); // if x = goal if(x.mapEquals(goal)) { // return reconstruct_path(came_from, came_from[goal]) Stack<EightPuzzle> toDisplay = reconstruct(x); System.out.println("Printing solution... "); System.out.println(start.toString()); print(toDisplay); return; } // remove x from openset // add x to closedset closedset.add(openset.poll()); LinkedList <EightPuzzle> neighbor = x.getChildren(); // foreach y in neighbor_nodes(x) while(neighbor.size() > 0) { EightPuzzle y = neighbor.removeFirst(); // if y in closedset if(closedset.contains(y)){ // continue continue; } // tentative_g_score := g_score[x] + dist_between(x,y) // // if y not in openset if(!closedset.contains(y)){ // add y to openset openset.add(y); // } // } // } } public static void print(Stack<EightPuzzle> x) { while(!x.isEmpty()) { EightPuzzle temp = x.pop(); System.out.println(temp.toString()); } } public static Stack<EightPuzzle> reconstruct(EightPuzzle winner) { Stack<EightPuzzle> correctOutput = new Stack<EightPuzzle>(); while(winner.getParent() != null) { correctOutput.add(winner); winner = winner.getParent(); } return correctOutput; } }

    Read the article

  • Is it bad idea to use flag variable to search MAX element in array?

    - by Boris Treukhov
    Over my programming career I formed a habit to introduce a flag variable that indicates that the first comparison has occured, just like Msft does in its linq Max() extension method implementation public static int Max(this IEnumerable<int> source) { if (source == null) { throw Error.ArgumentNull("source"); } int num = 0; bool flag = false; foreach (int num2 in source) { if (flag) { if (num2 > num) { num = num2; } } else { num = num2; flag = true; } } if (!flag) { throw Error.NoElements(); } return num; } However I have met some heretics lately, who implement this by just starting with the first element and assigning it to result, and oh no - it turned out that STL and Java authors have preferred the latter method. Java: public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; } STL: template<class _FwdIt> inline _FwdIt _Max_element(_FwdIt _First, _FwdIt _Last) { // find largest element, using operator< _FwdIt _Found = _First; if (_First != _Last) for (; ++_First != _Last; ) if (_DEBUG_LT(*_Found, *_First)) _Found = _First; return (_Found); } Are there any preferences between one method or another? Are there any historical reasons for this? Is one method more dangerous than another?

    Read the article

  • Interfaces: profit of using

    - by Zapadlo
    First of all, my ubiquitous language is PHP, and I'm thinking about learning Java. So let me split my question on two closely related parts. Here goes the first part. Say I have a domain-model class. It has some getters, setters, some query methods etc. And one day I want to have a possibility to compare them. So it looks like: class MyEntity extends AbstractEntity { public function getId() { // get id property } public function setId($id) { // set id property } // plenty of other methods that set or retrieve data public function compareTo(MyEntity $anotherEntity) { // some compare logic } } If it would have been Java, I should have implemented a Comparable interface. But why? Polymorphism? Readbility? Or something else? And if it was PHP -- should I create Comparable interface for myself? So here goes the second part. My colleague told me that it is a rule of thumb in Java to create an interface for every behavioral aspect of the class. For example, if I wanted to present this object as a string, I should state this behaviour by something like implements Stringable, where in case of PHP Stringable would look like: interface Stringable { public function __toString(); } Is that really a rule of thumb? What benefits are gained with this approach? And does it worth it in PHP? And in Java?

    Read the article

  • ???? “Java?”???????? ?Java???????????!--Java Day Tokyo 2013????

    - by ???Y
    2013?5?14????????Java Day Tokyo 2013?????????????????????1????????Java??????????????JavaOne???????????????????????????Java????????????????????????????????????????????????????????????????????????????????????(????) JavaOne?????????Java Day Tokyo 2013??? ??????Java?????????Java????????(JJUG)??????????????????????????????JJUG????????????????????????????????????????????????????????????????? ???????????????(?????) ???????????????????????????????4???????????????????????"Java SE 8"???????????????????????????????????????????????????? ??????????????????????????????????????2???????????? ???BigDecimal?????equals????????? 1???????BigDecimal?????equals???????????????????????????????????(equity)???(liabilities)?????????(asset)??????1???????????????? ????????Java SE 8???????????????????????????????????????????2??????????????????????????????????????????????????????????????????????????????????????????????????????????0???1???2?????????????? ?????????????BigDecimal???????????????????????????"100"???????????????????????100.00??????????????????????"10000"?????????????????10000????? ??????????BigDecimal?????equals?????????????????????????????2??????????????"10000"??????10000?????????????1???????????"100"???100.00??????????????????? ????????????????equals?????????2???????????????????????????????????????1??????????????????????compareTo???????????????????????????? switch????????? ??????HTML???HTML5????????????????Map?????<Progress>???<tt>???<applet>????3???????????????(new=?????deprecated=????removed=??)???????????switch??????????????????????????????????? ????????????????????????(????applet)?????????????????????????????decorate????????????????????????StringBuilder?????????????????????????? ??????????????????"<applet>?HTML5?????????"??????????????????????????????????????????4????? ???????????????????? ????????????????????????switch???case?break??????????????????????????????????"<applet>?HTML5?????????"???????????????????? ???????????????????????????????????switch??????????????????????????Java SE 6???switch????????????????????????Java SE 7?????????????????????????????????????????? ?????????????????? ????????????????????????????????????????????decorate??????????StringBuilder?????????????????????????????char???????(<)??????????????StringBuilder?????????char????????????????????????????????????????????int???99????????????? ????????????????????????append???????????name???(applet)??>?????????????????????????applet>????????? ????????????Map?status??<applet>???????applet>???????????switch??????status.get(key)????????????status?????null??????????? ???????"??"?????Java?????switch???????null????????NullPointerException??????????? ????????????????????????????????????? ????char?????????????????????????????(IDE)??????????????????????????????????????switch?????????????null????????????????????? ???????2???????????????????Java????·?????????????????????????????????????????????????????????????????????????

    Read the article

  • Android JSON HttpClient to send data to PHP server with HttpResponse

    - by Scoobler
    I am currently trying to send some data from and Android application to a php server (both are controlled by me). There is alot of data collected on a form in the app, this is written to the database. This all works. In my main code, firstly I create a JSONObject (I have cut it down here for this example): JSONObject j = new JSONObject(); j.put("engineer", "me"); j.put("date", "today"); j.put("fuel", "full"); j.put("car", "mine"); j.put("distance", "miles"); Next I pass the object over for sending, and receive the response: String url = "http://www.server.com/thisfile.php"; HttpResponse re = HTTPPoster.doPost(url, j); String temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS")==0) { Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); } The HTTPPoster class: public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); HttpEntity entity; StringEntity s = new StringEntity(c.toString()); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); entity = s; request.setEntity(entity); HttpResponse response; response = httpclient.execute(request); return response; } This gets a response, but the server is returning a 403 - Forbidden response. I have tried changing the doPost function a little (this is actually a little better, as I said I have alot to send, basically 3 of the same form with different data - so I create 3 JSONObjects, one for each form entry - the entries come from the DB instead of the static example I am using). Firstly I changed the call over a bit: String url = "http://www.orsas.com/ServiceMatalan.php"; Map<String, String> kvPairs = new HashMap<String, String>(); kvPairs.put("vehicle", j.toString()); // Normally I would pass two more JSONObjects..... HttpResponse re = HTTPPoster.doPost(url, kvPairs); String temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS")==0) { Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); } Ok so the changes to the doPost function: public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); if (kvPairs != null && kvPairs.isEmpty() == false) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size()); String k, v; Iterator<String> itKeys = kvPairs.keySet().iterator(); while (itKeys.hasNext()) { k = itKeys.next(); v = kvPairs.get(k); nameValuePairs.add(new BasicNameValuePair(k, v)); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } HttpResponse response; response = httpclient.execute(httppost); return response; } Ok So this returns a response 200 int statusCode = re.getStatusLine().getStatusCode(); However the data received on the server cannot be parsed to a JSON string. It is badly formatted I think (this is the first time I have used JSON): If in the php file I do an echo on $_POST['vehicle'] I get the following: {\"date\":\"today\",\"engineer\":\"me\"} Can anyone tell me where I am going wrong, or if there is a better way to achieve what I am trying to do? Hopefully the above makes sense!

    Read the article

  • Generics and Performance question.

    - by Tarmon
    Hey Everyone, I was wondering if anyone could look over a class I wrote, I am receiving generic warnings in Eclipse and I am just wondering if it could be cleaned up at all. All of the warnings I received are surrounded in ** in my code below. The class takes a list of strings in the form of (hh:mm AM/PM) and converts them into HourMinute objects in order to find the first time in the list that comes after the current time. I am also curious about if there are more efficient ways to do this. This works fine but the student in me just wants to find out how I could do this better. public class FindTime { private String[] hourMinuteStringArray; public FindTime(String[] hourMinuteStringArray){ this.hourMinuteStringArray = hourMinuteStringArray; } public int findTime(){ HourMinuteList hourMinuteList = convertHMStringArrayToHMArray(hourMinuteStringArray); Calendar calendar = new GregorianCalendar(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); HourMinute now = new HourMinute(hour,minute); int nearestTimeIndex = findNearestTimeIndex(hourMinuteList, now); return nearestTimeIndex; } private int findNearestTimeIndex(HourMinuteList hourMinuteList, HourMinute now){ HourMinute current; int position = 0; Iterator<HourMinute> iterator = **hourMinuteList.iterator()**; while(iterator.hasNext()){ current = (HourMinute) iterator.next(); if(now.compareTo(current) == -1){ return position; } position++; } return position; } private static HourMinuteList convertHMStringArrayToHMArray(String[] times){ FindTime s = new FindTime(new String[1]); HourMinuteList list = s.new HourMinuteList(); String[] splitTime = new String[3]; for(String time : times ){ String[] tempFirst = time.split(":"); String[] tempSecond = tempFirst[1].split(" "); splitTime[0] = tempFirst[0]; splitTime[1] = tempSecond[0]; splitTime[2] = tempSecond[1]; int hour = Integer.parseInt(splitTime[0]); int minute = Integer.parseInt(splitTime[1]); HourMinute hm; if(splitTime[2] == "AM"){ hm = s.new HourMinute(hour,minute); } else if((splitTime[2].equals("PM")) && (hour < 12)){ hm = s.new HourMinute(hour + 12,minute); } else{ hm = s.new HourMinute(hour,minute); } **list.add(hm);** } return list; } class **HourMinuteList** extends **ArrayList** implements RandomAccess{ } class HourMinute implements **Comparable** { int hour; int minute; public HourMinute(int hour, int minute) { setHour(hour); setMinute(minute); } int getMinute() { return this.minute; } String getMinuteString(){ if(this.minute < 10){ return "0" + this.minute; }else{ return "" + this.minute; } } int getHour() { return this.hour; } void setHour(int hour) { this.hour = hour; } void setMinute(int minute) { this.minute = minute; } @Override public int compareTo(Object aThat) { if (aThat instanceof HourMinute) { HourMinute that = (HourMinute) aThat; if (this.getHour() == that.getHour()) { if (this.getMinute() > that.getMinute()) { return 1; } else if (this.getMinute() < that.getMinute()) { return -1; } else { return 0; } } else if (this.getHour() > that.getHour()) { return 1; } else if (this.getHour() < that.getHour()) { return -1; } else { return 0; } } return 0; } } If you have any questions let me know. Thanks, Rob

    Read the article

  • 3-way quicksort, question

    - by peiska
    I am trying to understand the 3-way radix Quicksort, and i dont understand why the the CUTOFF variable there? and the insertion method? public class Quick3string { private static final int CUTOFF = 15; // cutoff to insertion sort // sort the array a[] of strings public static void sort(String[] a) { // StdRandom.shuffle(a); sort(a, 0, a.length-1, 0); assert isSorted(a); } // return the dth character of s, -1 if d = length of s private static int charAt(String s, int d) { assert d >= 0 && d <= s.length(); if (d == s.length()) return -1; return s.charAt(d); } // 3-way string quicksort a[lo..hi] starting at dth character private static void sort(String[] a, int lo, int hi, int d) { // cutoff to insertion sort for small subarrays if (hi <= lo + CUTOFF) { insertion(a, lo, hi, d); return; } int lt = lo, gt = hi; int v = charAt(a[lo], d); int i = lo + 1; while (i <= gt) { int t = charAt(a[i], d); if (t < v) exch(a, lt++, i++); else if (t > v) exch(a, i, gt--); else i++; } // a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi]. sort(a, lo, lt-1, d); if (v >= 0) sort(a, lt, gt, d+1); sort(a, gt+1, hi, d); } // sort from a[lo] to a[hi], starting at the dth character private static void insertion(String[] a, int lo, int hi, int d) { for (int i = lo; i <= hi; i++) for (int j = i; j > lo && less(a[j], a[j-1], d); j--) exch(a, j, j-1); } // exchange a[i] and a[j] private static void exch(String[] a, int i, int j) { String temp = a[i]; a[i] = a[j]; a[j] = temp; } // is v less than w, starting at character d private static boolean less(String v, String w, int d) { assert v.substring(0, d).equals(w.substring(0, d)); return v.substring(d).compareTo(w.substring(d)) < 0; } // is the array sorted private static boolean isSorted(String[] a) { for (int i = 1; i < a.length; i++) if (a[i].compareTo(a[i-1]) < 0) return false; return true; } public static void main(String[] args) { // read in the strings from standard input String[] a = StdIn.readAll().split("\\s+"); int N = a.length; // sort the strings sort(a); // print the results for (int i = 0; i < N; i++) StdOut.println(a[i]); } } from http://www.cs.princeton.edu/algs4/51radix/Quick3string.java.html

    Read the article

  • JUnit testing, exception in threa main

    - by Crystal
    I am new to JUnit and am trying to follow my prof's example. I have a Person class and a PersonTest class. When I try to compile PersonTest.java, I get the following error: Exception in thread "main" java.lang.NoSuchMethodError: main I am not really sure why since I followed his example. Person.java public class Person implements Comparable { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int compareTo(Object o) { String s1 = this.lastName + this.firstName; String s2 = ((Person) o).lastName + ((Person) o).firstName; return s1.compareTo(s2); } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return this.email.toLowerCase().hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } } PersonTest.java import org.junit.Test; // JDK 5.0 annotation support import static org.junit.Assert.assertTrue; // Using JDK 5.0 static imports import static org.junit.Assert.assertFalse; // Using JDK 5.0 static imports import junit.framework.JUnit4TestAdapter; // Need this to be compatible with old test driver public class PersonTest { /** A test to verify equals method. */ @Test public void checkEquals() { Person p1 = new Person("jj", "aa", "[email protected]", "1112223333"); assertTrue(p1.equals(p1)); // first check in equals method assertFalse(p1.equals(null)); // second check in equals method assertFalse(p1.equals(new Object())); // third chk in equals method Person p2 = new Person("jj", "aa", "[email protected]", "1112223333"); assertTrue(p1.equals(p2)); // check for deep comparison p1 = new Person("jj", "aa", "[email protected]", "1112223333"); p2 = new Person("kk", "aa", "[email protected]", "1112223333"); assertFalse(p1.equals(p2)); // check for deep comkparison } }

    Read the article

  • Why does my performance slow to a crawl I move methods into a base class?

    - by Juliet
    I'm writing different implementations of immutable binary trees in C#, and I wanted my trees to inherit some common methods from a base class. However, I find. I have lots of binary tree data structures to implement, and I wanted move some common methods into in a base binary tree class. Unfortunately, classes which derive from the base class are abysmally slow. Non-derived classes perform adequately. Here are two nearly identical implementations of an AVL tree to demonstrate: AvlTree: http://pastebin.com/V4WWUAyT DerivedAvlTree: http://pastebin.com/PussQDmN The two trees have the exact same code, but I've moved the DerivedAvlTree.Insert method in base class. Here's a test app: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Juliet.Collections.Immutable; namespace ConsoleApplication1 { class Program { const int VALUE_COUNT = 5000; static void Main(string[] args) { var avlTreeTimes = TimeIt(TestAvlTree); var derivedAvlTreeTimes = TimeIt(TestDerivedAvlTree); Console.WriteLine("avlTreeTimes: {0}, derivedAvlTreeTimes: {1}", avlTreeTimes, derivedAvlTreeTimes); } static double TimeIt(Func<int, int> f) { var seeds = new int[] { 314159265, 271828183, 231406926, 141421356, 161803399, 266514414, 15485867, 122949829, 198491329, 42 }; var times = new List<double>(); foreach (int seed in seeds) { var sw = Stopwatch.StartNew(); f(seed); sw.Stop(); times.Add(sw.Elapsed.TotalMilliseconds); } // throwing away top and bottom results times.Sort(); times.RemoveAt(0); times.RemoveAt(times.Count - 1); return times.Average(); } static int TestAvlTree(int seed) { var rnd = new System.Random(seed); var avlTree = AvlTree<double>.Create((x, y) => x.CompareTo(y)); for (int i = 0; i < VALUE_COUNT; i++) { avlTree = avlTree.Insert(rnd.NextDouble()); } return avlTree.Count; } static int TestDerivedAvlTree(int seed) { var rnd = new System.Random(seed); var avlTree2 = DerivedAvlTree<double>.Create((x, y) => x.CompareTo(y)); for (int i = 0; i < VALUE_COUNT; i++) { avlTree2 = avlTree2.Insert(rnd.NextDouble()); } return avlTree2.Count; } } } AvlTree: inserts 5000 items in 121 ms DerivedAvlTree: inserts 5000 items in 2182 ms My profiler indicates that the program spends an inordinate amount of time in BaseBinaryTree.Insert. Anyone whose interested can see the EQATEC log file I've created with the code above (you'll need EQATEC profiler to make sense of file). I really want to use a common base class for all of my binary trees, but I can't do that if performance will suffer. What causes my DerivedAvlTree to perform so badly, and what can I do to fix it?

    Read the article

  • Convert Java program to C

    - by imicrothinking
    I need a bit of guidance with writing a C program...a bit of quick background as to my level, I've programmed in Java previously, but this is my first time programming in C, and we've been tasked to translate a word count program from Java to C that consists of the following: Read a file from memory Count the words in the file For each occurrence of a unique word, keep a word counter variable Print out the top ten most frequent words and their corresponding occurrences Here's the source program in Java: package lab0; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; public class WordCount { private ArrayList<WordCountNode> outputlist = null; public WordCount(){ this.outputlist = new ArrayList<WordCountNode>(); } /** * Read the file into memory. * * @param filename name of the file. * @return content of the file. * @throws Exception if the file is too large or other file related exception. */ public char[] readFile(String filename) throws Exception{ char [] result = null; File file = new File(filename); long size = file.length(); if (size > Integer.MAX_VALUE){ throw new Exception("File is too large"); } result = new char[(int)size]; FileReader reader = new FileReader(file); int len, offset = 0, size2read = (int)size; while(size2read > 0){ len = reader.read(result, offset, size2read); if(len == -1) break; size2read -= len; offset += len; } return result; } /** * Make article word by word. * * @param article the content of file to be counted. * @return string contains only letters and "'". */ private enum SPLIT_STATE {IN_WORD, NOT_IN_WORD}; /** * Go through article, find all the words and add to output list * with their count. * * @param article the content of the file to be counted. * @return words in the file and their counts. */ public ArrayList<WordCountNode> countWords(char[] article){ SPLIT_STATE state = SPLIT_STATE.NOT_IN_WORD; if(null == article) return null; char curr_ltr; int curr_start = 0; for(int i = 0; i < article.length; i++){ curr_ltr = Character.toUpperCase( article[i]); if(state == SPLIT_STATE.IN_WORD){ article[i] = curr_ltr; if ((curr_ltr < 'A' || curr_ltr > 'Z') && curr_ltr != '\'') { article[i] = ' '; //printf("\nthe word is %s\n\n",curr_start); if(i - curr_start < 0){ System.out.println("i = " + i + " curr_start = " + curr_start); } addWord(new String(article, curr_start, i-curr_start)); state = SPLIT_STATE.NOT_IN_WORD; } }else{ if (curr_ltr >= 'A' && curr_ltr <= 'Z') { curr_start = i; article[i] = curr_ltr; state = SPLIT_STATE.IN_WORD; } } } return outputlist; } /** * Add the word to output list. */ public void addWord(String word){ int pos = dobsearch(word); if(pos >= outputlist.size()){ outputlist.add(new WordCountNode(1L, word)); }else{ WordCountNode tmp = outputlist.get(pos); if(tmp.getWord().compareTo(word) == 0){ tmp.setCount(tmp.getCount() + 1); }else{ outputlist.add(pos, new WordCountNode(1L, word)); } } } /** * Search the output list and return the position to put word. * @param word is the word to be put into output list. * @return position in the output list to insert the word. */ public int dobsearch(String word){ int cmp, high = outputlist.size(), low = -1, next; // Binary search the array to find the key while (high - low > 1) { next = (high + low) / 2; // all in upper case cmp = word.compareTo((outputlist.get(next)).getWord()); if (cmp == 0) return next; else if (cmp < 0) high = next; else low = next; } return high; } public static void main(String args[]){ // handle input if (args.length == 0){ System.out.println("USAGE: WordCount <filename> [Top # of results to display]\n"); System.exit(1); } String filename = args[0]; int dispnum; try{ dispnum = Integer.parseInt(args[1]); }catch(Exception e){ dispnum = 10; } long start_time = Calendar.getInstance().getTimeInMillis(); WordCount wordcount = new WordCount(); System.out.println("Wordcount: Running..."); // read file char[] input = null; try { input = wordcount.readFile(filename); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } // count all word ArrayList<WordCountNode> result = wordcount.countWords(input); long end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordcount: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); System.out.println("wordsort: running ..."); start_time = Calendar.getInstance().getTimeInMillis(); Collections.sort(result); end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordsort: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); Collections.reverse(result); System.out.println("\nresults (TOP "+ dispnum +" from "+ result.size() +"):\n" ); // print out result String str ; for (int i = 0; i < result.size() && i < dispnum; i++){ if(result.get(i).getWord().length() > 15) str = result.get(i).getWord().substring(0, 14); else str = result.get(i).getWord(); System.out.println(str + " - " + result.get(i).getCount()); } } public class WordCountNode implements Comparable{ private String word; private long count; public WordCountNode(long count, String word){ this.count = count; this.word = word; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public int compareTo(Object arg0) { // TODO Auto-generated method stub WordCountNode obj = (WordCountNode)arg0; if( count - obj.getCount() < 0) return -1; else if( count - obj.getCount() == 0) return 0; else return 1; } } } Here's my attempt (so far) in C: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> // Read in a file FILE *readFile (char filename[]) { FILE *inputFile; inputFile = fopen (filename, "r"); if (inputFile == NULL) { printf ("File could not be opened.\n"); exit (EXIT_FAILURE); } return inputFile; } // Return number of words in an array int wordCount (FILE *filePointer, char filename[]) {//, char *words[]) { // count words int count = 0; char temp; while ((temp = getc(filePointer)) != EOF) { //printf ("%c", temp); if ((temp == ' ' || temp == '\n') && (temp != '\'')) count++; } count += 1; // counting method uses space AFTER last character in word - the last space // of the last character isn't counted - off by one error // close file fclose (filePointer); return count; } // Print out the frequencies of the 10 most frequent words in the console int main (int argc, char *argv[]) { /* Step 1: Read in file and check for errors */ FILE *filePointer; filePointer = readFile (argv[1]); /* Step 2: Do a word count to prep for array size */ int count = wordCount (filePointer, argv[1]); printf ("Number of words is: %i\n", count); /* Step 3: Create a 2D array to store words in the file */ // open file to reset marker to beginning of file filePointer = fopen (argv[1], "r"); // store words in character array (each element in array = consecutive word) char allWords[count][100]; // 100 is an arbitrary size - max length of word int i,j; char temp; for (i = 0; i < count; i++) { for (j = 0; j < 100; j++) { // labels are used with goto statements, not loops in C temp = getc(filePointer); if ((temp == ' ' || temp == '\n' || temp == EOF) && (temp != '\'') ) { allWords[i][j] = '\0'; break; } else { allWords[i][j] = temp; } printf ("%c", allWords[i][j]); } printf ("\n"); } // close file fclose (filePointer); /* Step 4: Use a simple selection sort algorithm to sort 2D char array */ // PStep 1: Compare two char arrays, and if // (a) c1 > c2, return 2 // (b) c1 == c2, return 1 // (c) c1 < c2, return 0 qsort(allWords, count, sizeof(char[][]), pstrcmp); /* int k = 0, l = 0, m = 0; char currentMax, comparedElement; int max; // the largest element in the current 2D array int elementToSort = 0; // elementToSort determines the element to swap with starting from the left // Outer a iterates through number of swaps needed for (k = 0; k < count - 1; k++) { // times of swaps max = k; // max element set to k // Inner b iterates through successive elements to fish out the largest element for (m = k + 1; m < count - k; m++) { currentMax = allWords[k][l]; comparedElement = allWords[m][l]; // Inner c iterates through successive chars to set the max vars to the largest for (l = 0; (currentMax != '\0' || comparedElement != '\0'); l++) { if (currentMax > comparedElement) break; else if (currentMax < comparedElement) { max = m; currentMax = allWords[m][l]; break; } else if (currentMax == comparedElement) continue; } } // After max (count and string) is determined, perform swap with temp variable char swapTemp[1][20]; int y = 0; do { swapTemp[0][y] = allWords[elementToSort][y]; allWords[elementToSort][y] = allWords[max][y]; allWords[max][y] = swapTemp[0][y]; } while (swapTemp[0][y++] != '\0'); elementToSort++; } */ int a, b; for (a = 0; a < count; a++) { for (b = 0; (temp = allWords[a][b]) != '\0'; b++) { printf ("%c", temp); } printf ("\n"); } // Copy rows to different array and print results /* char arrayCopy [count][20]; int ac, ad; char tempa; for (ac = 0; ac < count; ac++) { for (ad = 0; (tempa = allWords[ac][ad]) != '\0'; ad++) { arrayCopy[ac][ad] = tempa; printf("%c", arrayCopy[ac][ad]); } printf("\n"); } */ /* Step 5: Create two additional arrays: (a) One in which each element contains unique words from char array (b) One which holds the count for the corresponding word in the other array */ /* Step 6: Sort the count array in decreasing order, and print the corresponding array element as well as word count in the console */ return 0; } // Perform housekeeping tasks like freeing up memory and closing file I'm really stuck on the selection sort algorithm. I'm currently using 2D arrays to represent strings, and that worked out fine, but when it came to sorting, using three level nested loops didn't seem to work, I tried to use qsort instead, but I don't fully understand that function as well. Constructive feedback and criticism greatly welcome (...and needed)!

    Read the article

  • General type conversion without risking Exceptions

    - by Mongus Pong
    I am working on a control that can take a number of different datatypes (anything that implements IComparable). I need to be able to compare these with another variable passed in. If the main datatype is a DateTime, and I am passed a String, I need to attempt to convert the String to a DateTime to perform a Date comparison. if the String cannot be converted to a DateTime then do a String comparison. So I need a general way to attempt to convert from any type to any type. Easy enough, .Net provides us with the TypeConverter class. Now, the best I can work out to do to determine if the String can be converted to a DateTime is to use exceptions. If the ConvertFrom raises an exception, I know I cant do the conversion and have to do the string comparison. The following is the best I got : string theString = "99/12/2009"; DateTime theDate = new DateTime ( 2009, 11, 1 ); IComparable obj1 = theString as IComparable; IComparable obj2 = theDate as IComparable; try { TypeConverter converter = TypeDescriptor.GetConverter ( obj2.GetType () ); if ( converter.CanConvertFrom ( obj1.GetType () ) ) { Console.WriteLine ( obj2.CompareTo ( converter.ConvertFrom ( obj1 ) ) ); Console.WriteLine ( "Date comparison" ); } } catch ( FormatException ) { Console.WriteLine ( obj1.ToString ().CompareTo ( obj2.ToString () ) ); Console.WriteLine ( "String comparison" ); } Part of our standards at work state that : Exceptions should only be raised when an Exception situation - ie. an error is encountered. But this is not an exceptional situation. I need another way around it. Most variable types have a TryParse method which returns a boolean to allow you to determine if the conversion has succeeded or not. But there is no TryConvert method available to TypeConverter. CanConvertFrom only dermines if it is possible to convert between these types and doesnt consider the actual data to be converted. The IsValid method is also useless. Any ideas? EDIT I cannot use AS and IS. I do not know either data types at compile time. So I dont know what to As and Is to!!! EDIT Ok nailed the bastard. Its not as tidy as Marc Gravells, but it works (I hope). Thanks for the inpiration Marc. Will work on tidying it up when I get the time, but I've got a bit stack of bugfixes that I have to get on with. public static class CleanConverter { /// <summary> /// Stores the cache of all types that can be converted to all types. /// </summary> private static Dictionary<Type, Dictionary<Type, ConversionCache>> _Types = new Dictionary<Type, Dictionary<Type, ConversionCache>> (); /// <summary> /// Try parsing. /// </summary> /// <param name="s"></param> /// <param name="value"></param> /// <returns></returns> public static bool TryParse ( IComparable s, ref IComparable value ) { // First get the cached conversion method. Dictionary<Type, ConversionCache> type1Cache = null; ConversionCache type2Cache = null; if ( !_Types.ContainsKey ( s.GetType () ) ) { type1Cache = new Dictionary<Type, ConversionCache> (); _Types.Add ( s.GetType (), type1Cache ); } else { type1Cache = _Types[s.GetType ()]; } if ( !type1Cache.ContainsKey ( value.GetType () ) ) { // We havent converted this type before, so create a new conversion type2Cache = new ConversionCache ( s.GetType (), value.GetType () ); // Add to the cache type1Cache.Add ( value.GetType (), type2Cache ); } else { type2Cache = type1Cache[value.GetType ()]; } // Attempt the parse return type2Cache.TryParse ( s, ref value ); } /// <summary> /// Stores the method to convert from Type1 to Type2 /// </summary> internal class ConversionCache { internal bool TryParse ( IComparable s, ref IComparable value ) { if ( this._Method != null ) { // Invoke the cached TryParse method. object[] parameters = new object[] { s, value }; bool result = (bool)this._Method.Invoke ( null, parameters); if ( result ) value = parameters[1] as IComparable; return result; } else return false; } private MethodInfo _Method; internal ConversionCache ( Type type1, Type type2 ) { // Use reflection to get the TryParse method from it. this._Method = type2.GetMethod ( "TryParse", new Type[] { type1, type2.MakeByRefType () } ); } } }

    Read the article

  • Elusive race condition in Java

    - by nasufara
    I am creating a graphing calculator. In an attempt to squeeze some more performance out of it, I added some multithreaded to the line calculator. Essentially what my current implementation does is construct a thread-safe Queue of X values, then start however many threads it needs, each one calculating a point on the line using the queue to get its values, and then ordering the points using a HashMap when the calculations are done. This implementation works great, and that's not where my race condition is (merely some background info). In examining the performance results from this, I found that the HashMap is a performance bottleneck, since I do that synchronously on one thread. So I figured that ordering each point as its calculated would work best. I tried a PriorityQueue, but that was slower than the HashMap. I ended up creating an algorithm that essentially works like this: I construct a list of X values to calculate, like in my current algorithm. I then copy that list of values into another class, unimaginatively and temporarily named BlockingList, which is responsible for ordering the points as they are calculated. BlockingList contains a put() method, which takes in two BigDecimals as parameters, the first the X value, the second the calculated Y value. put() will only accept a value if the X value is the next one on the list to be accepted in the list of X values, and will block until another thread gives it the next excepted value. For example, since that can be confusing, say I have two threads, Thread-1 and Thread-2. Thread-2 gets the X value 10.0 from the values queue, and Thread-1 gets 9.0. However, Thread-1 completes its calculations first, and calls put() before Thread-2 does. Because BlockingList is expecting to get 10.0 first, and not 9.0, it will block on Thread-1 until Thread-2 finishes and calls put(). Once Thread-2 gives BlockingList 10.0, it notify()s all waiting threads, and expects 9.0 next. This continues until BlockingList gets all of its expected values. (I apologise if that was hard to follow, if you need more clarification, just ask.) As expected by the question title, there is a race condition in here. If I run it without any System.out.printlns, it will sometimes lock because of conflicting wait() and notifyAll()s, but if I put a println in, it will run great. A small implementation of this is included below, and exhibits the same behavior: import java.math.BigDecimal; import java.util.concurrent.ConcurrentLinkedQueue; public class Example { public static void main(String[] args) throws InterruptedException { // Various scaling values, determined based on the graph size // in the real implementation BigDecimal xMax = new BigDecimal(10); BigDecimal xStep = new BigDecimal(0.05); // Construct the values list, from -10 to 10 final ConcurrentLinkedQueue<BigDecimal> values = new ConcurrentLinkedQueue<BigDecimal>(); for (BigDecimal i = new BigDecimal(-10); i.compareTo(xMax) <= 0; i = i.add(xStep)) { values.add(i); } // Contains the calculated values final BlockingList list = new BlockingList(values); for (int i = 0; i < 4; i++) { new Thread() { public void run() { BigDecimal x; // Keep looping until there are no more values while ((x = values.poll()) != null) { PointPair pair = new PointPair(); pair.realX = x; try { list.put(pair); } catch (Exception ex) { ex.printStackTrace(); } } } }.start(); } } private static class PointPair { public BigDecimal realX; } private static class BlockingList { private final ConcurrentLinkedQueue<BigDecimal> _values; private final ConcurrentLinkedQueue<PointPair> _list = new ConcurrentLinkedQueue<PointPair>(); public BlockingList(ConcurrentLinkedQueue<BigDecimal> expectedValues) throws InterruptedException { // Copy the values into a new queue BigDecimal[] arr = expectedValues.toArray(new BigDecimal[0]); _values = new ConcurrentLinkedQueue<BigDecimal>(); for (BigDecimal dec : arr) { _values.add(dec); } } public void put(PointPair item) throws InterruptedException { while (item.realX.compareTo(_values.peek()) != 0) { synchronized (this) { // Block until someone enters the next desired value wait(); } } _list.add(item); _values.poll(); synchronized (this) { notifyAll(); } } } } My question is can anybody help me find the threading error? Thanks!

    Read the article

  • Implementing IComparable<NotSelf>

    - by Luc Touraille
    This might be a trivial question, but I didn't find any information about this: is it "harmful" or considered bad practice to make a type T implement IComparable<S> (T and S being two different types)? Example: class Foo : IComparable<int> { public int CompareTo(int other) { if (other < i) return -1; if (other > i) return 1; return 0; } private int i; } Should this kind of code be avoided, and if yes, why?

    Read the article

  • Sort ArrayList of custom Objects by property

    - by Samuel
    Hello World!! :D I had a question which is pretty easy if you know the answer I guess. I read about sorting ArrayLists using a Comparator but somehow in all of the examples people used compareTo which according to some research is a method working on Strings... I wanted to sort an ArrayList of custom objects by one of their properties: a Date object (getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like: public class customComparator { public boolean compare(Object object1, Object object2) { return object1.getStartDate().before(object2.getStartDate()); } } public class randomName { ... Collections.sort(Database.arrayList, new customComparator); ... } I just started with Java so please forgive my ignorance :) Thanks in advance!! -Samuel

    Read the article

  • Creating a CLR UDF with variable number of parameters

    - by josephj1989
    Hi I wanted a function to find the greatest of a list of String values passed in. I want to invoke it as Select greatest('Abcd','Efgh','Zxy','EAD') from sql server. It should return Zxy. The number of parameters is variable.Incidentally it is very similar to oracle GREATEST function. So I wrote a very simple CLR function (Vs2008) and tried to deploy it. See below public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString Greatest(params SqlString[] p) { SqlString max=p[0]; foreach (string s in p) max = s.CompareTo(max) > 0 ? s : max; return max; } }; But when I try to compile or deploy it I get the following error Cannot find data type SqlString[]. Is it possible to satisfy my requirement using SQL CLR ?

    Read the article

  • Entity framework - exclude list of values

    - by DutrowLLC
    Is there a way to exclude a list of values for an object attribute when querying the database through entity framework? I tried to be slick and pull this number: List<String> StringList = new List<String>(); StringList.Add("ya_mama"); StringList.Add("has"); StringList.Add("fleas"); servicesEntities context = new servicesEntities(); var NoFleasQuery = (from x in context.person where !StringList.Any(y => y.CompareTo(x.the_string_I_dont_want_it_to_be) == 0) // <--- the part where I thought I was slick select x); ...it compiled, but after I ran it, it gave me this error: Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context. 'Closure type'???? How about MY closure!!! Entity framework... you broke my heart.

    Read the article

  • biginteger calucation prfoblem

    - by murali
    hi i am using the following code but the parameters are not passed to the methods. BigInteger p = BigInteger.valueOf(0); BigInteger u1 = obj.bigi_calc(g1, l); in this g1,l are long values the method is private BigInteger bigi_calc(long g1, long l){ BigInteger cal = BigInteger.valueOf(g1); BigInteger cal1= BigInteger.valueOf(l); for(BigInteger f = BigInteger.ONE;f.compareTo(cal1)>0;f=f.add(BigInteger.ONE)){ //BigInteger p= BigInteger.valueOf(0); p = cal.multiply(cal1); System.out.println("check p"+p); } // System.out.println("check p"+p); return p; } the elipse shows that it may be out of sync.. but the paramerters are not passed to the functions.. can you plz help me to slove this problem

    Read the article

  • need identical string comparison function in php and java

    - by steelbytes
    I have sorted list of strings that I move between php and java. to be able to bsearch on this data, I need the same comparison function. any idea what string compare functions I can use that will always give the same result in both? eg php's strcmp() vs java's String.compareTo() yes I know I could make my own string compare that does char by char carefully, but I was hoping there's a simple answer. PS, don't care if case sensitive or not, as long as it is consistant.

    Read the article

  • Riddle: Spot the serious bug in this bubble sort implementation

    - by ripper234
    (No, this isn't a homework assignment, I just found the bug and thought it might be useful to share it here) import java.util.List; public class BubbleSorter { public <T extends Comparable<T>> void sort(List<T> list) { while (true) { boolean didWork = false; for (int i = 0; i < list.size() - 1; ++i) { if (list.get(i).compareTo(list.get(i + 1)) > 0) { swap(list, i, i + 1); didWork = true; break; } } if (!didWork) return; } } private static <T> void swap(List<T> list, int i, int j) { T tmp = list.get(i); list.set(i, list.get(j)); list.set(j, tmp); } }

    Read the article

  • Implementing IComparer<T> For IComparer<DictionaryEntry>

    - by Phil Sandler
    I am using the ObservableSortedDictionary from Dr. WPF. The constructor looks like this: public ObservableSortedDictionary(IComparer<DictionaryEntry> comparer) I am really struggling to create an implementation that satisfies the constructor and works. My current code (that won't compile) is: public class TimeCreatedComparer<T> : IComparer<T> { public int Compare(T x, T y) { var myclass1 = (IMyClass)((DictionaryEntry)x).Value; var myclass2 = (IMyClass)((DictionaryEntry)y).Value; return myclass1.TimeCreated.CompareTo(myclass2.TimeCreated); } } It says I can't cast from T to DictionaryEntry. If I cast directly to IMyClass, it compiles, but I get a runtime error saying I can't cast from DictionaryEntry to IMyClass. At runtime, x and y are instances of DictionaryEntry, which each have the correct IMyClass as their Value.

    Read the article

  • Arraylist is null; I cannot access books in the arraylist

    - by user3701380
    I am a beginner-intermediate java programmer and I am getting a null pointer exception from my arraylist. I am writing a bookstore program for APCS and when i add the book, it is supposed to add to the arraylist in the inventory class. But when i call a method to search for a book (e.g. by title), it shows that there isn't anything in the arraylist. //Here is my inventory class -- it has all methods for adding the book or searching for one The searching methods are in getBookByTitle, getBookByAuthor, and getBookByISBN and the method for adding a book is addBook package webbazonab; //Inventory Class //Bharath Senthil //Ansh Sikka import java.util.ArrayList; public class Inventory{ private ArrayList<Book> allBooks = new ArrayList<Book>(); private String bookTitles; private String bookAuthors; private String bookPrices; private String bookCopies; private String ISBNs; public Inventory() { } //@param double price, int copies, String bookTitle, String Author, String isbnNumber public void addBooks(Book addedBook){ allBooks.add(addedBook); } public boolean isAvailable(){ for(Book myBook : allBooks){ if(myBook.copiesLeft() == 0) return false; } return true; } public String populateTitle(){ for (Book titleBooks : allBooks){ bookTitles = titleBooks.getTitle() + "\n"; return bookTitles; } return bookTitles; } public String populateAuthor(){ for(Book authorBooks : allBooks){ bookAuthors = authorBooks.getAuthor() + "\n"; return bookAuthors; } return bookAuthors; } public String populatePrice(){ for (Book pricedBooks : allBooks){ bookPrices = String.valueOf(pricedBooks.getPrice()) + "\n"; } return "$" + bookPrices; } /** * * @return */ public String populateCopies(){ for (Book amtBooks : allBooks){ bookCopies = String.valueOf(amtBooks.copiesLeft()) + "\n"; return bookCopies; } return bookCopies; } public String populateISBN(){ for (Book isbnNums : allBooks){ ISBNs = isbnNums.getIsbn() + "\n"; return ISBNs; } return ISBNs; } @SuppressWarnings("empty-statement") public Book getBookByTitle(String titleSearch) { for(Book titleBook : allBooks) { if (titleBook.getTitle().equals(titleSearch)) { return titleBook; } } return null; } public Book getBookByISBN(String isbnSearch){ for(Book isbnBookSearches : allBooks){ if(isbnBookSearches.getIsbn().equals(isbnSearch)){ return isbnBookSearches; } } return null; } public Book getBookByAuthor(String authorSearch){ for(Book authorBookSearches : allBooks){ if(authorBookSearches.getAuthor().equals(authorSearch)){ return authorBookSearches; } } return null; } public void sort(){ for(int i = 0; i < allBooks.size(); i++) { for(int k = 0; k < allBooks.size(); k++) { if(((Book) allBooks.get(i)).getIsbn().compareTo(((Book) allBooks.get(k)).getIsbn()) < 1) { Book temp = (Book) allBooks.get(k); allBooks.set(k, allBooks.get(i)); allBooks.set(i, temp); } else if(((Book) allBooks.get(i)).getIsbn().compareTo(((Book) allBooks.get(k)).getIsbn()) > 1) { Book temp = (Book) allBooks.get(i); allBooks.set(i, allBooks.get(k)); allBooks.set(k, temp); } } } } public ArrayList<Book> getBooks(){ return allBooks; } } //The exception occurs when i call the method here (in another class): Inventory lib = new Inventory(); jTextField12.setText(lib.getBookByAuthor(authorSearch).getTitle()); Here is my book class if you need it package webbazonab; //Webbazon AB //Project By: Ansh Sikka and Bharath Senthil public class Book { private double myPrice; private String myTitle; private String bookAuthor; private String isbn; private int myCopies; public Book(double price, int copies, String bookTitle, String Author, String isbnNumber) { myPrice = price; myCopies = copies; myTitle = bookTitle; bookAuthor = Author; isbn = isbnNumber; } public double getPrice() { return myPrice; } public String getIsbn() { return isbn; } public String getTitle() { return myTitle; } public String getAuthor() { return bookAuthor; } public int copiesLeft(){ return myCopies; } public String notFound(){ return "The book you searched for could not be found!"; } public String toString() { return "Title: " + getTitle() + "\nAuthor: " + getAuthor() + "\nNumber of Available Books: " + copiesLeft() + "\nPrice: $" + getPrice(); } } Thanks!

    Read the article

  • Passing a comparator syntax help in Java

    - by Crystal
    I've tried this a couple ways, the first is have a class that implements comparator at the bottom of the following code. When I try to pass the comparat in sortListByLastName, I get a constructor not found error and I am not sure why import java.util.*; public class OrganizeThis implements WhoDoneIt { /** Add a person to the organizer @param p A person object */ public void add(Person p) { staff.put(p.getEmail(), p); //System.out.println("Person " + p + "added"); } /** * Remove a Person from the organizer. * * @param email The email of the person to be removed. */ public void remove(String email) { staff.remove(email); } /** * Remove all contacts from the organizer. * */ public void empty() { staff.clear(); } /** * Find the person stored in the organizer with the email address. * Note, each person will have a unique email address. * * @param email The person email address you are looking for. * */ public Person findByEmail(String email) { Person aPerson = staff.get(email); return aPerson; } /** * Find all persons stored in the organizer with the same last name. * Note, there can be multiple persons with the same last name. * * @param lastName The last name of the persons your are looking for. * */ public Person[] find(String lastName) { ArrayList<Person> names = new ArrayList<Person>(); for (Person s : staff.values()) { if (s.getLastName() == lastName) { names.add(s); } } // Convert ArrayList back to Array Person nameArray[] = new Person[names.size()]; names.toArray(nameArray); return nameArray; } /** * Return all the contact from the orgnizer in * an array sorted by last name. * * @return An array of Person objects. * */ public Person[] getSortedListByLastName() { PersonLastNameComparator comp = new PersonLastNameComparator(); Map<String, Person> sorted = new TreeMap<String, Person>(comp); ArrayList<Person> sortedArrayList = new ArrayList<Person>(); for (Person s: sorted.values()) { sortedArrayList.add(s); } Person sortedArray[] = new Person[sortedArrayList.size()]; sortedArrayList.toArray(sortedArray); return sortedArray; } private Map<String, Person> staff = new HashMap<String, Person>(); public static void main(String[] args) { OrganizeThis testObj = new OrganizeThis(); Person person1 = new Person("J", "W", "111-222-3333", "[email protected]"); Person person2 = new Person("K", "W", "345-678-9999", "[email protected]"); Person person3 = new Person("Phoebe", "Wang", "322-111-3333", "[email protected]"); Person person4 = new Person("Nermal", "Johnson", "322-342-5555", "[email protected]"); Person person5 = new Person("Apple", "Banana", "123-456-1111", "[email protected]"); testObj.add(person1); testObj.add(person2); testObj.add(person3); testObj.add(person4); testObj.add(person5); System.out.println(testObj.findByEmail("[email protected]")); System.out.println("------------" + '\n'); Person a[] = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("------------" + '\n'); a = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("SORTED" + '\n'); a = testObj.getSortedListByLastName(); for (Person b : a) { System.out.println(b); } System.out.println(testObj.getAuthor()); } } class PersonLastNameComparator implements Comparator<Person> { public int compare(Person a, Person b) { return a.getLastName().compareTo(b.getLastName()); } } And then when I tried doing it by creating an anonymous inner class, I also get a constructor TreeMap cannot find symbol error. Any thoughts? inner class method: public Person[] getSortedListByLastName() { //PersonLastNameComparator comp = new PersonLastNameComparator(); Map<String, Person> sorted = new TreeMap<String, Person>(new Comparator<Person>() { public int compare(Person a, Person b) { return a.getLastName().compareTo(b.getLastName()); } }); ArrayList<Person> sortedArrayList = new ArrayList<Person>(); for (Person s: sorted.values()) { sortedArrayList.add(s); } Person sortedArray[] = new Person[sortedArrayList.size()]; sortedArrayList.toArray(sortedArray); return sortedArray; }

    Read the article

  • Why is insertion into my tree faster on sorted input than random input?

    - by Juliet
    Now I've always heard binary search trees are faster to build from randomly selected data than ordered data, simply because ordered data requires explicit rebalancing to keep the tree height at a minimum. Recently I implemented an immutable treap, a special kind of binary search tree which uses randomization to keep itself relatively balanced. In contrast to what I expected, I found I can consistently build a treap about 2x faster and generally better balanced from ordered data than unordered data -- and I have no idea why. Here's my treap implementation: http://pastebin.com/VAfSJRwZ And here's a test program: using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static Random rnd = new Random(); const int ITERATION_COUNT = 20; static void Main(string[] args) { List<double> rndTimes = new List<double>(); List<double> orderedTimes = new List<double>(); rndTimes.Add(TimeIt(50, RandomInsert)); rndTimes.Add(TimeIt(100, RandomInsert)); rndTimes.Add(TimeIt(200, RandomInsert)); rndTimes.Add(TimeIt(400, RandomInsert)); rndTimes.Add(TimeIt(800, RandomInsert)); rndTimes.Add(TimeIt(1000, RandomInsert)); rndTimes.Add(TimeIt(2000, RandomInsert)); rndTimes.Add(TimeIt(4000, RandomInsert)); rndTimes.Add(TimeIt(8000, RandomInsert)); rndTimes.Add(TimeIt(16000, RandomInsert)); rndTimes.Add(TimeIt(32000, RandomInsert)); rndTimes.Add(TimeIt(64000, RandomInsert)); rndTimes.Add(TimeIt(128000, RandomInsert)); string rndTimesAsString = string.Join("\n", rndTimes.Select(x => x.ToString()).ToArray()); orderedTimes.Add(TimeIt(50, OrderedInsert)); orderedTimes.Add(TimeIt(100, OrderedInsert)); orderedTimes.Add(TimeIt(200, OrderedInsert)); orderedTimes.Add(TimeIt(400, OrderedInsert)); orderedTimes.Add(TimeIt(800, OrderedInsert)); orderedTimes.Add(TimeIt(1000, OrderedInsert)); orderedTimes.Add(TimeIt(2000, OrderedInsert)); orderedTimes.Add(TimeIt(4000, OrderedInsert)); orderedTimes.Add(TimeIt(8000, OrderedInsert)); orderedTimes.Add(TimeIt(16000, OrderedInsert)); orderedTimes.Add(TimeIt(32000, OrderedInsert)); orderedTimes.Add(TimeIt(64000, OrderedInsert)); orderedTimes.Add(TimeIt(128000, OrderedInsert)); string orderedTimesAsString = string.Join("\n", orderedTimes.Select(x => x.ToString()).ToArray()); Console.WriteLine("Done"); } static double TimeIt(int insertCount, Action<int> f) { Console.WriteLine("TimeIt({0}, {1})", insertCount, f.Method.Name); List<double> times = new List<double>(); for (int i = 0; i < ITERATION_COUNT; i++) { Stopwatch sw = Stopwatch.StartNew(); f(insertCount); sw.Stop(); times.Add(sw.Elapsed.TotalMilliseconds); } return times.Average(); } static void RandomInsert(int insertCount) { Treap<double> tree = new Treap<double>((x, y) => x.CompareTo(y)); for (int i = 0; i < insertCount; i++) { tree = tree.Insert(rnd.NextDouble()); } } static void OrderedInsert(int insertCount) { Treap<double> tree = new Treap<double>((x, y) => x.CompareTo(y)); for(int i = 0; i < insertCount; i++) { tree = tree.Insert(i + rnd.NextDouble()); } } } } And here's a chart comparing random and ordered insertion times in milliseconds: Insertions Random Ordered RandomTime / OrderedTime 50 1.031665 0.261585 3.94 100 0.544345 1.377155 0.4 200 1.268320 0.734570 1.73 400 2.765555 1.639150 1.69 800 6.089700 3.558350 1.71 1000 7.855150 4.704190 1.67 2000 17.852000 12.554065 1.42 4000 40.157340 22.474445 1.79 8000 88.375430 48.364265 1.83 16000 197.524000 109.082200 1.81 32000 459.277050 238.154405 1.93 64000 1055.508875 512.020310 2.06 128000 2481.694230 1107.980425 2.24 I don't see anything in the code which makes ordered input asymptotically faster than unordered input, so I'm at a loss to explain the difference. Why is it so much faster to build a treap from ordered input than random input?

    Read the article

  • asp .net MVC 2.0 Validation

    - by ANDyW
    Hi I’m trying to do some validation in asp .net MVC 2.0 for my application. I want to have some nice client side validation. Validation should be done most time on model side with DataAnnotations with custom attributes( like CompareTo, StringLenght, MinPasswordLenght (from Membership.MinimumumpassworkdLenght value). For that purpose I tried to use xval with jquery.validation. Some specific thing is that most of forms will be working with ajax and most problems are when I want to validate form with ajax. Here is link for sample project http://www.sendspace.com/file/m9gl54 . I got two forms as controls ValidFormControl1.ascx, ValidFormControl2.ascx <% using (Ajax.BeginForm("CreateValidForm", "Test", new AjaxOptions { HttpMethod = "Post" })) {%> <div id="validationSummary1"> <%= Html.ValidationSummary(true)%> </div> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.Name)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Name)%> <%= Html.ValidationMessageFor(model => model.Name)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Email)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Email)%> <%= Html.ValidationMessageFor(model => model.Email)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Password)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Password)%> <%= Html.ValidationMessageFor(model => model.Password)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.ConfirmPassword)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.ConfirmPassword)%> <%= Html.ValidationMessageFor(model => model.ConfirmPassword)%> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <%= Html.ClientSideValidation<ValidModel>() .UseValidationSummary("validationSummary1", "Please fix the following problems:") %> Both look same the difference is only validation summaryID (validationSummary1, validationSummary2). Both controls are rendered on one page : Form2 <%Html.RenderPartial("~/Views/Test/ValidFormControl2.ascx", null); %> Form1 <%Html.RenderPartial("~/Views/Test/ValidFormControl.ascx", null); %> Validation property First problem, when we have two controls with same type to validate it don’t work becosue html elements are rendered by field name ( so we have two element with same name “Password” ). Only first form will be validated by client side. The worst thing is that even if we have different types and their fields name is same validation won’t work too ( this thing is what I need to repair it will be stupid to name some unique properites for validation ). Is there any solution for this ? Custom attributes validation Next thing custom attributes validation ( All those error are when I use Ajax for on normal form validation is working without problem. ): CompareTo - Simple compare to that is done in mvc template for account model ( class attribute saying with two property will be compared ) , and it wasn’t show on page. To do it I created own CachingRulesProvider with compareRule and my Attribute. Maybe there is more easy way to do it? StringLenght with minimum and maximum value, I won’t describe how I done it but is there any easy whey to do it? Validation summary When I have two two control on page all summary validation information goes to first control validation summary element, even xval generated script say that elementID are different for summary. Any one know how to repair it? Validation Information Is there any option to turn on messages on place where is Html.ValidationMessageFor(model = model.ConfirmPassword). Becsoue for me it isn’t show up. I would like to have summary and near field information too not only red border. Any one know how to do it? Ajax submit Anyone know how to do easy without massive code in javascript to do submit via javascript. This will be used to change input submit to href element (a). Both look same the difference is only validation summaryID

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >