Skip to content

Instantly share code, notes, and snippets.

@seunghwanly
Last active January 10, 2023 14:46
Show Gist options
  • Save seunghwanly/d2882f3bc6145c1a61b7013a8d4519b7 to your computer and use it in GitHub Desktop.
Save seunghwanly/d2882f3bc6145c1a61b7013a8d4519b7 to your computer and use it in GitHub Desktop.
flying-flash-9887

Create 1D Random Dice

use dart:math to create a random number and fill it inside the dice(list).

Set Specific Rules for dice

  /// set dice position
  ///  (0,0)  [(0,1)]  (0,2)   (0,3)
  /// [(1,0)] [(1,1)] [(1,2)] [(1,3)]
  ///  (2,0)  [(2,1)]  (2,2)   (2,3)

  /// <pos> > <index>
  /// (0,1) > 0
  /// (1,0) > 1
  /// (1,1) > 2
  /// (1,2) > 3
  /// (1,3) > 4
  /// (2,1) > 5

  /// set pair <pos> : <index>
  /// (0,1) - (2,1) : 0 - 5
  /// (1,0) - (1,2) : 1 - 3
  /// (1,1) - (1,3) : 2 - 4

Practice Dart

  • use user-defined function
  • use while and for loop
  • use switch-case
  • use if-else
  • use ternary ( ? : )
  • use final and late
  • use List.filled constructor
  • use library (dart:math)
import 'dart:math';
void main() {
/// init 1d array
List<int> dice1D = List.filled(6, 0);
/// set dice position
/// (0,0) [(0,1)] (0,2) (0,3)
/// [(1,0)] [(1,1)] [(1,2)] [(1,3)]
/// (2,0) [(2,1)] (2,2) (2,3)
/// <pos> > <index>
/// (0,1) > 0
/// (1,0) > 1
/// (1,1) > 2
/// (1,2) > 3
/// (1,3) > 4
/// (2,1) > 5
/// set pair <pos> : <index>
/// (0,1) - (2,1) : 0 - 5
/// (1,0) - (1,2) : 1 - 3
/// (1,1) - (1,3) : 2 - 4
/// set rules
bool hasDiceFormat(List<int> dice) {
if (dice.length != 6) return false;
return (dice[0] + dice[5]) == 7 &&
(dice[1] + dice[3]) == 7 &&
(dice[2] + dice[4]) == 7;
}
for (int i = 0; i < 3; i++) {
/// set random number
int randomNumber = -1;
while(true) {
final int n = Random().nextInt(6) + 1;
bool isUnique = true;
for(int j = 0; j < 6; j++) {
if(dice1D[j] == n) {isUnique = false; break;}
}
if(isUnique) {
randomNumber = n;
break;
}
}
if(randomNumber == -1) return;
if (dice1D[i] == 0) {
dice1D[i] = randomNumber;
late int oppositeIndex;
switch (i) {
case 0:
oppositeIndex = 5;
break;
case 1:
oppositeIndex = 3;
break;
case 2:
oppositeIndex = 4;
break;
default:
oppositeIndex = -1;
break;
}
if (oppositeIndex != -1) {
dice1D[oppositeIndex] = 7 - randomNumber;
}
}
}
/// check if the dice is made properly
print('The dice has made ${hasDiceFormat(dice1D) ? 'perfectly' : 'bad'} -> $dice1D');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment