Randomly Sort array of integers

All,
I have a question. I am writing an applet that loads a bunch of images into an array and then draws all the images in the array. However,I want to be able to randomly shuffle the images in the array and print them out.
I can randomly do this with numbers but how would I do it for a array of images?
Thanks

Here's something I use for shuffling object arrays: public class Shuffler {
    static private final Random RNG = new java.util.Random() ;
    static public void shuffleObjects(Object[] objs) {
        int offset = 0 ;
        int cnt = objs.length ;
        while (cnt > 1) {
            int swapIdx = RNG.nextInt(cnt) + offset ;
            if (swapIdx != offset) {
                Object tmp = objs[swapIdx] ;
                objs[swapIdx] = objs[offset] ;
                objs[offset] = tmp ;
            offset++ ;
            cnt-- ;
}

Similar Messages

  • Random an Array of integers

    how can i random an array of int's ?

    int RandomArray[] = new int [155];
    for ( int i = 0 ; i <=29 ; i ++ ) {
    RandomArray[i] = 1 ;
    for ( int i = 30 ; i <=86 ; i ++ ) {
    RandomArray[i] = 2 ;
    for ( int i = 87 ; i <=123 ; i ++ ) {
    RandomArray[i] = 3 ;
    for ( int i = 124 ; i <=154 ; i ++ ) {
    RandomArray[i] = 4 ;
    an array of 30x 1 , 57x 2 , 36x 3 and 30x 4
    i want to random the array and but it in a stack so i can get one by one and directly remove the top one who is taken
    i hope this is enough information
    thx

  • Write an algorithm to sort an array of integers

    "Write an algorithm to sort an array of integers"
    I was asked this at an interview and required to do it in 5 mins. I don't think you can use sort them by putting them in a collection, i think you need to write an algorithm from scartch. Any idea what the best way to do this would have been?

    Depends what you mean by "best."
    BubbleSort is probably the only one I could write off the top of my head in five minutes, but as sorting routines go for practical use, it sucks. If you know how to write MergeSort or QuickSort or dman near anything off off the top of your head, that would proabably be better.
    No one sorting algorithm is "best" without any context, however.
    If you don't know any sorting algorithms, use google or your data structures and algorithms textbook.

  • Sorting an array of integers into ascending order

    Today I decided to blow the cobwebs off my old laptop and see what I could remember from my Java days.
    As a task for myself to see what I could remember, I decided to try and write a program that does the following:
    - Declares an array of 4 integers
    - Sorts the array into ascending order, from lowest to highest.
    - Prints on screen the sorted array.
    After an hour or so I finally cracked it, and ended up with a working program. Here she is:
    public class Sorting_arrays_1
        public static void main()
           int [] array = {4,3,7,1};
           //A variable used to help with swopping values
           int temporary;
              //finds the smallest number out of elements 0, 1, 2, and 3 of the array, then moves it to position 0
              for (int count = 0; count<array.length;count++)
                int smallestNumber = array[0];
                if (array[count] < smallestNumber)
                    smallestNumber = array[count];
                    temporary = array[0];
                    array[0]=array[count];
                    array[count]=temporary;
             //finds the smallest number out of elements 1, 2, and 3 of the array, then moves it to position 1
             for (int count = 1; count<array.length;count++)
                int smallestNumber = array[1];
                if (array[count] < smallestNumber)
                    smallestNumber = array[count];
                    temporary = array[1];
                    array[1]=array[count];
                    array[count]=temporary;        
              //finds the smallest number out of elements 2 and 3 of the array, then moves it to position 2
              for (int count = 2; count<array.length;count++)
                int smallestNumber=array[2];
                if (array[count] < smallestNumber)
                    smallestNumber = array[count];
                    temporary = array[2];
                    array[2]=array[count];
                    array[count]=temporary;     
             //prints the array in ascending order
             for (int count=0; count<array.length;count++)
                 System.out.print(array[count] + " ");
    }Could this code be simplified though? Maybe with a for loop?
    I mean, it does the job, but it looks so clumbsy and inefficient... Imagine how much code I would need if I wanted to sort 1000 numbers..

    Use bubble sort if u want a quick fix
    public static void bubbleSort(int [] a)
    for(int i=0; i<a.length-1; i++)
         for(int j=0; j<a.length-1-i; j++)
              if(a[j]>a[j+1])
                   int temp = a[j];
                   a[j]=a[j+1];
                   a[j+1]=temp;
    Or use Merge sort if u want better run time... ie.(N log N)

  • Random Number Arrays

    Right I'm just learning so take it easy on me ok.
    I would like to know how to create a program that generates 6 random numbers and puts them into an array but I don't want duplicate values.
    I know of a piece of code which generates random doubles but I need integers for this and if you could tell me how to arrange them insde the array (you know highest-lowest).
    Yes I do know that many of you ot there would find this really easy but I could use some help so if you don't mind maybe not a whole program but some examples of code would be appreciated.
    I'm not sure if you have a similar thread somewhere because it could be 10 pages in so I haven't checked that far...

    import java.util.Random;
    public class Help
    public static void main(String[] args)
    Random rand = new Random();
    int[] nums = new int[6];
    for(int k = 0; k < nums.length; k++)
    a[k] = rand.nextInt();
    int nums_length = nums.length;
    System.out.println("Unsorted Array:");
    displayArray(nums, nums_length);
    nums = insertionSort(nums, nums_length);
    System.out.println("Sorted Array:");
    displayArray(nums, nums_length);
    // Insertion sort method. Sorts an array of ints in
    in descending order.
    public static int[] insertionSort(int[] array, int
    nt array_Length)
    int j, i, key;
    for (j = 1; j < array_Length; j++)
    key = array[j];
    // Move all values smaller then key up one
    up one position.
    for (i = j - 1; (i >= 0) && (array[i] < key);
    key); i--)
    array[i + 1] = array;
    array[i + 1] = key; // insert key into proper
    proper position
    return array;
    // Method that simply displays each element of
    of input_array.
    public static void displayArray(int[] inputArray,
    y, int input_size)
    int i;
    for (i = 0; i < input_size; i++)
    System.out.println(inputArray[i] + " ");
    System.out.println("\n");
    I went through the code...i dont understand y did we do insertion sort on the array of numbers and hw is the duplicacy of numbers being prevented..as far as i knw..insertion sort will nt remove duplicacy....
    enlighten me please

  • API which can sort array in decending order

    hi all,
    i just want to know is there any API available in Java which can sort an array of integers in desending order

    http://www.google.co.uk/search?hl=en&q=java+quicksort+API&btnG=Search&meta=
    will bring this right up:
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html

  • Array of Integers please help?

    pleace can someone help me? i am new in java . i want to create an array integers? Here i hava my codes that creates an array of strings? can anybody convert that so can accept integer and modified my method to add Integers instead of strings?Thanks for your time
    public class Numbers implements Serializable {
    * A constant: The maximum number of Random numbers
    // static public int MAXSETS = 3;
    static public final int MAXSETS = 3;
    * The integer variable count will hold the number of states in the subset
    private int count = 0;
    * The array state will hold the States in the subset of states
    private String number[] = new String[MAXSETS];
    * Constructor method: Reserve space for the 50 Integers
    public Numbers() {
    for(int i=0;i < MAXSETS;i++) {
    number = new String();
    * addNumbers: adds a number to the collection of Numbers
    * a string with the new number is passed as a parameter
    public void addNumbers(String newNumber) {
    number[count] = newNumber;
    count++;
    // System.out.println("scdsddfs"+ state);
    * toString: Convert the object to a string
    public String toString() {
    // int num;
    String str = count + " ";
    for(int i=0;i < count;i++){
    // num = Integer.parseInt(str);
    str = number;
    // str = str+" "+number;
    // System.out.println("scdsddfs"+ str);
    return str;

    pleace can someone help me? i am new in java . i want
    to create an array integers? Here i hava my codes that
    creates an array of strings? can anybody convert that
    so can accept integer and modified my method to add
    Integers instead of strings?Thanks for your time[snip]
    You create an array of integers by saying
    int[] myArrayOfIntegers[SIZE_I_WANT];To convert a String to an int, use the Integer.parseInt method.
    Good luck
    Lee

  • Functions to read and display an array of integers

    Hi guys,
    I am trying to implement with a class called Sort a function to read in an array of integers from a file and a function to display that array.
    public class Sort
         public static int[] read(String file) throws IOException
            /* Create Reader object to read contents of file */
            BufferedReader br = new BufferedReader(new FileReader(file));
            /* Read file and store lines in ArrayList */
            ArrayList<Integer> list = new ArrayList<Integer>();
            /* Variable */
            String in;
            /* While not equal to null reads data from file */
            while ((in = br.readLine()) != null)
                /* Adds data from file to ArrayList */
                list.add(Integer.parseInt(in));
            /* Converts ArrayList into an array */
            int[] array = new int[list.size()];
            for(int i = 0; i < list.size(); i++)
                /* Get array elements */
                array[i] = list.get(i);
            /* Returns array */
            return array;
        public int display()
            for (int i = 0; i < list.size(); i++)
                System.out.println(list.get(i));
    }I am having one of those moments when you forget everything, I need help with display the array in a seperate function, will someone help me please?
    Thanks!

    I know that its just implementing it.
    I have:
    public void display()
            for(int i = 0; i < array.length; i++)
                System.out.println(array);
    But I'm lost on how to make this work, i.e it says "cannot find array variable". I've not done Java for a while and feel like I have forgot everything!
    Edited by: mbruce10 on Nov 15, 2009 1:31 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Getting Largest Int From an Array of Integers

    public class TestMe
        public TestMe(int ai[])
            _numbers = ai;
    public int getBiggest1()
            int i = _numbers[0];
            for(int j = 1; j < _numbers.length; j++)
                if(_numbers[j] >= _numbers[j - 1] && i < _numbers[j])
                    i = _numbers[j];
            return i;
        public int getBiggest2()
            double d = Math.random();
            int i = _numbers[0];
            for(int j = 1; j < _numbers.length; j++)
                if(d >= 0.10000000000000001D && i < _numbers[j])
                    i = _numbers[j];
            return i;
      private TestMe()
        private int _numbers[];
    }can anyone see what is wrong with either of the two methods as regards returning the largest integer from an array of integers.
    As far as I can see they work no matter what ints are in the array.
    Any ideas anyone ?
    Regards
    Sean

    I used the following client program to use ur class:
    I also modified ur class a bit and made the other constructor (the one with no arguments) as public to extend the class.
    Both the functions, viz, getBiggest1() and getBiggest2() are working fine...
    Now, I am new to JAVA so I might have made mistakes. Please correct me if there is anything wrong.
    /*Here is ur class that i have modified*/
    public class GetBiggest {
         public GetBiggest(int ai[])     {
              _numbers = ai;   
         public int getBiggest1()     {
              int i = _numbers[0];
              for(int j = 1; j < _numbers.length; j++)           
              if(_numbers[j] >= _numbers[j - 1] && i < _numbers[j])
                   i = _numbers[j];
              return i;
         public int getBiggest2() {       
              double d = Math.random();
              int i = _numbers[0];       
              for(int j = 1; j < _numbers.length; j++)           
              if(d >= 0.10000000000000001D && i < _numbers[j])
                   i = _numbers[j];
              return i;
    public GetBiggest()     {
    private int _numbers[];
    /*Ur class ends here*/
    /*My client program starts here*/
    import java.lang.*;
    public class TestBiggest extends GetBiggest
         public static void main (String args[])
              int[] arrNums = {30, 20, 40, 10};
              GetBiggest GB = new GetBiggest(arrNums);
              int greatest = 0;
              try
                   greatest = GB.getBiggest2();
                   System.out.println("\nBiggest number is : " + greatest);
              }//end try block
              catch(Exception e)
                   System.out.println("Some error");
              }//end catch block
         }//end main
    }//end class
    /*End of my client program*/

  • Constructing a linked list from an array of integers

    How do I create a linked list from an array of 28 integers in a constructor? The array of integers can be of any value that we desire. However we must use that array to test and debug methods such as getFirst(), getLast(), etc...
    I also have a method int getPosition(int position) where its suppose to return an element at the specified position. However, I get an error that says cannot find symbol: variable data or method next()
    public int getPosition(int position){
         LinkedListIterator iter=new LinkedListIterator();
         Node previous=null;
         Node current=first;
         if(position==0)
         return current.data;
         while(iter.hasMore()){
         iter.next();
         if(position==1)
         return iter.data;
         iter.next();
         if(position==2)
         return iter.data;
         iter.next();
         if(position==3)
         return iter.data;
         iter.next();
         if(position==4)
         return iter.data;
         iter.next();
         if(position==5)
         return iter.data;
         iter.next();
         if(position==6)
         return iter.data;
         iter.next();
         if(position==7)
         return iter.data;
         iter.next();
         if(position==8)
         return iter.data;
         iter.next();
         if(position==9)
         return iter.data;
         iter.next();
         if(position==10)
         return iter.data;
         iter.next();
         if(position==11)
         return iter.data;
         iter.next();
         if(position==12)
         return iter.data;
         iter.next();
         if(position==13)
         return iter.data;
         iter.next();
         if(position==14)
         return iter.data;
         iter.next();
         if(position==15)
         return iter.data;
         iter.next();
         if(position==16)
         return iter.data;
         iter.next();
         if(position==17)
         return iter.data;
         iter.next();
         if(position==18)
         return iter.data;
         iter.next();
         if(position==19)
         return iter.data;
         iter.next();
         if(position==20)
         return iter.data;
         iter.next();
         if(position==21)
         return iter.data;
         iter.next();
         if(position==22)
         return iter.data;
         iter.next();
         if(position==23)
         return iter.data;
         iter.next();
         if(position==24)
         return iter.data;
         iter.next();
         if(position==25)
         return iter.data;
         iter.next();
         if(position==26)
         return iter.data;
         iter.next();
         if(position==27)
         return iter.data;
         iter.next();
         if(position==28)
         return iter.data;
         if(position>28 || position<0)
         throw new NoSuchElementException();
         }

    How do I create a linked list from an array of 28 integers
    in a constructor? In a LinkedList constructor? If you check the LinkedList class (google 'java LinkedList'), there is no constructor that accepts an integer array.
    In a constructor of your own class? Use a for loop to step through your array and use the LinkedList add() method to add the elements of your array to your LinkedList.
    I get an error that
    says cannot find symbol: variable data or method
    next()If you look at the LinkedListIterator class (google, wait for it...."java LinkedListIterator"), you will see there is no next() method. Instead, you typically do the following to get an iterator:
    LinkedList myLL = new LinkedList();
    Iterator iter = myLL.iterator();
    The Iterator class has a next() method.

  • In imovie can you trim multiple clips at a time?  Also, can you randomly sort the photos?

    In imovie can you trim multiple clips at a time?  Also, can you randomly sort the photos?

    Can I do all at once or 1 at a time? It seems to only allow 1 at a time.
    No. But you can do one, copy its settings, then seclect the rest and "Paste Audio Settings" to all of them all at once in a project.

  • Removes duplicates from a sorted array without having to create a new array

    Funcation removes duplicates from a sorted array without having to create a new array

    Funcation removes duplicates from a sorted array
    without having to create a new arrayIs a 'funcation' like a vacation but more fun or
    something?LMFAO. You just jumped with both feet on one of my biggest peeves. I've been outed!
    Actual words/phrases I've seen used which I hate with every fiber of my being:
    "Mrs. Freshly's"
    "McFlurry"
    "Freshissimo"
    "Spee-dee"
    "Moons Over My Hammy"
    One of my favorite SNL skits had Will Ferrell leading a panel of movie reviewers (they're the worst for this kind of junk). Each one had some cheesy pun to describe their respective movie. Ferrell topped the show off with his endorsement of "Fantasia 2000 is Fantasgreat!"
    LOL.
    "Come to Slippy Village - it's a FUNCATION!"
    &#167; (runs off, laughing maniacally, head explodes)

  • Exception handling in sorting arrays

    Hi all, I have a problem with the use of the built in java sort fo arrays. My program works on an array with 4 or 5 entities. When I run it in some folders it works but not in others. I get the following error after compilation, where "ResultData" is the class of array to be sorted:Exception in thread "main" java.lang.NullPointerException
    at ResultData.compareTo(TextEdit.java:1215)
    at java.util.Arrays.mergeSort(Arrays.java:1064)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1072)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.sort(Arrays.java:1014)
    at java.util.Collections.sort(Collections.java:78)
    [\code]Can any one give a suggestion?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Here is the code for the class "ResultData"class ResultData implements Comparable
         String file1;
         String file2;
         double var, var1, var2;
         public ResultData(String f1,String f2,double v, double x, double y)
                   file1= f1; file2=f2;
                   var=v; var1=x; var2=y;
         public String getFile1Name()
              return file1;
         public String getFile2Name()
              return file2;
         public double getVar()
              return var;
         public double getVar1()
              return var1;
         public double getVar2()
              return var2;
         public String toString()
              return file1+"          "+file2+"          "+var+"          "+var1+"          "+var2;
           public int compareTo(Object o)
              ResultData r= (ResultData)o;
              double result = this.getVar()- r.getVar();
              if (result < 0.0)         return -1;
              else if(result > 0.0)     return 1;
              else return 0;
    } // ends class ResultData

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Random sort order in slideshows

    I was trying to import some jpg's into a slideshow, from a folder of jpg's. I found that the slides that ended up in the iDVD slideshow were randomly sorted. The sort order matched neither the date/timestamp, the filename, or any other metadata I could work out. I then imported them into iPhoto and discovered I could force a sort order there and bring them across from iPhoto into iDVD and that worked.
    However, the behavior of iDVD when importing from a regular folder of images is very buggy, and of course there are no slideshow sorting options within the program. I do this regularly and pumping everything through iPhoto just so I can get my slideshows sorted is cumbersome. Has anyone else seen this and is there an explanation/fix?
    Thanks.

    Did you have any luck with this? I have been trying all day to find a solution for this very problem. I know I can do the *into iPhoto first* theory - but as I am adding from Aperture I had thought I was past the iPhoto malarky.

Maybe you are looking for

  • I am unable to re-install iTunes after replacing my HD.

    Have uninstalled iTunes, downloaded a new version (4 times) and keep getting this msg: "iTunes installer completed. The installer encountered errors before it could be configured. Errors occured during installation. Your system has not been modified.

  • NEW PLAYER: Creative Zen Vision:M (30

    Well, it seems that we did not have to wait till 8th dec to see what new product Creative will be releasing.According to internet leak, the new product is the Zen Vision:M <IMG src="http://img.photobucket.com/albums/v624/kingone/zen_vis_m.jpg"> ? 2.5

  • How to decrease width of spreadsheet tab?

    In Numbers 3.1, is there a way to decrease the spreadsheet tabs that go across the top of a workbook?  I have a few spreadsheets.  They trail off to the right out of view because each spreadsheet tab is so wide.  I tried to drag the width but you can

  • HT204486 Why does Photo App not synchronize my Books?

    I'm really surprised to see that only the photos and some small other parts of my work with Photo get synchronized through iCloud Fotostream to my different Apple devices. No Book, np Slideshow, not even Face tiles get synchronized. This is very disa

  • Issue with crystal reports 2008 clickonce fix pack 1.7

    Hi, When we try to extract the crystal reports 2008 clickonce fix pack 1.7 then we get a message saying that the zip file is corrupt. Anyone got this problem or has a solution for it ?