如何在Java中选择随机数时停止重复

时间:2015-04-26 18:01:06

标签: java random no-duplicates

public void start() throws TwitterException, IOException 
{
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
    AccessToken oathAccessToken = new AccessToken(ACCESS_KEY, ACCESS_KEY_SECRET);
    twitter.setOAuthAccessToken(oathAccessToken);
    ColourBlender myColourBlender = new ColourBlender();
    twitter.updateStatus(TwitterActions.getCatchphrase());
}

public static String getCatchphrase() throws FileNotFoundException
{
    ColourBlender myColourBlender = new ColourBlender();
    String newColour = myColourBlender.BlendColour();
    String[] phraseArray = {"Phrase1", "Phrase2", "Phrase3"};
    Random r = new Random();
    String catchphrase = phraseArray[r.nextInt(phraseArray.length)];
    return catchphrase;
}

在这段代码中,我希望在数组中有许多标语,这些标语将在Twitter上随机发送,但我不希望它们被重复。

如何停止生成重复项?

4 个答案:

答案 0 :(得分:3)

你可以随便洗一下这句话。所以元素将是随机顺序。

Arrays.shuffle(phraseArray);

答案 1 :(得分:1)

实现它的最简单方法是创建一个可能的数字列表(例如1到100),然后你可以用-(void) getData:(NSData *) data{ NSError *error; json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptionserror:&error]; } -(void) start{ NSURL *url = [NSURL URLWithString:kGETUrl]; NSData *data = [NSData dataWithContentsOfURL:url]; [self getData:data]; //NSLog(@"Test:", data); NSIndexPath *indexPath; NSDictionary *info = [json objectAtIndex:indexPath.row]; //int *num = [json count]; for(NSString* key in info){ NSLog([info objectForKey:@"title"]); } } 对它们进行随机播放。

或者您可以使用Collections.shuffle来跟踪生成的数字

LinkedHashSet

LinkedHashSet将帮助您跟踪创建的数字的插入顺序。

答案 2 :(得分:0)

您不能保证java.util.Random.nextInt()不重复。但是,如果要生成的随机数量相对较小,则可以将它们添加到集合中,然后执行Collections.shuffle()

答案 3 :(得分:0)

如何添加一个PhraseManager,它可以从短语列表中删除N次迭代中使用过的元素(或者其他一些机制,例如永远不允许重复)。代码如下所示:

public class Class {
    static class PhraseManager {
        public final int N = 1;
        private Random r = new Random();

        private final LinkedList<String> phrases = new LinkedList<String>();
        private final LinkedList<String> phrasesUsedLastNTimes = new LinkedList<String>();

        public PhraseManager(Collection<String> phrases) {
            this.phrases.addAll(phrases);
        }

        public String getRandomPhrase() {

            String catchphrase = phrases.remove(r.nextInt(phrases.size()));
            phrasesUsedLastNTimes.addFirst(catchphrase);
            if(phrasesUsedLastNTimes.size() > N) {
                phrases.addLast(phrasesUsedLastNTimes.pollLast());
            }
            return catchphrase;
        }


    }

    private static PhraseManager phraseManager = new PhraseManager(Arrays.asList(new String[] {"Phrase1", "Phrase2", "Phrase3"}));

    public void start() throws TwitterException, IOException {

        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
        AccessToken oathAccessToken = new AccessToken(ACCESS_KEY,
                ACCESS_KEY_SECRET);
        twitter.setOAuthAccessToken(oathAccessToken);
        ColourBlender myColourBlender = new ColourBlender();
        twitter.updateStatus(TwitterActions.getCatchphrase());
    }

    public static String getCatchphrase() throws FileNotFoundException
    {
        ColourBlender myColourBlender = new ColourBlender();
        String newColour = myColourBlender.BlendColour();


        return phraseManager.getRandomPhrase();
    }
}