Java算法八:八枚银币

八枚银币(Coins)

问题说明:

现在有八枚银币abcdefg,已知其中一枚是假币,其重量不同于真币,但不知道是轻还是重,如何用天平以最小的比较次数决定出那个是假币,并得知假币是比真币轻还是重。

结果:

Java代码:

package com.allen;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

 

public class Coins {

private int[] coins;

   

    public Coins() {

        coins = new int[8];

        for(int i = 0; i < 8; i++)

            coins[i] = 10;

    }

   

    public void setFake(int weight) {

        coins[(int) (Math.random() * 7)] = weight;

    }

   

    public void fake() {

        if(coins[0]+coins[1]+coins[2] ==

          coins[3]+coins[4]+coins[5]) {

            if(coins[6] > coins[7])

                compare(6, 7, 0);

            else

                compare(7, 6, 0);

        }

        else if(coins[0]+coins[1]+coins[2] >

                coins[3]+coins[4]+coins[5]) {

            if(coins[0]+coins[3] == coins[1]+coins[4])

                compare(2, 5, 0);

            else if(coins[0]+coins[3] > coins[1]+coins[4])

                compare(0, 4, 1);

            if(coins[0]+coins[3] < coins[1]+coins[4])

                compare(1, 3, 0);

        }

        else if(coins[0]+coins[1]+coins[2] <

                coins[3]+coins[4]+coins[5]) {

            if(coins[0]+coins[3] == coins[1]+coins[4])

                compare(5, 2, 0);

            else if(coins[0]+coins[3] > coins[1]+coins[4])

                compare(3, 1, 0);

            if(coins[0]+coins[3] < coins[1]+coins[4])

                compare(4, 0, 1);

        }

    }

   

    protected void compare(int i, int j, int k) {

        if(coins[i] > coins[k])

            System.out.print("\n假币 " + (i+1) + " 较重");

        else

            System.out.print("\n假币 " + (j+1) + " 较轻");

    }

   

    public static void main(String[] args)  {

        if(args.length == 0) {

          System.out.println("输入假币重量(比10大或小),ex:6");

            return;

        }

       

        Coins eightCoins = new Coins();

        eightCoins.setFake(Integer.parseInt(args[0]));

        eightCoins.fake();

    }

}

这里if(args.length == 0)需要设置一下参数:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AllenGd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值