开发者

Random, and not same with last 10. (Java)

I'm new here.. I want to make a code to remember the last 10 numbers and to be not same.

private static ArrayList<Integer> nums = new ArrayList<Integer>();

public static void main(String[] args) 
{
    System.out.println(getRandomNumber());
}

public static int getRandomNumber()
{
    int randomN = 0, rand = Rnd.nextInt(20);
    while (nums.size() == 10)
    {
        nums.remove(nums.get(0));
        continue;
    }
    if (!nums.contains(rand)) 
    {
        nums.add(rand);
        randomN = rand;
    }
    else getRandomNumber();

    return randomN;
}

when the array reach 10 values the first one will be deleted .. I hope you understand what I want :) Th开发者_Go百科anks


Try using an ArrayDequeue and when the length grows to more than 10, you simple remove the items from the tail.


import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

class main{
    public ArrayList<Integer> nums;
    public Random generator;

    public static void main(String[] args){
        // Calling Start
        (new main()).start();
    }

    public void start(){
        nums =  nums = new ArrayList<Integer>();

        generator = new Random();

        for(int i=0;i<15;i++){
            add(generator.nextInt(20));
            print();
        }
    }

    public void add(int newNumber){
        // Check by iterating if i is already in nums
        Iterator it = nums.iterator();

        while(it.hasNext()){
            if(newNumber == (Integer) it.next())
                return;     // i is already in our list
                            // so get out add()
        }

        if(nums.size() == 10){
            int forward = nums.get(0);

            for(int i = 1; i < 10; i++){
                // Move numbers back 1 position
                nums.set(i-1,forward);
                // Save next number in forward
                forward = nums.get(i);
            }
        }

        nums.add(newNumber);
    }

    public void print(){
        String str = "";
        Iterator it = nums.iterator();

        if(it.hasNext()){
            str += "num: [ " + (Integer) it.next();
        }

        while(it.hasNext()){
            str += " , " + (Integer) it.next();
        }

        str += " ]";

        System.out.println(str);
    }
}


I would either use a circular array or a linked list for this. Depending on what you plan to use the list of numbers for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜