Code to sort un-common elements in arrays

the code which i made so far
class ArraySetExample
     public static void main (String [] args)
          String rainbow [] = {"red","orange","yellow","green","blue","indigo","violet"};
          String flag [] = {"red","white","blue"};
          // To printout the set of common colours in flag and rainbow
          System.out.println("the set of rainbow colours in the national flag");
          for (int i=0; i<flag.length;i++)
             for (int j=0; j<rainbow.length;j++)
                     if (flag.equals(rainbow[j])) System.out.println(flag[i]);
now i want to add String flagcolours[] // colours which are in flag but not in rainbow
          String rainbowcolours[] // colours which are in rainbow but not flagthe logic which i thought isflagcolours.addAll(rainbow);
          flagcolours.removeAll(flag);
                    rainbowcolours.addAll(flag);
                    rainbowcolours.removeAll(rainbow);but i want a code in arrays. can someone sort my missing code or anything if I have done wrongclass ArraySetExample
     public static void main (String [] args)
          String rainbow [] = {"red","orange","yellow","green","blue","indigo","violet"};
          String flag [] = {"red","white","blue"};
          String flagcolours[]; // colours which are in flag but not in rainbow
          String rainbowcolours[]; // colours which are in rainbow but not flag
          // To printout the set of colours in flag and rainbow
          System.out.println("the set of rainbow colours in the national flag");
          for (int i=0; i<flag.length;i++)
          for (int j=0; j<rainbow.length;j++)
               if (flag[i].equals(rainbow[j])) System.out.println(flag[i]);
               //............MISSING CODE.............
Edited by: crystalarun on Oct 21, 2007 8:13 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Then you will probably need to create a new array for each intersection and using nested for loops add items to your arrays depending on whether they are in one array and not in another by checking in an if-block. First work out what you would do on paper, then translate this to java. It's not hard once you see the solution on paper.
Good luck.

Similar Messages

  • Sort Second Element in Array of Strict Type Def Clusters

    I need to sort the an array of strict type def clusters by the second or third element in the cluster.  In the past I have used 1-D array sort and sorted by the first element of the cluster.  When I need to sort by the second, third, or fourth element of the cluster I just break down the cluster and rebuild it placing the desired sort element in the first position of the new cluster.  This works for simple tasks and clusters, but as the cluster gets more complicated this becomes a pain to do this.  There must be a cleaner way to sort by other elements within the original array of strict type def clusters.  Has anyone succeeded in doing this a different way?

    Hello,
    Here's the way I would do it...just create a new cluster array, where each cluster contains two elements...the unbundled item you want to sort by, and the cluster itself.  Then sort the new cluster array, then unbundle the sorted cluster array to get the original clusters (now sorted).  Here is a screenshot:
    There may be a better way, but this is the first thing I thought of.
    -D
    Message Edited by Darren on 03-16-200610:00 AM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Sorted_cluster.jpg ‏30 KB

  • Merging elements of array

    Hi,
    I am new to programming.
    I have a sensor that sends a data stream through a serial port. I have collect all that data in a 1D unsigned byte array. Now, lets say my 1-D array is [12][45][65][12]...... where each "[ ]"  is a element of the array. Now to make sense of this data what i need to do is merge two elements the array and multipy it by 2/(2^15). i.e. My converted data should by [1245]*2/(2^15). Basically 2 bytes together makes sense. I can do a simple add of each element. Also the other problem is,data from the sensor is a stored as the 1-D array  of unsigned byte. However, the converted data is supposed to be signed 16-bit integer.
    Please give any suggestions on how to go about doing this.
    Siddhant Shah

    Another option is "decimate&Join". (Here it is easy to change the byte order if needed).
    Message Edited by altenbach on 12-15-2008 06:28 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    8bitTo16BitByteOrder.png ‏5 KB

  • Sort(); changes key numbers of array

    Hello!
    I have a question about using function sort();
    I set the initial key of array to be 1 (instead of default 0). Everything goes OK until I sort the array. After sorting the array initial key value sets itself back to zero.
    Here is the example:
    <?php
    $var = array(1 => "Good", "Better", "The Best");
    foreach ($var as $index => $value)
         echo $index." - ".$value."<br />";
    sort($var);
    foreach ($var as $index => $value)
         echo "<br />".$index." - ".$value;
    ?>
    How to avoid the change of the initial array key?
    The output should be:
    1 - Better
    2 - Good
    3 - The Best

    DissidentPJ wrote:
    I have a question about using function sort();
    I set the initial key of array to be 1 (instead of default 0). Everything goes OK until I sort the array. After sorting the array initial key value sets itself back to zero.
    Yes, of course, it will. If you read the PHP manual page for sort(), it says quite clearly "This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys."
    PHP has a large number of sort functions to handle a variety of requirements. However, what you want to do is to reorder the values AND renumber the keys. The simple way to do it is to use sort(), which puts the values in the right order starting at 0. Just add 1 to the key when you use it.

  • Sorting values added to an array

    Hi,
    I've written some code to sort value in an array as I add them, but I can't get it to work properly. So far I have:
    public boolean add(int next)
            int last, temp, previous;
            if (size < 1) // checks whether any values have been added to determine correct value for previous.
                previous = size;
            else
                previous = size - 1;
            if (size < arraySize) //determines whether array is full or not
                last = numberList[previous];
                if (next > last)
                    numberList[size] = next;
                    size++;
                else if (next < last)
                    temp = last;
                    numberList[previous] = next;
                    numberList[size] = temp;
                    size++;
                numberAdded = true;
                return numberAdded;
            }Which does add the numbers, but they aren't arranged into the proper order. When I look over it I can't see anything that stands out as being wrong, so I was wondering whether anybody could see anything?
    Thanks for your help,

    endasil wrote:
    nickd_101 wrote:
    I don't want a loop in this case, as i want to put the values into the correct position (with respect to the previous one) as they're added into the array. Basically, my idea is that the previous value is checked against the new value and then they are swapped if the previous value is larger than the new or kept as is if not.So you're saying that if you added
    1, 2, 4, 5, 3
    you'd want the resultant order to be
    1, 2, 4, 3, 5?
    Because by your logic that's what would happen. The most that can ever happen by your logic is that a new entry would be at most 1 away from the end of the array.
    P.S. use an SortedSet, given that your code doesn't allow duplicate values anyway.
    Edited by: endasil on Nov 19, 2007 2:15 PMThanks for the response. What I meant is that I would eventually want it in ascending order 1,2,3,4,5. What I thought I was doing was sorting the comparing the new value with the preceding everytime a number was added so that it would always go in consecutive order. So, for example say the numbers were added to the array one by one in the order 3,5,4,1,2; 3 would be compared to 5 and there would be no change in the position. As i've typed this out i've just realised the massive logical error i've made! Could you point me in the right direction to get this to work as i'm new to this. I've managed to get a pre-defined array sorting as normal, but for this i need to sort everytime I add a new value?
    Thanks again

  • Code for how to read an integer array from the command prompt...

    hello,
    Could anyone give me the code for how to read an integer array from the command prompt...its very urgent!..

    If you are using a recent version of Java (5 or later) you can use Scanner:
    http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
    That page has some example code on it, too.

  • Revel sorts differently than Elements. How can I fix this?

    I have many photos uploaded in Revel now but see the sort according to the file date instead of the EXIF exposure date on some of the photos. These were scanned photos. The probable cause is that for these photos I set only a date but no time in the organizer. I suspect that therefore Revel's sort falls back to the file date.
    I'd like to fix this for the photos in the organizer. But I did not find a search criteria to find photos w/o a time set or set to "unknown". I have therefore 3 questions:
    1) is my assumption correct?
    2) when I change the photo's time will Revel detect that change? (date is unchanged)
    3) how can I find the photos that have a date set but no time set?
    Thanks

    Today, I found out that the sorting in may Elements 12 catalog is already incorrect. In my old Elements 9 catalog the sorting is correct. It was converted to elements 12 catalog upon installation of elements 12.
    So, I think probably the catalog conversion has a bug. It should tolerate incomplete date/times, i.e. datatimes w/o time, w/o day and time, w/o month/day and time, just as the sorting in elements 9 did.
    Any idea how to fix that (on my side)?

  • The prefix mx for element mx:Array is not bound

    Hi All
    I have a component:
    <?xml version="1.0" encoding="utf-8"?>
      <mx:Array id="arr">
        <mx:Object label="Flex"
          thumbnailImage="http:/someURL"
          fullImage="http://someURL" />
      </mx:Array>
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
    </mx:Canvas>
    This gives me an error
    The prefix "mx" for element "mx:Array" is not bound
    I need a root element here, but I cannot use mx:Canvas, what would be the best choice?
    cheers
    Luca

    Hi Luca,
    Try to put the Array inside your canvas rather than outside ...
    <?xml version="1.0" encoding="utf-8"?
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Array id="arr">
        <mx:Object label="Flex"
          thumbnailImage="http:/someURL"
          fullImage="http://someURL" />
      </mx:Array>
    </mx:Canvas>
    Why  you dont want to use mx:Canvas as root tag of your component.. ?? However which ever component you use try to put the <mx:Array/> inside your root tag of your component, otherwise you will be thrown the same error as mentioned. The error occurs as the the compiler doesn't recognize the namespace mx for the array since you declared it outside the root tag of your component.
    Thanks,
    Bhasker

  • Remove element from array

    hi
    if i have an array
    eg
    int[] array = {4,2,1,2,1};
    how to i remove the index 2 from it and create a new array?
    thanks

    You can't remove the element--an array's size is fixed at creation.
    If you want a new array, create a new one that's one element smaller, then use System.arrayCopy to copy the elements you want to keep.

  • Redemption code for Adobe photoshop/premiere elements 11 does not work

    redemption code for Adobe photoshop/premiere elements 11 does not work

    I am having the same issue except that my premiere elements code worked great, but the photoshop elements key failed. Ugh.

  • How do I remove an identical background / common element from a series of layers/images.

    Hello and good day,
    I have found dozens of articles on how to remove the uncommon items from a series of near identical photos, for instance removing tourists from a series of shots using Scripts -> Statistics...
    What I am trying to do is the exact opposite of this.
    I would like to compare a series of frames, and remove all common elements from them; leaving only differences.  I figured I would be able to use the statistics script to get the common background, then somehow compare it to each frame and remove the common background.  Basically doing a reverse green screen when I am removing the background instead of adding it.
    I have Adobe Master Collection CS6.
    Regards,
    Jeffrey Taylor

    That sounds like something AstroPhotographers might use.  We have an expert here, but I believe he is kind of busy right now, but he might happen along.
    Otherwise, I don't know how to do a reverse Median effect.  You can do it with two layers by aligning and setting the top layer blend mode to Difference, but identical features go black.  You'd have to make a luminosity mask from that frame and apply it to a layer mask to leave the people after returning the layer mode to normal.    But I can't think how to do it with a lot of frames together.

  • DSEE 7 error code 12 - Sort Response Control for server side sort

    I am using Sun DSEE 7, My application works fine for small data set (e.g. 1000) and gives me correct sorted result, but same code fails for large data set (e.g. 656000). I find that for large data set, I am getting the error "*javax.naming.OperationNotSupportedException: [LDAP: error code 12 - Sort Response Control];*". I have changed the look-throught-limit, size-limit and time-limit values to unlimited using dsconf utility. I changed db cache size, entry cache size to appropriate values and also i increased all-id-threshold, all-ids-threshold-eq, all-ids-threshold-pres to the max possible value (2147483646) for one index attribute which i am using in my query but still exception is coming. If i change my client code (Java code using JNDI) to use Context.NONCRITICAL for SortControl, the sorted result is coming fine for small data set (access log shows query as indexed) but result is not sorted for large dataset and also i see the query is now unindexed. I am using only one attribute for sorting. Please help me out what configuration i am missing here.

    Exactly. There is no reason to have the LDAP server sort the
    results during the retrieval.
    Query of Query can be used such as:
    <cfldap name="ldapResults" .....> <!--- Do the LDAP
    query first --->
    <cfquery dbtype="query" name="sortedResults">
    SELECT
    FROM
    ldapResults
    ORDER BY
    sprintcompany
    ,sprintpocrole
    ,sn
    </cfquery>
    Then, use the "sortedResults" query for the rest of your
    processing.

  • How can i retrieve missing element in array

    how can i retrieve missing element in arrays if array length is exceeded

    Not sure about what the question means, but could it be that OP is not aware that the first element in an array is at index 0 (not 1) ?
    <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html" style="background:url(http://java.sun.com/docs/books/tutorial/figures/java/objects-tenElementArray.gif) no-repeat; width:400; height:145;"></a>

  • Code for find the missing number in array without sorting/comparing in java

    Hi all,
    We have 1 to 100 number in an array, but one number is missing (from 1 to 100). we have to find it out without sorting or comparing of this missing number in array.
    please help me out to find the solution this query.
    regards & thanks
    Mohan Kumar
    Bangalore,
    India

    Maybe you could sum up the numbers you've got in your array and subtract the result from 5050 [the term [code](N*N+N)/2 where N is your upper bound (i.e. 100)]. You'll get the sum of all missing values (which in this case would be exactly the missing number). n.b. that you could genaeralize on that for arbitrary finite series.
    Kind Regards,

  • My PriorityQueue doesn't seem to sort it's elements correctly ....

    Hi, here is my semi-complete program, I have removed the methods that were irrelevant to make things simple. The program is supposed to represent Graphs, and minimal spanning trees. I first have to put edges in a priority queue of type : PQEntry (Below), which are to be sorted by their 'distance'. I have not included the interfaces as they weren't necessary here (all methods are already implemented). There is no compile error, but for example when I run the program, and enter 'mst' (it shoud print the contents of the Priority Queue in the order of their distances), it puts the first few elements in order but fails to do so on the remaining elements. below is a sample run.
    graph> init
    graph> mst
    [(4 5) = 51
    , (12 14) = 51
    , (7 9) = 70
    , (10 11) = 60
    , (8 9) = 75
    , (7 8) = 100
    , (3 4) = 90
    , (9 10) = 95
    , (4 7) = 151
    , (15 16) = 110
    , (5 6) = 151
    , (11 5) = 600
    , (11 12) = 151
    , (11 13) = 200
    , (12 13) = 100
    , (3 7) = 300
    , (13 15) = 200
    , (13 16) = 200
    , (14 15) = 170
    , (10 4) = 400
    , (14 16) = 251
    graph>
    class PQEntry implements Comparable {
         int node1 , node2 , distance;
         public PQEntry(int node1 , int node2 , int distance) {
              this.node1 = node1;
              this.node2 = node2;
              this.distance = distance;
         public int getPriority () {
              return distance;
         public String toString() {
              String output = "(" + node1 + " " + node2 + ")" + " = " + distance + "\n" ;
              return output;
         public int compareTo(Object o) {
              if(o instanceof PQEntry){
                   if (getPriority() > ((PQEntry) o).getPriority()) {
                        return 1;
                   } else if(getPriority() == ((PQEntry) o).getPriority()) {
                        return 0;
                   } else {
                        return -1;
              } else {
                   throw new IllegalArgumentException("o must be an instance of PQEntry");
    import java.io.*;
    import java.util.*;
    class Main {
         final static String PROMPT = "graph> ";
         static private Graph myGraph = new GraphImp(51);
         static void initGraph() {
         myGraph.addEdge(3, 4, 90);
         myGraph.addEdge(3, 7, 300);
         myGraph.addEdge(4, 7, 151);
         myGraph.addEdge(4, 5, 51);
         myGraph.addEdge(5, 6, 151);
         myGraph.addEdge(7, 8, 100);
         myGraph.addEdge(7, 9, 70);
         myGraph.addEdge(8, 9, 75);
         myGraph.addEdge(9, 10, 95);
         myGraph.addEdge(10, 4, 400);
         myGraph.addEdge(10, 11, 60);
         myGraph.addEdge(11, 5, 600);
         myGraph.addEdge(11, 12, 151);
         myGraph.addEdge(11, 13, 200);
         myGraph.addEdge(12, 13, 100);
         myGraph.addEdge(12, 14, 51);
         myGraph.addEdge(13, 16, 200);
         myGraph.addEdge(13, 15, 200);
         myGraph.addEdge(14, 15, 170);
         myGraph.addEdge(14, 16, 251);
         myGraph.addEdge(15, 16, 110);
         public static void main(String[] args) {
              Scanner in = new Scanner(System.in);
              String[] input;
              String line;
              do {
                   System.out.print(PROMPT);
                   input = in.nextLine().split(" ");
                   if (input[0].equalsIgnoreCase("add")) {
                        if(input.length == 4){
                             if(!input[1].equals(input[2])) {
                                  myGraph.addEdge(Integer.parseInt(input[1]), Integer.parseInt(input[2]), Integer.parseInt(input[3]));
                             } else {
                                  System.out.println("Error! A node cannot connect to itself");
                        } else {
                             System.out.println("Incorrect command format, enter 3 seperate integers after 'add'");
                   } else if(input[0].equalsIgnoreCase("del")) {
                        if(input.length == 3) {
                             myGraph.deleteEdge(Integer.parseInt(input[1]), Integer.parseInt(input[2]));     
                        } else {
                             System.out.println("Incorrect command format, enter two seperate intgers after 'del'");
                   } else if(input[0].equalsIgnoreCase("help") && input.length == 1) {
                        System.out.println("The available commands are: help, quit, add i j l, del i j, where 'i' is the source node, 'j' is the target node and the 'l' is the length of the edge between them");
                   } else if(input[0].equalsIgnoreCase("quit") && input.length == 1) {
                        System.exit(0);
                   } else if(input[0].equalsIgnoreCase("mst") && input.length == 1) {
                        int[][] tempMatrix = myGraph.getMatrix();
                        PriorityQueue<PQEntry> edges = new PriorityQueue<PQEntry>(51);
                        List<PQEntry> sortedEdges = new LinkedList<PQEntry>();
                        for(int i = 1; i < 51; i++) {
                             for(int j = 1; j < 51; j++){
                                  if (tempMatrix[i][j] > 0) {
                                            edges.add(new PQEntry(i, j, tempMatrix[i][j]));
                             sortedEdges.addAll(edges);
                        System.out.println(sortedEdges);
                   } else if(input[0].equalsIgnoreCase("print") && input.length == 1) {
                        System.out.println(myGraph.toString());
                   } else if(input[0].equalsIgnoreCase("init") && input.length == 1) {
                        initGraph();
                   } else {
                        System.out.println("unknown Command, enter help for lsit of valid commands");
              } while(true);
    import java.util.*;
    class GraphImp implements Graph {
         //contains a two-dimensional array to hold the start vertex, end vertex
         //and the distance between the two verteces.
         private int [][] matrix;
              //constructor, sets the bounds of the two-dimensional array
              public GraphImp(int size) {
                   matrix = new int[size][size];
              //returns the two-dimensional array to the method calling it
              public int[][] getMatrix() {
                   return matrix;
              //this method first checks whether the two nodes are within the
              //acceptable range and gives an erro if not. It then checks whether an edge exists between the nodes
              //if an edge already exists it gives the user an error message, otherwise adds the edge
              //to the two-dimensional array at the appropriate position.
              public void addEdge(int node1 , int node2 , int distance) {
                   if(node1 > 0 || node1 < 51 || node2 > 0 || node2 < 51) {
                        if(matrix[node1][node2] == 0 && matrix[node2][node1] == 0) {
                             matrix[node1][node2] = distance;
                        } else {
                             System.out.println("Error! An edge already exists between the two nodes");
                   } else {
                        System.out.println("Error! Atleast one of the nodes are out of range, please enter within the range 1 - 51");
              //This method first checks whether the two nodes are within the acceptable range
              //if they are not an error message is given, otherwise it checks whether an edge exists
              //between the nodes. If there already exists one is prints an error, otherwise it removes
              //the corresponding edge.
              public void deleteEdge(int node1 , int node2) {
                   if(node1 > 0 || node2 > 0 || node1 < 51 || node2 < 51) {
                        if(matrix[node1][node2] != 0 || matrix[node2][node1] != 0) {
                             matrix[node1][node2] = 0;
                             matrix[node2][node1] = 0;
                        } else {
                             System.out.println("Error! No such edge exists to delete");
                   } else {
                        System.out.println("Error! Atleast one of the nodes are out of range, please enter within the range 1 - 51");
              //this method
              public String toString()
                   String result = "";
                   for(int j = 0; j < matrix[0].length; j++){
                        for(int i = 0; i < matrix[0].length; i++){
                             if (matrix[j] > 0){
                                  result = result + "(" + j + "," + i + ")" + " = " + matrix[j][i] + "\n";
                   return result;

    msjamalan wrote:
    Hi, here is my semi-complete program, I have removed the methods that were irrelevant to make things simple. The program is supposed to represent Graphs, and minimal spanning trees. I first have to put edges in a priority queue of type : PQEntry (Below), which are to be sorted by their 'distance'. I have not included the interfaces as they weren't necessary here (all methods are already implemented). There is no compile error, but for example when I run the program, and enter 'mst' (it shoud print the contents of the Priority Queue in the order of their distances), it puts the first few elements in order but fails to do so on the remaining elements. below is a sample run.AFAIK, a sorted priority queue sorts the output returned by the queue's poll method. So if you iterate through the entire queue via the poll() method, what is spit out should be sorted. If you just print the queue itself via println, you wan't see this sorting.
    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?
    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.
    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [cod&#101;] below your pasted code like so:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]Much luck!

Maybe you are looking for