Menu
Coddy logo textTech

Shuffling a List

Part of the Logic & Flow section of Coddy's Dart journey — lesson 8 of 65.

When you need to randomize the order of elements in a list, Dart provides the shuffle() method. This method rearranges all elements in the list randomly, creating an unpredictable order that's perfect for games, simulations, or any situation where you need random arrangements.

The shuffle() method modifies the original list directly, changing the positions of all elements randomly. Each time you call shuffle(), you'll get a different arrangement of the same elements.

List<String> cards = ['Ace', 'King', 'Queen', 'Jack'];
print('Original: $cards');  // [Ace, King, Queen, Jack]

cards.shuffle();
print('Shuffled: $cards');  // [Queen, Ace, Jack, King] (random order)

This method is particularly useful for creating card games, randomizing quiz questions, or any application where you want to present items in an unpredictable sequence. Since shuffle() works in place, you don't need to create a new list - the existing list is randomly reorganized for you.

challenge icon

Challenge

Easy

Create a program that manages a game tournament bracket by shuffling teams into random matchups. Your program should:

  1. Read a string input representing the tournament name (this value is read but not printed)
  2. Read multiple string inputs representing team names (the input ends when an empty string is received)
  3. Shuffle the teams into a random order
  4. Print each team name on a separate line

For example, if the tournament name is "Local Cup" and the teams are "Wolves", "Hawks", your program should output the team names in a shuffled (random) order, one per line:

Hawks
Wolves

Or:

Wolves
Hawks

Since shuffle() randomizes the order, any arrangement of the teams is valid.

Cheat sheet

The shuffle() method randomizes the order of elements in a list:

List<String> cards = ['Ace', 'King', 'Queen', 'Jack'];
print('Original: $cards');  // [Ace, King, Queen, Jack]

cards.shuffle();
print('Shuffled: $cards');  // [Queen, Ace, Jack, King] (random order)

The shuffle() method modifies the original list directly and creates a different random arrangement each time it's called.

Try it yourself

import 'dart:io';

void main() {
  // Read tournament name
  String? tournamentName = stdin.readLineSync();
  
  // Read team names until empty string
  List<String> teams = [];
  String? teamName;
  while ((teamName = stdin.readLineSync()) != null && teamName!.isNotEmpty) {
    teams.add(teamName);
  }
  
  // TODO: Shuffle the teams list for random matchups

  // Print each team on a separate line
  for (String team in teams) {
    print(team);
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow