Создайте List
индексов от 0
до names_ofcolor[random].length() - 1
и перемешайте его, используя Collections::shuffle
. Затем вы можете использовать перетасованные индексы для установки метки кнопки.
String names_ofcolor[] = { "red", "green", "blue" };
int random = (int) (Math.random() * names_ofcolor.length);
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < names_ofcolor[random].length(); i++) {
indices.add(i);
}
Collections.shuffle(indices);
for (int j = 0; j < names_ofcolor[random].length(); j++) {
Button btn = new Button(this);
btn.setId(j);
btn.setBackgroundColor(Color.WHITE);
btn.setTextSize(16);
linearlayout.addView(btn);
btn.setText("" + names_ofcolor[random].charAt(indices.get(j)));
}
Быстрая демонстрация:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
String names_ofcolor[] = { "red", "green", "blue" };
int random = (int) (Math.random() * names_ofcolor.length);
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < names_ofcolor[random].length(); i++) {
indices.add(i);
}
Collections.shuffle(indices);
for (int j = 0; j < names_ofcolor[random].length(); j++) {
String label = "" + names_ofcolor[random].charAt(indices.get(j));
System.out.print(label);
}
}
}
Пробный запуск :
regne
Другой прогон образца:
erd
Другой прогон образца:
elbu