Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 22

C Exercise 22

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Two table tennis teams compete, with three players each. Team A has a, b, and c; team B has x, y, and z.

The match-ups are decided by drawing lots. Someone asked the players about the match list: a said he does not play against x, and c said he does not play against x or z. Write code to find the three match-ups.

Approach:

  1. Use 3 loops Enumerate the possible match-ups between each player of team A and the players of team B.
  2. add Constraints, filter out combinations that do not meet the requirements:
  3. a does not play against x.
  4. c does not play against x or z.
  5. - a does not play against x. - c does not play against x or z.
    1. Ensure that each player of team B plays against only one player of team A.

    Example

    // Created by www.runoob.com on 15/11/9.

    // Copyright (c) 2015 Runoob Tutorial. All rights reserved.

    //

    #include

    <
    
    stdio.h
    
    int
    
    main
    
    (
    
    )
    
    {

    // Define the 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, c respectively

    char

    i

    ,

    j

    ,

    k

    ;

    // Enumerate the opponent of a

    for

    (

    i

    = '

    x

    ';

    i

    <= '

    z

    ';

    i

    ++

    )

    {

    // Enumerate the opponent of b

    for

    (

    j

    = '

    x

    ';

    j

    <= '

    z

    ';

    j

    ++

    )

    {

    // Ensure that a and b have different opponents

    if

    (

    i

    !=

    j

    )

    {

    // Enumerate the opponent of c

    for

    (

    k

    = '

    x

    ';

    k

    <= '

    z

    ';

    k

    ++

    )

    {

    // Ensure that c's opponent differs from those of a and b

    if

    (

    i

    !=

    k

    &&

    j

    !=

    k

    )

    {

    // Satisfy the problem conditions: a does not play against x, c does not play against x or z

    if

    (

    i

    != '

    x

    ' &&

    k

    != '

    x

    ' &&

    k

    != '

    z

    '

    )

    {

    // Output the match results

    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 Language Examples 100 Classic C Language Examples