游客国籍

问题描述

在一个旅馆中住着六个不同国籍的人,他们分别来自美国、德国、英国、法国、俄罗斯和意
大利。他们的名字叫 A、B、C、D、E 和 F。名字的顺序与上面的国籍不一定是相互对应的。
现在已知:
1)A 美国人是医生。
2)E 和俄罗斯人是教师。
3)C 和德国人是技师。
4)B 和 F 曾经当过兵,而德国人从未参过军。
5)法国人比 A 年龄大;意大利人比 C 年龄大。
6)B 同美国人下周要去西安旅行,而 C 同法国人下周要去杭州度假。
试问由上述已知条件,A、B、C、D、E 和 F 各是哪国人?

算法思路

  • 有题目条件,逐确定谁不是哪国人
  • 确定每个变量的取值范围之后,剩下的就是一个判断条件变量之间各不相等
  • 本质上这个题目还是暴力的方法 => 确定有几个变量,在确定变量的范围 => 利用逻辑条件进行暴力判断

代码示例

Python

# (美,德,英,法,俄,意) => (0,1,2,3,4,5)
#
for a in [2,5]:
    for b in [2,4,5]:
        if a != b:
            for c in [2]:
                if a!=c and b!=c:
                    for d in [0,1,2,3,4,5]:
                        if a!=d and b!=d and c!=d:
                            for e in [2,3,5]:
                                if a!=e and b!=e and c!=e and d!=e:
                                    for f in [0,2,3,4,5]:
                                        if a!=f and b!=f and c!=f and d!=f and e!=f:
                                            print("a:%d,b:%d,c:%d,d:%d,e:%d,f:%d"%(a,b,c,d,e,f))

Java


public class 游客国籍 {

    static int[] a_arr;
    static int[] b_arr;
    static int[] c_arr;
    static int[] d_arr;
    static int[] e_arr;
    static int[] f_arr;

    static void init() {
        a_arr = new int[] { 2, 5 };
        b_arr = new int[] { 2, 4, 5 };
        c_arr = new int[] { 2 };
        d_arr = new int[] { 0, 1, 2, 3, 4, 5 };
        e_arr = new int[] { 2, 3, 5 };
        f_arr = new int[] { 0, 2, 3, 4, 5 };

    }

    public static void main(String[] args) {
        init();
        for (Integer a : a_arr)
            for (Integer b : b_arr)
                if (a != b)
                    for (Integer c : c_arr)
                        if (a != c && b != c)
                            for (Integer d : d_arr)
                                if (a != d && b != d && c != d)
                                    for (Integer e : e_arr)
                                        if (a != e && b != e && c != e && d != e)
                                            for (Integer f : f_arr)
                                                if (a != f && b != f && c != f && d != f && e != f)
                                                    System.out.printf("a:%d,b:%d,c:%d,d:%d,e:%d,f:%d\n", a, b, c, d, e,
                                                            f);

    }
}
01-08 08:10
查看更多