C Exercise Example 22

100 Classic C Examples

Title:Two table tennis teams competed, each sending three players. Team A wasa、b、cThree people, Team B isx、y、zThree people.

The match roster was decided by drawing lots. Someone asked the players about the roster: a said he would not play with x, and c said he would not play with x or z. Please write code to find the roster of the three pairs of players.

Idea:

  1. Usage3 loopsEnumerate the possible matches between each player of Team A and the players of Team B.
  2. addConstraintsand filter out the combinations that do not satisfy the problem requirements:
    • a does not compete with x.
    • c does not compete with x or z.
  3. Ensure that each player of Team B can only play against one player of Team A.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> int main() { // Define members of Team A and Team B char teamA[] = {'a', 'b', 'c'}; // Team A: a, b, c char teamB[] = {'x', 'y', 'z'}; // Team B: x, y, z // Variables i, j, k represent the opponents of a, b, and c respectively char i, j, k; // Enumerate a's opponents for (i = 'x'; i <= 'z'; i++) { // Enumerate b's opponents for (j = 'x'; j <= 'z'; j++) { // Ensure the opponents of a and b are different if (i != j) { // Enumerate c's opponents for (k = 'x'; k <= 'z'; k++) { // Ensure c's opponent is different from the opponents of a and b if (i != k && j != k) { // Satisfy the problem conditions: a does not compete against x, c does not compete against x or z if (i != 'x' && k != 'x' && k != 'z') { // Output the matching result printf("Match order: a--%c\tb--%c\tc--%c\n", i, j, k); } } } } } } return 0; }

The output of the above example is:

顺序为:a--z    b--x    c--y

100 Classic C Examples

other extensions