I have a grid: int[][] the_grid = new int[4][4];
and I want to randomly populate it with elements ?, +, -, *, !, /, #, % such that exactly two squares have one of the elements in them. What's the most succinct and efficient way to accomplish this task?
Asked
Active
Viewed 894 times
0

Paul Samsotha
- 205,037
- 37
- 486
- 720

user3193204
- 53
- 6
-
Sorry, I don't really understand... are the elements *?, +, -, *, !, /, #, %* considered as `int`? Or is your grid actually a `String[][]` ? – ccjmne Feb 07 '14 at 05:09
-
Good puzzle. http://stackoverflow.com/a/4040031/2359488 this link shows how to generate random numbers without duplicates. If you populate a list containing 16 elements ( ?, +, -, *, !, /, #, % .. each twice), and then pop them back randomly into your grid, you'd get what you want. – Khulja Sim Sim Feb 07 '14 at 05:14
-
Also, 2 more things: could it possibly be a `char[][]` array; and when you say *exactly two squares have one of the elements in them*, what does that mean? – Alvin Bunk Feb 07 '14 at 05:17
1 Answers
1
In case your grid actually contains String
s (and not int
s), I would simply:
list the tokens you can have:
final List<String> tokens = Arrays.asList("?", "+", "-", "*", "!", "/", "#", "%", "?", "+", "-", "*", "!", "/", "#", "%");
shuffle these tokens:
Collections.shuffle(tokens);
then finally add them while iterating over your grid:
int i = 0, j = 0;
for (final String token : tokens) {
theGrid[i][j] = token;
if (++j == 4) {
j = 0;
++i;
}
}
Complete example:
final String[][] theGrid = new String[4][4];
final List<String> tokens = Arrays.asList("?", "+", "-", "*", "!", "/", "#", "%", "?", "+", "-", "*", "!", "/", "#", "%");
Collections.shuffle(tokens);
int i = 0, j = 0;
for (final String token : tokens) {
theGrid[i][j] = token;
if (++j == 4) {
j = 0;
++i;
}
}
Usage:
for (final String[] row : theGrid) {
for (final String column : row) {
System.out.print(column);
}
System.out.println();
}
Sample output (changes every time):
?!!%
+*--
#/#%
*/?+

ccjmne
- 9,333
- 3
- 47
- 62