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:18

And for the entertainment, a hash set. By the way, >>9-kun:
use Random to produce an int, wrap it in an Integer object, and check whether than Integer object currently exists in the Hash

It's a set. You don't need to check if it's already in there. Just keep adding until you have enough.


import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Random;
import java.util.LinkedHashSet;

public class Main {
    final static int maxn = 1000;
    final static int width = 10;
    final static int height = 10;
   
    public static void main(String[] args) {
        Random rnd = new Random();
        try{
            LinkedHashSet numbers = new LinkedHashSet();
            while( numbers.size() < width * height )
                numbers.add( rnd.nextInt(maxn) );

            DecimalFormat fmt = new DecimalFormat(" 000 ");
            Iterator it = numbers.iterator();
            for( int i = 0; i < height; ++i ) {
                for( int j = 0; j < width; ++j ) {
                    System.out.print( fmt.format( (Integer)it.next() ) );
                }
                System.out.println();
            }
        } catch( Exception e ) {
            System.out.println( e.toString() );
        }
    }
}

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