Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Java Help :O

Name: ipoopmypants !49.zlWoq9M 2009-11-24 22:53

Anyone know how in Java I check check an array to see if there are any duplicates?

        int[] random = new int[100];
        Random randomGenerator = new Random();
        boolean inArray = true;

for(int i = 0; i < random.length; i++)
        {
            random[i] = randomGenerator.nextInt(999);
            if(random[i] == /*CHECK ALL OTHER INDEXES IN THE ARRAY*/)
            {
                random[i]++;
            }
           
            }

Name: HMA FAN 2009-11-25 12:00

Generating your ints with random() is kind of nasty. Your algorithm isn't guaranteed to terminate. Here's something more predictable.


import java.text.DecimalFormat;
import java.util.Collections;
import java.util.ArrayList;

public class Main {
    final static int maxn = 1000;
    final static int width = 10;
    final static int height = 10;
   
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList();
        for( int i = 0; i < maxn; ++i )
            numbers.add(i);
        Collections.shuffle( numbers );

        DecimalFormat fmt = new DecimalFormat(" 000 ");
        for( int i = 0; i < height; ++i ) {
            for( int j = 0; j < width; ++j ) {
                System.out.print( fmt.format( numbers.get(i*width + j) ) );
            }
            System.out.println();
        }
    }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List