Android随机非重复字符串

时间:2011-10-16 04:40:12

标签: android string random

我正在制作宾果游戏。我有一个5x5网格的图像按钮,每个都有自己的文本视图。当应用程序启动或重置时,我希望每个textview显示一个随机字符串,在游戏过程中没有任何一个字符串显示两次。我目前在资源数组中有字符串,包含127个项目:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="tile_text">
    <item>String 1</item>
    <item>String 2</item>
    <item>String 3</item>
    ...all the way to String 127
</string-array>
</resources>

并在每个文本视图上显示随机字符串:

public String[] myString;

Resources res = getResources();
myString = res.getStringArray(R.array.tile_text);

Random random = new Random(System.currentTimeMillis());

int[] textViews = {

//I have all my textviews added to this array
};

for(int v : textViews) {
        TextView tv = (TextView)findViewById(v);

        tv.setText(myString[random.nextInt(myString.length)]);          
}

以上效果很好,但即使数组中有200个字符串可供选择,某些项目仍会显示两次。有没有办法我可以让阵列洗牌而不是每场比赛两次选择相同的字符串?我搜索过,我发现随机字符串的信息,但没有关于非重复随机字符串的信息,所以如果这是一个重复的问题,请道歉。

1 个答案:

答案 0 :(得分:1)

我会保留已添加的字符串列表,然后继续选择新的随机字符串,直到找到列表中尚未存在的字符串。

这样的事情:

Vector<String> alreadyUsed = new Vector<String>();

for(int v : textViews) {
    TextView tv = (TextView)findViewById(v);

    String nextString;
    do {
        nextString = myString[random.nextInt(myString.length)];                
    } while (alreadyUsed.contains(nextString));
    alreadyUsed.add(nextString);

    tv.setText(nextString);          
}
相关问题