java的项目添加随机时间间隔的ArrayList [英] java add items to arraylist at random time intervals

查看:109
本文介绍了java的项目添加随机时间间隔的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

努力随机时间间隔添加项目。

trying to add an item at random time intervals.

我想我需要开始时,我等于arriveTime,一旦满足我需要建立一个新的随机到达,并添加我(否则它不会再因为我已经是过去的到来发生了。所以我再添如果一旦被满足创造新的到达时间,然后重新添加我。伪code似乎是有道理的,code没有这么多,任何帮助是AP preciated。

I was thinking I need to start when i is equal to arriveTime, once that is met I need to create a new random arrival and add i (otherwise it will not happen again as i is already past arrival. So I add another if, once that is met create new arrival time and add i again. pseudocode seems to make sense, code not so much, any help is appreciated.

    ArrayList<Integer> q = new ArrayList<Integer>();
    Random r = new Random();
    int arrivals = 0;

    for (int i = 1; i <= 720; i++) {
        int arrive = r.nextInt(4)+1;
        if (i == arrive) {
            q.add(i);
            arrivals ++;
            arrive = r.nextInt(4)+1+i;
        }
        else if (i == arrive) {
            q.add(i);
            arrivals ++;
            arrive = r.nextInt(4)+1+i;
        }

    }

对不起,arriveTime应该只是到达。 ArriveTime不存在

sorry, arriveTime should be just arrive. ArriveTime does not exist.

编辑:从意见扩张。 '我'再presents时间,我不想一个随机整数添加到列表中。而在随机时间间隔添加相同的对象'我'。我加入i键列表,看看在什么时候该算法将一个项目的价值,因为它没有似乎是工作。结果各不相同,但它似乎是被添加到列表总是个位数。也做了更新,以code。

edit: To expand from comments. 'i' represents time and I dont want to add a random integer to the list. Rather add the same object at random intervals of 'i'. I was adding the value of 'i' to the list to see at what times the algorithm was adding an item because it didnt seem to be working. Results vary, but it seems to be always single digits that get added to list. Also made updates to code.

推荐答案

您应该比较时间 1-4在如果语句,然后添加值 I (如 I 重新$ p $的时间psentative )事情是这样的。

you should be comparing time to 1-4 in your if statements, then adding that value to i (as i is representative of time) Something like this

    ArrayList<Integer> q = new ArrayList<Integer>();
    Random r = new Random();
    int arrivals = 0;

    for (int i = 1; i < 100 ; i++) { //loop as many times as you want.
        int time = r.nextInt(4)+1; //choose a random time of arrival, 1-4

        //now compare time to your random time intervals (1-4, not i
        //if it matches add that value to i
        if (time == 1) {  
            //add your object to the list
            i += 1; 
        }
        else if (time == 2) {
            //add your object to the list
            i += 2;
        }

        else if (time == 3) {
            //add your object to the list
            i += 3;
        }
        else if (time == 4) {
            //add your object to the list
            i += 4;
        }
    }

这篇关于java的项目添加随机时间间隔的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆