Как перетасовать char из массива строк? - PullRequest
1 голос
/ 05 мая 2020

Я пытаюсь заставить игру угадать слово, но я не могу перетасовать char из массива строк

 String names_ofcolor[] = {"red", "green", "blue"};

 int random = (int) (Math.random() * names_ofcolor.length);

    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(j));

    }

1 Ответ

0 голосов
/ 05 мая 2020

Создайте 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...