Count Compares

I am new to Java, and not entirely familiar with the built-in functions. I am hoping someone can help with a simple question:
My objective is to create an array of objects, sort them using Arrays.sort(), and search them with BinarySearch(), then analyze the efficiency. I need to count the number of compares and the number of objects in the array to do this.
I have created a class which implements Comparable, but I am not sure how to get the count of compareTo() calls back to the driver program, since it is called from within the sort and search methods.
Cheers!

That's what I was thinking of, except that if I were you, I wouldnt' put that static stuff in a Comparator.
The Comparator can be completely standalone, and keep its own counter variable. And everything could be instance-level (i.e., non-static) in a Comparator. Also also I'd advise not creating a setCounter method -- just set the value in the constructor and increment it in compare(). No need to let some other class mess potentially with the counter.
You only need the static counter and static methods if you want to implement this functionality in the Comparable class, because in that case you have multiple separate objects working on shared state.
The cleaner solution is just to do it all in a Comparator, I think. That keeps everything pretty well-modularized.
For a really clean design, create a wrapper Comparator:
public class CountingComparator implements Comparator {
    private final Comparator wrapped;
    private int count = 0;
    public CountingComparator(Comparator wrapped) {
        this.wrapped = wrapped;
    public int compare(Object o1, Object o2) {
        count++;
        return wrapped.compare(o1, o2);
    public int getCount() {
        return count;
}Then none of your other code, including the wrapped Comparator, needs to know that any counting is going on.

Similar Messages

  • Adding new row to the reports list page

    How can I add a new report row in the reports list of the reports tab.
    Ex: a new row to the report "users by Date of Join report" is to be added
    How can we add Please help me out in this

    I am facing the same problem!
    camickr wrote:
    Try adding an empty row containing a null value for the String instead of the empty String.camickr, it will not help, the DefaultRowSorter in the "*+compare(int model1, int model2)+*" method return -1 if the first value is null and 1 if the sacond value is null. and incase of DESCENDING it mult by -1.
                    // Treat nulls as < then non-null
                    if (v1 == null) {
                        if (v2 == null) {
                            result = 0;
                        } else {
                            result = -1;
                    } else if (v2 == null) {
                        result = 1;
                    } else {
                        result = sortComparators[counter].compare(v1, v2);
                    if (sortOrder == SortOrder.DESCENDING) {
                        result *= -1;
                    }And this is the real problem!
    The empty line is sorted as the smallest value and incase of DESCENDING it will be the first line (because of the mult by -1).
    We could have overide it and incase of the empty row(usualy the last row) do not mult by -1 in DESCENDING mode.
    But the problem is that the "+*compare*+" method and it's caller "*+Row+*" inner class are private :-(
    It is not wise to do it but we can do like kmp83 wrote:
    kmp83  wrote:
    copy/duplicate "private" code from DefaultRowSorter into my extended class.Anyone have another suggestion?

  • Loading display names in array

    Hi,
    I would like comparing registry display names before and after a software installation.
    So the function below is :
    1. loading display names
    2. Then I create manually a registry display names
    3. I load again the display names
    4. And I am running a comparison between previous and after installation.
    The display names, I created is Vcredist2005. So the comparison should return Vcredist2005.
    But I get only the last value of the arrays. Why??
    Function Get-DisplayName {
    Begin {
    [string[]]$regKeyApplications = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
    'HKLM:SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
    Process {
    [psobject[]]$installedApplication = @()
    ForEach ($regKey in $regKeyApplications) {
    $installedApplication += Get-ChildItem $regKey | foreach { Get-ItemProperty $_.PSPath } `
    | select DisplayName `
    | Where {$_.DisplayName -ne $null}| Sort-Object DisplayName
    $installedApplication=$installedApplication | Sort-Object DisplayName
    Write-Output $installedApplication
    End {
    $a=Get-DisplayName
    $a.Count
    #Add a false display name in the registry before continuing running.
    #I added Vcredist2005
    pause
    $b=Get-DisplayName
    $b.Count
    Compare-Object -ReferenceObject $B -DifferenceObject $A
    Thanks,

    When you're using compare-object to compare objects you should specify the property you want to compare:
    Try this:
    Compare-Object -ReferenceObject $B -DifferenceObject $A -Property DisplayName
    Inspired by Carlsberg.

  • Can View improve Performance?

    Hi,
    For improving performance, i have created a view in rpd so that my fact table row count comparing with base fact table reduce from 117888 records to 3263 records. And I am using this view as a fact table and joined with other dimension tables. But I am wondering by doing this will be there be any better performance?
    Thanks,
    Phani.

    Hi,
    I dont think view will help in performance instead go for materialized views.
    Check this.....http://www.biblogs.com/2008/11/28/thoughts-on-obiee-performance-optimization-diagnostics/
    Need help on OBIEE performance
    Regards,
    Srikanth

  • Nokia 5300 battery

    I am having real problem with the Nokia 5300 battery life. I have never expect this type of problem with Nokia phones. I usually encounter this type of problem with Motorola phones. I've bought this phone for 2 weeks and already have to buy a spare battery because the phone battery keeps running out. I use the bluetooth headset sometimes (on standby) other than that I hardly ever talk on the phone and would not dare using it to listen to music since I am worry about the battery. There is no reason why I should charge my phone that often. Not only does the battery not last, it takes 3 - 4 hours to charge. Changing spare battery has not been a easy task too. The back casing is very difficult to open when you have long nails.
    I have been using Nokia phones for the last 10 years, changed 8 different models, and had loved every one of them. This is the first time that I am disappointed.

    Lithium Polymer (Li-Poly) :
    The newest and most advanced technology for cellular phone batteries. This brand new chemistry of battery allows for the most compact cells available. Li-Poly batteries are extremely light and in most cases very thin allowing for the highest battery life for the size. Lithium Polymer batteries share all of the benefits of Li-Ion plus can last up to twice as long.
    Advantages:
    -Very low profile - batteries resembling the profile of a credit card are feasible.
    -Flexible form factor - manufacturers are not bound by standard cell formats. With high volume, any reasonable size can be produced economically.
    -Lightweight - gelled electrolytes enable simplified packaging by eliminating the metal shell.
    -Improved safety - more resistant to overcharge; less chance for electrolyte leakage.
    -Lithium Polymer had lesser power dissipation.
    -Lithium Polymer supports larger capacity even at the same size with Lithium Ion ones.
    Limitations:
    -Lower energy density and decreased cycle count compared to lithium-ion.
    -Expensive to manufacture.
    -No standard sizes. Most cells are produced for high volume consumer markets.
    -Higher cost-to-energy ratio than lithium-ion
    Message Edited by nj15 on 26-Sep-200710:29 PM

  • Type already exists?

    I am using Add-Type but I am getting the error:
    Cannot add type. The type name 'TestSetup' already exists.
    Can I tell if a type already exists and remove it so that I will not get this error?
    Thank you.
    Kevin Burton

    This is way outside of my experience, so please ignore this if this isn't actually helpful.
    I've been playing around with a way to test if a type has been added or not.
    Here's my test code for adding a new type:
    # Get list of currently loaded assemblies
    $before = [appdomain]::currentdomain.getassemblies()
    # Add a new type
    # Example 1 from http://technet.microsoft.com/en-us/library/hh849914.aspx
    $source = @"
    public class BasicTest{ public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); }}
    Add-Type -TypeDefinition $source
    # Get updated list of loaded assemblies
    $after = [appdomain]::currentdomain.getassemblies()
    # Console output with information about the differences in assemblies
    Write-Host "Before: $($before.Count)"
    Write-Host "After: $($after.Count)"
    Compare-Object -ReferenceObject $before -DifferenceObject $after
    Here I'm testing for the type, based on finding the class name:
    # Class name to test for
    $className = 'BasicTest'
    # Get list of currently loaded assemblies
    $loaded = [appdomain]::currentdomain.getassemblies()
    $ErrorActionPreference = 'SilentlyContinue'
    $foundType = $loaded | Where { ($_.GetExportedTypes()).Name -eq $className }
    $ErrorActionPreference = 'Continue'
    If ($foundType) { Write-Host 'Type found' }
    Else { Write-Host 'Type not found' }
    Perhaps I'm totally misunderstanding what you're trying to accomplish and this won't be helpful as all, but this was interesting nonetheless.
    EDIT: Wow, the answer to this ends up being WAY easier than I made it. See below.
    Don't retire TechNet! -
    (Maybe there's still a chance for hope, over 12,225+ strong and growing)

  • Function reference / documentation

    Hi there,
    where can I find a complete "function reference" of CR functions?
    At MSDN (Microsoft Developer Network) I just found the following:
    [http://msdn.microsoft.com/en-us/library/ms225339.aspx]
    But there is only a description of the syntax how to use functions in CR ...
    I need a "function reference" where all functions are listed and described!
    e.g.
    Split(inputString, delmitter, count, compare)
    Can delmitter be a char or even a string, what does the compare paramter etc. OK, this is just a simple example and I can do "try and error" but this isn't the correct way of course and there are a lot of functions available in CR ...
    Since VS2008 the MSDN integration of CR does not work (404 error) ...
    (used VS2005 in the past)
    Thanks in advance,
    hfrmobile

    Wow, thank you for your immediate response
    We're using "Crystal Reports Basic for Visual Studio 2008" at the moment ...
    If I click the "?" button in "Formular Workshop" I just get the following:
    Visual Studio
    Information Not Found
    See Also  Send Feedback
    The information that you are trying to access could not be found. Various events could have caused this error.
    - Broken links
    - No topic in Local Help
    - No F1 Help topic available
    - Online Help is not available
    - Help has not been installed
    - Online Help cannot be accessed because the proxy server cannot authenticate the user
    To report this error, visit the MSDN Product Feedback Center.
    There should be such thing at the SDN?
    --hfrmobile

  • Synchronis​ation Problem

    Have just downloaded updated Desktop Manager software (5.0 bundle 1168) since when synchronisation no longer works. Process starts in normal way, counting & comparing records on device & computer, then goes into screen "Preparing Sync Preview" where it stays. Have left running for many hours but still continues. Unable to stop without closing down entrire software.

    Mercedes Benz have released a software upgrade recently for their Bluetooth systems....but there are no copies of the disc available in the UK....and my local dealership don't know whether it'll solve the problem.....AND it's an 80-minute job for each vehicle for which I'll be invoiced.
    Come on BB, sort this out! Software version 10.1.0.1483 worked just fine.

  • Howto implement timeout

    Ok I have the following problem...
    I have multiple VI's. Most of these VI's contain a loop which can theoratically loop a infinit amount of time. Some VI's which can run infinitly call VI's which can run infinitly. Now my problem is how do I timeout them. 
    I got a few solutions but none that I like. 
    Currently I have the following (not wanted implementation). Each VI has a timeout input. Then inside the VI I check if the VI has timed out. Now this implementation is flawed because of the following. I have A.vi and B.vi. A.vi calls B.vi. A.vi and B.vi have a input timeout. I wire the timeout of A.vi to B.vi. Now the flaw in my current design is that the timeout is sort of relative. Before B.vi is called in A.vi already some time has passed. Thus when B.vi is called in A.vi with that timeout it is possible that while B.vi is running A.vi would have timeout... but this does not happen because B.vi is still running with the same timeout of A, hence gets extended, because the timeout is added with the time when the VI is called and then compared when running. I attachted a sample VI of my current implementation. 
    Now I want to be able to have a more abstract method. Something like a VI which holds the timeout. I was thinking of a functional global... however this would conflict when two VI's are running with different timeouts which both call that VI when they run in parallel. 
    Hopefully someone has a clever idea/solution.
    Attachments:
    A.vi ‏10 KB
    B.vi ‏9 KB

    If A.vi calls B.vi, and you expect B.vi to be done in 100 ms it's naturally impossible for A.vi to be done in 100 ms as well if B.vi times out. You can use the timed elapsed in B output and add it to the time elapsed in A to compare it with the timeout instead. However if B does time out A will still take a bit longer to time out.
    Hmmm wel that would not be possible of course because what when B will execute infinitly...
    If your current approach is as simple as the demo VIs you attached, you may very rarely run into a problem when the Tick Counter rolls over, giving you a much longer timeout than you expect.  (Of course, loops with no wait are also a problem).
    Sounds like what you want is to change your timeout inputs to "Timeout At" inputs, so that it times out at a given time.  Instead of comparing with the Tick Count, compare with Get Date/Time in Seconds (this also solves the rollover problem).  Then you can pass the same Timeout At value from A directly into B.  Alternatively, add the Timeout At input instead of replacing the Timeout, and set the initial value to NaN.  Check if the input is NaN - if so, get the current time in seconds, add the timeout value, and use that as the new Timeout At; otherwise, just use the Timeout At value that was passed in.
    Yes I actually came up with this solution also "Timeout At" idea. But I don't really like it, I was hoping for a more abstract/generic method. Where I could just use the tickcount. 
    The real issue lies in fact with the problem that I can't determine which VI's are going to be called and because they can be executed in parallel. If I could do this I could just create a notifier for that set of VI's which need a timeout check.

  • Digital Integrator

    To whom it may concern,
    I need to design two digital integrators to solve a 2nd order differential equation.  It needs to take both AC/DC.  I've been told that if my input is DC, that my output should be a ramp. If my input is a sine wave the output should be a cosine wave (shifted wave form). The IC's to be used are the following: ADC, DAC, adder, u/d counter, comparator, register.  Not all of these IC's are necessary to make this work.  e.g. One can use just adders and a ADC/DAC to get it to work.
    I'm not very familiar with Digital design, and would appreciate any help or direction in this area.  I've been "playing around" with multisim a bit with no avail.  
    My goal is to design the circuit with multisim, replicate it onto a breadboard, then a PCB. 
    Thanks in advance
    Tom 

    To whom it may concern,
    I need to design two digital integrators to solve a 2nd order differential equation.  It needs to take both AC/DC.  I've been told that if my input is DC, that my output should be a ramp. If my input is a sine wave the output should be a cosine wave (shifted wave form). The IC's to be used are the following: ADC, DAC, adder, u/d counter, comparator, register.  Not all of these IC's are necessary to make this work.  e.g. One can use just adders and a ADC/DAC to get it to work.
    I'm not very familiar with Digital design, and would appreciate any help or direction in this area.  I've been "playing around" with multisim a bit with no avail.  
    My goal is to design the circuit with multisim, replicate it onto a breadboard, then a PCB. 
    Thanks in advance
    Tom 

  • Using a Comparable Class with Treeset, creating counter in comparable clas

    http://rafb.net/paste/results/jibQzk63.html - comparable http://rafb.net/paste/results/Noahue63.html - loading
    http://rafb.net/paste/results/re1Swn60.html - contents of .txt file * sorry the paste is weird lol.
    Trying to List word count in alphabetical order - Already did that
    Having a counter so it counts the number of time that specfic word appeared in the txt file - This is my problem I don't know where to add the counter in my comparable class so it stores a number and adds everytime that same word appears. ex. "and 7" the word "and" appeared 7 times in the .txt file
    so if some1 could help me, would be apperciated. I've like tried everything and getting the opposite results.

    That's just the issue I'm having. My sample code functions as long as the parameterized type being compared isn't Comparable. For example, changing the type to A<Integer,String> works fine.
    I think I may have discovered why this is the case. By declaring A<Comparable,String>, I am implying that the first parameterized type (call it T) is Comparable<T>. As a result, what I need is an A<Comparable<Comparable>, String>; that is, anything which is comparable must be able to be compared to the object. Since Integer is only Comparable<Integer>, it cannot be compared to all Comparable objects and therefore doesn't meet the requirements.
    I'm not used to looking the other way on the inheritance tree. :)
    The original trouble I had with this came from when I was passing a hash code generator into a piece of source and I needed to compare the hashes. The only guarantee I have regarding the hashes is that they are Comparable and I was putting them in a similar Pair structure. I then wanted to build a comparator to compare them but, since they're Comparable<?>, I can't know to what they can be compared... so I'll have to change the contract on the code. ;)
    Thanks. Cheers. :)

  • Comparing counts after conversion: iPhoto to Aperture

    Well, I just finished a major conversion from iPhoto to Aperture. 47,000 photos and videos in a 303 gigabyte iPhoto Library. It was a long and winding road, and I learned a lot about how to compare counts of photos and videos between iPhoto and Aperture. I hope this information helps someone spend a few less hours on the task than I had to.
    After an iPhoto-Aperture library conversion, the first check you'll probably want to do, to confirm all went well, is to compare the number of photos and/or videos reported from each application. You'll probably compare the overall total, and/or the total for important subgroups (say, all photos keyworded "family".) Here are some things to be aware of:
    - You can run iPhoto and Aperture at the same time, even if Aperture is referencing the photos in their iPhoto library locations. This can make various count comparisons easy. Sometimes though I found the apps suddenly bogged down, and I had to quit one of the two to recover (this was on a 4GB 2.93 GHz iMac).
    - Whether your Aperture "stacks" are open or closed affects the photo count reported by Aperture. If you edit an original photo in iPhoto, in the end all you see is edited photo, the original is preserved but tucked away unseen. In terms of a photo count, you still have just one photo. When this photo is imported into Aperture, it comes in as a 2-photo stack (original & edited). If you stacks are closed, your counts should match; if your stacks are open, Aperture will be higher.
    - Photos "hidden" in iPhoto come in as "rejects" in Aperture (i.e. a rating of "X" on a scale of X,1,2,3,4 or 5 stars). When the search box in Aperture says "Showing All," you are including the rejects in the count (that is, the count appearing at the bottom of the window in browser mode). If it says "Unrated or better," the rejects are not being counted. Make sure you are consistently including or excluding hidden/rejects when comparing numbers.
    - Formats supported by iPhoto but not by Aperture. I have some old (pre-OS X) screenshots in PICT format. Viewable just fine in iPhoto, but they do not get imported into Aperture.
    - Some video formats (in my case, MPEG1 Muxed) are imported into Aperture, but are not playable within Aperture, and do not show up if you filter on File Type = Video (that last part seems just plain wrong behavior).
    - Every count I saw in Aperture included videos, even when the count was labeled "Photos" (e.g. "23,434 Photos"—you'll see this under Projects, if you group by folder)
    - I did have a few items that were *just plain skipped*, with no error dialog, by the import. Scary. But in every case, there was evidence of a problem in iPhoto: I would see a fine thumbnail, but if I tried to open the photo or video, I'd see a gray exclamation point where the photo/video should appear. In every case I successfully found an valid original (in the iPhoto "Originals" folder) and moved it manually into Aperture. Problem is, are you going to try and view every photo you have in iPhoto, checking for exclamation points? I tracked my missing photos/videos down by painstakingly comparing counts in matching slices of time (say, August 2006) in iPhoto and Aperture. When I narrowed a count discrepancy to a set of 100 pics or so, I compared thumbnails between the 2 apps until I found the item missing from Aperture. Not fun.
    I hope this helps somebody. Now that I've made the switch, I have a love-hate relationship with Aperture. Mostly love. But that is a separate post. Aperture is also my first Pro app from Apple, and iPhoto and Aperture make a fascinating case study in contrasting user interface design (freedom from choice vs. options galore). Also a topic for another post.
    Mike M

    Hey, thanks for the comprehensive post. It helped me quite a bit and probably saved me a lot of time; I'm sure it did the same to a lot of people who didn't have an account here as well.

  • Compare text in one cell to a range of cells, get interger count of values

    Hi there,
    Basically what I'd like to do is, as a value in one cell, compare the text in a second cell to a range of third cells, and get a count of "hits".
    EXACT(second,third) will compare two cells, return a boolean. How do I batch run EXACT, and force boolean values into integers.
    Conceptually:
    For each J2:J14;$X=$X+INT(EXACT(B2,$_);return $X
    Can this be done in Numbers?

    Nevermind; the following works:
    =COUNTIF(($J2:$J14),B1)

  • Comparing count of one table with another

    Hi,
    I want to compare the number of rows in three tables with the number of rows in another table and see if they are equal
    Here is what I have so far:
    SELECT decode(the_count,100,1,0) from (select sum(num_rows) as the_count from user_tables where table_name in('LOCATION','DEPARTMENT','JOB'));
    This compares the number of rows with 100. If they equal 100m, then 1 is displayed, otherwise 0.
    I want to compare the_count with the result of select(num_rows) as other_count from user_tables where table_name='EMPLOYEE';
    Any suggestions?

    it is better to use the actual table.
      select decode(cnt1.the_count,cnt2.other_count,'Number of rows equal','Number of rows not equal') comment
        from (select sum(row_cnt) the_count
                from (select count(*) row_cnt
                        from job
                      union all
                      select count(*) row_cnt
                        from salary_grade)) cnt1
              select count(*) other_count
                from price) cnt2;

  • How to get count,index and compare to arraylists

    hi
    how to get count,index and comparing of 2 arraylist.... plz suggest me asap...

    How is your question related to JDBC? And what have you done so far with your code?

Maybe you are looking for

  • Do I have a chance at FHA automatic underwriting approval?

    Here's my situation:  Long but please read and help :-) I recently sold my home in GA and relocated back to CA.  I had my current mortgage for only 18 months before relocation and have had zero missed payments.  When I called my current morgage broke

  • Oracle XML Publisher Java API's showing arabic characters as question marks

    Hi All, I have created a custom xml publisher report. All the setups in xdo.cfg and the fonts have been installed. When i run the report as concurrent program using the XDODTEXE as the executable this report executes fine displaying the arabic charac

  • My iBook library is empty

    My iBook library shelves are empty. When I tap on the iBook icon, the previously filled shelves appear and are empty. The screen then arbitrarily goes to blank book pages that won't turn. Also, there are nom icons at the top of either the shelves or

  • Oracle Datawarehousing training

    Please let me know any institute that offers training on Oracle Express/Datawarehousing, since there is a immediate requirement for a project. Kindly treat this mail as urgent and post me a reply to this forum.

  • My icloud e-mail won't come online.  Keeps telling me there's a user/password error

    I'm trying to bring my email online but I keep getting the same messge that icloud can't connect.  When I run online doctor, it says the connection to the internet is good but all the red dots have a user/password error.  I've gone through every pass