Finding Mode of an array of numbers.

I'm having troubles with finding the mode of an array of numbers.
When the mode is in the middle of the set of numbers, it works, but when it is at the end, it doesnt.
For example..
if i had the numbers ...
2,3,3,4,5,6,6,6 in an array, it would tell me that the mode is 3.
if i had the numbers...
2,4,5,5,5,6 in an array, it would tell me that the mode is 5.
So the first set of numbers, the mode is incorrect, but the second set of numbers is correct.
The following is my code...
public static int getMode(int[] list)
int mode = 0;
int elements = 0;
int tempMode = list[0];
int temp = 1;
for(int x = 1; x < list.length; x++)
if(list[x-1] == list[x])
temp++;
}else{
if(temp > elements)
System.out.println("entered");
tempMode = list[x-1];
elements = temp;
temp = 1;
}else{
temp = 1;
mode = tempMode;
return mode;
}

You need to add another test at the end of the loop:
    public static int getMode(int[] list)
        int mode = 0;
        int elements = 0;
        int tempMode = list[0];
        int temp = 1;
        int x;
        for (x = 1; x < list.length; x++)
            if (list[x - 1] == list[x])
                temp++;
            else
                if (temp > elements)
                    tempMode = list[x - 1];
                    elements = temp;
                    temp = 1;
                else
                    temp = 1;
        if (temp > elements)
            tempMode = list[x - 1];
        mode = tempMode;
        return mode;

Similar Messages

  • Finding mode

    I am trying to figure out some coding on how to find mode for an array of
    integers? How do I go about the coding for finding mode?
    Thank you.

    Cross/duplicate-posted http://forum.java.sun.com/thread.jsp?thread=470485&forum=54&message=2170864

  • Need help with ouput of a list or array of numbers input from user

    I'm only a few weeks into learning java, so this may seem simple to some, but...
    I am trying to write a program that will receive numbers from a user,
    and then list, add, average those numbers. I've got the program to
    work except for listing the numbers that were input.
    Can someone help guide me????
    i've left the code I've tried in as comments.
    Enter an integer value, the program exits if the input is 0:
    20
    Enter an integer value, the program exits if the input is 0:
    40
    Enter an integer value, the program exits if the input is 0:
    60
    Enter an integer value, the program exits if the input is 0:
    80
    Enter an integer value, the program exits if the input is 0:
    0
    Total numbers entered: 4
    The array of numbers is: 0 0 0 0
    The sum is 200
    The average is 50
    The maximum number is 0
    The minimum is 0
    Here is my code:
    * Title:        Reads integers and finds the total, average, maximum of the input values
    * Description:
    * Copyright:    Copyright (c) 2002
    * Company:      Duke Court.
    * @author Mary Davenport
    * @version 1.0
    public class part3page6
      public static void main(String[] args)
      int data = 0;
      int sum = 0;
      int countnum = -1;
      int maximum = 0;
      int minimum = 0;
      int average = (countnum - 1);
      do
          System.out.println("Enter an integer value, " +
            " the program exits if the input is 0:  ");
          data = MyInput.readInt();
          sum += data;
          countnum++;
        } while (data != 0);
          //in order to figure the max & the min it appears that the
        //program will need to utilize arrays to store the individual numbers
        //that are input from the user.
        //create an array of the input data
        int[] number = new int[countnum];
        //creat a list of the input data
        int []myList = {data};
        //lists how many numbers entered
        System.out.println("Total numbers entered:  " + number.length);
        //list array of numbers -- this is giving me [I@3179c3,
        //instead of 20, 40, 60, 80 when I use "new int[countnum]"
    //     System.out.print("The array of numbers is: "
    //      + new int[countnum]);
        //list array of numbers:  this is giving me " 0 0 0 0 "
           //instead of 20, 40, 60, 80  with the following for statement
           // (number[i] + " ")
        System.out.print("The array of numbers is: ");
          for(int i=0; i<number.length; i++)
            System.out.print(number[i] + "  ");
      //list mylist of numbers from input, 20, 40, 60, 80
      //output is The list of numbers is: [I@3179c3
    //  System.out.print("The list of numbers is: " + myList);
        System.out.println();
        System.out.println("The sum is " +  sum);
        average = sum/countnum;
        System.out.println("The average is " + average);
        System.out.println("The maximum number is " +  maximum);
        System.out.println("The minimum is " +  minimum);

    When you input the data you need to save it to the array. Currently you are not saving the value you are just adding it
    ArrayList nums = new ArrayList();
       do
           System.out.println("Enter an integer value, " +
             " the program exits if the input is 0:  ");
           data = MyInput.readInt();
    nums.add(new Integer(data));
           sum += data;
           countnum++;
         } while (data != 0);

  • Summing and Finding Maximum in 2d array

    So I have an 2d array of numbers and I am trying to find the maximum sum of the rows and give back the row number. So far I can get the sum and the maximum number but I need to give back the row number of the maximum value.
    public static void RowSumRow (int[][] table)
          static int sum[] = new int[5];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          System.out.println("The maximal revenue is $" + max + " at region " + region);
        }myMethods.maximumSearch
    public static int maximumSearch(int a[])
         int Max = a[0];
         for (int index=0; index < a.length; index++)
             if(Max < a[index])
              Max = a[index];
            return Max;
       }

    this is correct right?
    (the prarmeter rows is the rows that are to be tested)
    public static void RowSumRow (int[][] table, int rows)
          int sum[] = new int[rows];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          for(int x=0; x < sum.length; x++)
              if (max == sum[x])
                region = x-1;
          System.out.println("The maximal revenue is $" + sum[region] + " at region " + region);
        }This does what I want it to do right? Ive tested a few times and it is working, but is it logically correct?

  • OCR - array of numbers

    Hello
    I am beginner in image processing and I  need sugestion how to create array of numbers from image.
    So far I ve processed this:
    to that:
    in vision builder.
    Now I should divide this square into 9x9 smaller and then run OCR in each of them?
    And what about size of the base numbers in OCR, should I create instances of the same number (depending on size?)
    Thanks for help

    I ve done that in 6 steps starting from:
    1) color plane extraction HSL
    2)Local Threashold Background Correction  look for dark objects 11x11
    3)Binary image conversion
    4)Adv Morphology remove border objecst
    5)Lookup table Equalize and 4x find straight edge
    but sometimes after morphology i get that:
    depending on foto quality
    thanks for some suggestions

  • What is the best way to get the minimum or maximum value from an Array of numbers?

    Let's say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]
    What is the best way to find the minimum or maximum value in
    that Array?
    Right now, to get the maximum, I am looping through the
    Array, and resetting a variable to the value if it is greater than
    the existing value:

    Here's other approaches, the cookbook is your friend:
    http://digitalmedia.oreilly.com/pub/a/oreilly/digitalmedia/helpcenter/actionscript30cookbo ok/chapter5.html?page=7
    enjoy.

  • How to escape a single quote in a find mode view

    Hello,
    I'm working with JDeveloper 10g.
    I've defined a view that is used in "find mode" in a JSP.
    When a value with a single quote is inserted in a field of the search form, an exception is thrown:
    JBO-27122: SQL error during statement preparation.
    ORA-00907: missing right parenthesis.
    The problem is that the "single quote" is not being escaped:
    WHERE STREET LIKE 'ABAT ESCARRE, DE L'A'
    How could I force the view to escape the "single quote"?
    Thanks

    Arrest the single quote by calling a javascript method.
    This might help you
    Re: af:clientListener javascript function call question
    http://download.oracle.com/docs/cd/E12839_01/apirefs.1111/e12419/tagdoc/af_clientListener.html
    Edited by: Srinidhi on Mar 23, 2011 3:46 PM

  • Problem with "find" mode in adf/swing application

    Hi all,
    I'm working on ADF Swing application which uses MS SQL Server 2005 (JDeveloper 10g 10.1.3)
    I think that my issue might be well-known…sorry if it has been already discussed somewhere else…
    I have a problem with the “find” mode for a detail panel in a master-detail form…(To make it clear the “find” mode is switched on when clicking on the special button on a navigation panel).
    So this mode works well in a master panel, but it demonstrates strange behavior on a detail panel, i.e. it takes me two attempts to find the necessary child object and it doesn’t switch back in a simple way from this mode to the normal mode….say if we are in the department 10 (Dept is a master form) we can’t simply find KING employee (Emp is a detail form)…is there any workaround for this?
    Thanks in advance. Alex.

    Hi Frank, please look this issue

  • Open Purchase Order Form in Find Mode

    Hi,
    I have to open the Purchase Order Form in Find Mode.How to open in Find mode?.
    I Used the Following Code in Form_Load  && Action_Success=true
    if(oForm.Mode = SAPbouiCOM.BoFormMode.fm_ADD_MODE)
            oForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE
    But it is not working.Please help me to solve this.
    Regards,
    M.Dhivya

    call
    ActivateMenuItem( "1281")
    in application object.

  • How to disable a Entire row in a Matrix in Find Mode (User Form)

    Hi,
    How to disable a Entire row in a Matrix in Find Mode (User Form)
    Regards
    Jambu

    Hi,
       Iam using Bubble event = false in click event but the matrix row
    is allow to edit but we cant save the document in Find Mode That is fine.
    What is my actual requirement is In find mode matrix Row not allow to enter the data .
    For examble In ADD mode i enter the data in Three rows (Item Section - Matrix) and
    save the document. Whwn i open the document in find mode the three row is not allow
    to editable like the same functionality of PO, sales Order, etc ..
    Regards
    Jambu

  • How to look at a query string from Nav Bar Find Mode

    I would like to view the resultant query string from the Navigavtion Bar's Find Mode. I am using a Master/Detail and am querying with the selection criteria from the detail only.
    I am getting unexpected results, and would just like to SEE what the query string IS.
    Thanks

    I am getting unexpected results, and would just like to SEE what the query string IS.Run your app with diagnostic output turned on. Here's the instructions for that.
    To turn on diagnostic, go to the IDE,
    1. Select the project.
    2. Do right mouse click and select "Project Settings..."
    3. On the Settings dialog, select Configurations/Runner.
    4. In the righthand side pane, you should see a textbox for "Java
    Options". Please add the following JVM switch:
    -Djbo.debugoutput=console
    Then, rerun. The run command should include
    -Djbo.debugoutput=console as in
    "D:\JDev9i\jdk\bin\javaw.exe" -Djbo.debugoutput=console -classpath ...
    You should now see a lot more output on the IDE's message window.
    This should also include the findmode query that gets built after you hit the execute button from a findmode panel.

  • ADF Faces w/ADF BC: Bug(?) w/null values in drop down list in find mode

    Using JDev 10.1.3.0.4.
    I have a page that shows a single record. The user can toggle between regular and Find mode to enter query by example criteria.
    One of the fields has been bound to a dynamic list. The "No Selection" Item in the List Binding Editor is set to "Selection Required".
    When editing a record, this list does not have an empty item. When the user enters find mode, the list has an empty item in the list - which makes sense since the user might not want to search on a value in that particular field.
    However, if the user enters find mode, selects an item from the list, executes the query (Execute action), and enters find mode again then the empty item no longer shows up in the list. Is this a bug?
    (Note - there is an easy workaround - if you delete and create in find mode, then the new critieria record has the list fixed with an empty item in it.)

    Using JDev 10.1.3.0.4.
    I have a page that shows a single record. The user can toggle between regular and Find mode to enter query by example criteria.
    One of the fields has been bound to a dynamic list. The "No Selection" Item in the List Binding Editor is set to "Selection Required".
    When editing a record, this list does not have an empty item. When the user enters find mode, the list has an empty item in the list - which makes sense since the user might not want to search on a value in that particular field.
    However, if the user enters find mode, selects an item from the list, executes the query (Execute action), and enters find mode again then the empty item no longer shows up in the list. Is this a bug?
    (Note - there is an easy workaround - if you delete and create in find mode, then the new critieria record has the list fixed with an empty item in it.)

  • How to find WBS-Elements of CO-DOC-Numbers

    Hi,
    I need to know, whether a wbs element exists for a CO doc number / CO item number, or not.
    I have to create an extractor to load the doc number - wbs element mapping into BI.
    Do someone have some R/3 table proposals?
    Exists a meta data repository like in BI or a used-in function for R/3?
    DataSource 0WBS_ELEMNT_ATTR extracts wbs elements as field POSID.
    DataSource 0CO_OM_CCA_9 extracts CO doc number as field BELNR.
    DataSource 0CO_OM_CCA_9 extracts CO item number as field BUZEI.
    Field 0AUXACCVAL is not useable in case of error in R/3: PM orders with wbs elements will not get an valid 0AUXACCVAL value.
    Thanks and regards,
    Wolfgang

    warnerja wrote:
    flounder wrote:
    DrLaszloJamf wrote:
    You mean x.length?<pbs>
    Depends upon your interpretation of "number of elements in the array"
    int[] numbers = new int[10];
    numbers[0] = 42;
    numbers[1] = 666;Number of elements in the array is 2 not 10.
    </pbs>If you used something other than a primitive type for the array element type you could have a case. A value of integer zero for the other elements is still a value, so there are indeed 10 elements there.Even if it were not primitive, every element would have a value. That value would either be null or a reference.

  • How do I convert a 1-D array of cluster of 5 elements into a 2-D array of numbers? (history data from a chart)

    Hello,
    in my vi I have a chart with 5 Plots displaying measurement data.
    The user should be able to save all the history data from the chart at anytime. (e.g. the user watches the chart and some event happens, then he presses a "save"-button)
    I know, that I can read out the history data with a property node. That is not the problem. The problem is, how do I handle the data? The type of the history data is a 1-D array of cluster of 5 elements.
    I have to convert that data somehow into a 2 D-array of numbers or strings, so that I can easily save it in a text-file.
    How do I convert a 1-D array of cluster of 5 elements into a 2-D array of numbers?
    I use LabVIEW 7.1
    Johannes
    Greetings Johannes
    Using LabVIEW 7.1 and 2009 recently
    Solved!
    Go to Solution.

    Gerd,
    thank you for the quick response and the easy solution.
    Look what I did in the meantime. I solved the problem too, but muuuch more complicate :-)
    And I have converted the numbers to strings, so that I can easily write them into a spreasheet file.
    Johannes
    Message Edited by johanneshoer on 04-28-2009 10:39 AM
    Greetings Johannes
    Using LabVIEW 7.1 and 2009 recently
    Attachments:
    SaveChartHistory.JPG ‏57 KB
    SaveChartHistory.JPG ‏57 KB

  • How to use CFL in Business Partners Master in Find Mode

    Hi,
    I have a problem in Business Partners Master Form. I need add conditions in Choose From List in Find Mode when I set an asterisk in the CardCode TextField for filtering the businnes partners list.
    When I capture the et_CHOOSE_FROM_LIST itemEvent in BeforeAction, I can't get the ChooseFromList ID for adding the conditions in the ChooseFromList Object.
    Sample Code:
    Public Sub ItemEvent(ByVal FormUID As String, pVal As SAPbouiCOM.IItemEvent, BubbleEvent As Boolean)
          Select Case pVal.EventType
                Case et_CHOOSE_FROM_LIST:
                    Dim lcflE As SAPbouiCOM.ChooseFromListEvent
                    Dim id As String
                    Set lcflE = pVal
                    id = lcflE.ChooseFromListUID -> The ID is "-1"
          End If
    End Sub
    Thank's in advance
    Best Regards

    Hello Rafea,
    if you can't get it via lcflE.ChooseFromListUID -> The ID is "-1",I guess you need to know choosefromlist UID by test one by one with oForm.ChooseFromLists.Item(i). Or you can save the fom as xml then chech the CFL UID.
    If pVal.FormType = 139 And pVal.EventType = SAPbouiCOM.BoEventTypes.et_CHOOSE_FROM_LIST Then
                If pVal.ItemUID = "4" Then
                    If pVal.InnerEvent And pVal.Before_Action Then
                        BubbleEvent = False
                        Dim oForm As SAPbouiCOM.Form
                        oForm = SBO_Application.Forms.Item(FormUID)
                        Dim oCons As SAPbouiCOM.Conditions                   
                        Dim oCFL As SAPbouiCOM.ChooseFromList
                        'oCFL = oCFLs.Add(oCFLCreationParams)
                        oCFL = oForm.ChooseFromLists.Item("2")
                        oCons = oCFL.GetConditions()
                        'Note: Add the condition only once.
                        If 0 = oCons.Count Then
                            Dim oCon As SAPbouiCOM.Condition
                            oCon = oCons.Add()
                            oCon.Alias = "Cardcode"
                            oCon.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL
                            oCon.CondVal = "C0001"
                            'Set your own condition here instead of the system conditions
                            oCFL.SetConditions(oCons)
                        End If
                        BubbleEvent = True
                    End If
                End If
            End If
    Kind Regards
    -Yatsea

Maybe you are looking for