Given n coins and a pan balance,find the only counterfeit 2

本文介绍了一个基于递归的算法,该算法通过将球分成几组并使用天平进行比较,来找出不同重量的球。算法考虑了不同数量的球,并在每个递归步骤中有效地缩小搜索范围。
Now it comes to the Scale class. The main job of it is to weight both sides. So the class is pretty simple, sum the weights of balls and compare.

Now based on these classes, the translation of the algorithm is straight forward:

java 代码
 
  1. package solve;  
  2.   
  3. import scale.Ball;  
  4. import scale.Scale;  
  5.   
  6. import java.util.Set;  
  7. import java.util.Iterator;  
  8. import java.util.HashSet;  
  9.   
  10. public class ProblemSolver  
  11. {  
  12.     private Set orignalballSet;  
  13.   
  14.     private Scale scale = new Scale();  
  15.   
  16.     public ProblemSolver(Set orignalballSet)  
  17.     {  
  18.         this.orignalballSet = orignalballSet;  
  19.     }  
  20.   
  21.     public void findWeight()  
  22.     {  
  23.         findBadBall(this.orignalballSet);  
  24.     }  
  25.   
  26.     private void findBadBall(Set ballSet)  
  27.     {  
  28.         int ballSetSize = ballSet.size();  
  29.   
  30.         // recursion defaults  
  31.         if (ballSetSize == 1)  
  32.         {  
  33.             OneBallCaseSolver solver = new OneBallCaseSolver();  
  34.             solver.setScale(scale);  
  35.             solver.setOriginalBallSet(orignalballSet);  
  36.             solver.findWeight(ballSet);  
  37.             return;  
  38.         }  
  39.         else if (ballSetSize == 2)  
  40.         {  
  41.             TwoBallCaseSolver solver = new TwoBallCaseSolver();  
  42.             solver.setScale(scale);  
  43.             solver.setOriginalBallSet(orignalballSet);  
  44.             solver.findWeight(ballSet);  
  45.             return;  
  46.         }  
  47.         else if (ballSetSize == 3)  
  48.         {  
  49.             ThreeBallCaseSolver solver = new ThreeBallCaseSolver();  
  50.             solver.setScale(scale);  
  51.             solver.findWeight(ballSet);  
  52.             return;  
  53.         }  
  54.   
  55.         // recursion starts here.  
  56.   
  57.         // check whether all elements are marked. If so, then by the lemma,  
  58.         //     It takes at most n times of weighing to point out the defect one  
  59.         //     with the weigh, if N < 3^n, where N is the number of balls.  
  60.         // In order to check all balls, it's sufficient to check just one  
  61.         // because we either mark all or none.  
  62.         // With the marks, we definitely weigh less times.  
  63.         Ball firstBall = (Ball)ballSet.iterator().next();  
  64.         if (!firstBall.getStatus().equals(Ball.UNKNOWN))  
  65.         {  
  66.             findWithMarks(ballSet);  
  67.             return;  
  68.         }  
  69.   
  70.         // if we get here, this means no mark is found, so we blindly populate  
  71.         // An extra good ball would reduce the size of the group, said in this lemma:  
  72.         //     If an extra genuine good is available, when the defect ball can be found with  
  73.         //     the weigh in N ball by n trials, where N <= (3^n - 1)/2.  
  74.         // In fact, using these two lemmas we can prove, by deduction, the entire problem:  
  75.         //     Given N balls, if N <= (3^n - 3)/2, then we can findBadBall it with weigh in n trials.  
  76.         // This call is confusing: even the above if block is not marked, the whole set could have a good ball  
  77.         // one case is when we have a even scale, and this is the third group.  
  78.         Ball goodBall = Utils.findGoodBall(this.orignalballSet);  
  79.   
  80.         int subsize = ballSetSize / 3// divided into 3 groups  
  81.         if (goodBall != null)  
  82.         {  
  83.             subsize++; // for the good ball we are adding in.  
  84.         }  
  85.         else if (ballSetSize % 3 == 2)  
  86.         {  
  87.             subsize++; // use the groups with equal sizes.  
  88.         }  
  89.   
  90.         HashSet group1 = new HashSet(subsize);  
  91.         HashSet group2 = new HashSet(subsize);  
  92.         HashSet group3 = new HashSet(ballSetSize - 2*subsize);  
  93.   
  94.         if (goodBall != null) group1.add(goodBall);  
  95.   
  96.         Iterator it = ballSet.iterator();  
  97.         // fill in group1 first.  
  98.         while (it.hasNext())  
  99.         {  
  100.             if (group1.size() < subsize) group1.add(it.next());  
  101.             if (group1.size() >= subsize) break;  
  102.         }  
  103.   
  104.         // fill in group2 first.  
  105.         while (it.hasNext())  
  106.         {  
  107.             if (group2.size() < subsize) group2.add(it.next());  
  108.             if (group2.size() >= subsize) break;  
  109.         }  
  110.   
  111.         // put the rest into group3  
  112.         while (it.hasNext())  
  113.         {  
  114.             group3.add(it.next());  
  115.         }  
  116.           
  117.         int scaleResult = scale.weigh(group1, group2);  
  118.         if (scaleResult == Scale.EVEN)  
  119.         {  
  120.             Utils.markStatus(group1, Ball.NORMAL);  
  121.             Utils.markStatus(group2, Ball.NORMAL);  
  122.   
  123.   
  124.             findBadBall(group3);  
  125.         }  
  126.         else // the counterfeit is not in group3, it's in group1 or group2  
  127.         {  
  128.             Utils.markStatus(group3, Ball.NORMAL);  
  129.   
  130.             Utils.markStatus(group1, Utils.convertToBallStatus(scaleResult));  
  131.             Ball goodput = Utils.findGoodBall(group1);  
  132.             if (goodput != null)  
  133.             {  
  134.                 group1.remove(goodput);  
  135.             }  
  136.   
  137.             Utils.markStatus(group2, Utils.convertToBallStatus(-scaleResult));  
  138.             goodput = Utils.findGoodBall(group2);  
  139.   
  140.             if (goodput != null)  
  141.             {  
  142.                 group2.remove(goodput);  
  143.             }  
  144.   
  145.             Set newSet = new HashSet(group1.size() + group2.size());  
  146.             Iterator itt = group1.iterator();  
  147.             while (itt.hasNext()) newSet.add(itt.next());  
  148.             itt = group2.iterator();  
  149.             while (itt.hasNext()) newSet.add(itt.next());  
  150.   
  151.             findWithMarks(newSet);  
  152.         }  
  153.     }  
  154.   
  155.     //=======================================================================  
  156.     // Some big ugly codes go to here  
  157.     //=======================================================================  
  158.     private void findWithMarks(Set src)  
  159.     {  
  160.         int size = src.size();  
  161.   
  162.         int subsize = size / 3// divided into 3 groups  
  163.         if (size % 3 == 2) subsize++; // use the groups with equal sizes.  
  164.   
  165.         HashSet group1 = new HashSet(subsize);  
  166.         HashSet group2 = new HashSet(subsize);  
  167.         HashSet group3 = new HashSet(size - 2*subsize); // this is the off scale group  
  168.   
  169.         // now we need to populate in such a way so that group1 and group2  
  170.         // have equal number of same weigh, both for 1 and -1. The reason  
  171.         // we need this is because in some cases, we need to switch them in  
  172.         // forming nextGroup.  
  173.         evenlyDistribute(src, group1, group2, group3, subsize);  
  174.   
  175.         if (group1.size() > 0)  
  176.         {  
  177.             int result = scale.weigh(group1, group2);  
  178.             if (result == Scale.EVEN)  
  179.             {  
  180.                 // mark group1 and group2  
  181.                 Utils.markStatus(group1, Ball.NORMAL);  
  182.                 Utils.markStatus(group2, Ball.NORMAL);  
  183.                 findBadBall(group3);  
  184.             }  
  185.             // get lighter balls from lighter groups, get heavier balls from heavier groups  
  186.             else if (result == Scale.HEAVIER)  
  187.             {  
  188.                 Utils.markStatus(group3, Ball.NORMAL);  
  189.   
  190.                 HashSet nextGroup = new HashSet();  
  191.                 getHeavier(group1, nextGroup);  
  192.                 getLighter(group2, nextGroup);  
  193.                 findBadBall(nextGroup);  
  194.             }  
  195.             else // -1  
  196.             {  
  197.                 Utils.markStatus(group3, Ball.NORMAL);  
  198.   
  199.                 HashSet nextGroup = new HashSet();  
  200.                 getHeavier(group2, nextGroup);  
  201.                 getLighter(group1, nextGroup);  
  202.                 findBadBall(nextGroup);  
  203.             }  
  204.         }  
  205.         else  
  206.         {  
  207.             findBadBall(group3);  
  208.         }  
  209.     }  
  210.   
  211.     private void getHeavier(Set src, Set des)  
  212.     {  
  213.         for (Iterator it=src.iterator(); it.hasNext();)  
  214.         {  
  215.             Ball ball = (Ball)it.next();  
  216.             if (ball.getStatus().equals(Ball.HEAVIER)) des.add(ball);  
  217.             else ball.setStatus(Ball.NORMAL);  
  218.         }  
  219.     }  
  220.   
  221.     private void getLighter(Set src, Set des)  
  222.     {  
  223.         for (Iterator it=src.iterator(); it.hasNext();)  
  224.         {  
  225.             Ball ball = (Ball)it.next();  
  226.             if (ball.getStatus().equals(Ball.LIGHTER)) des.add(ball);  
  227.             else ball.setStatus(Ball.NORMAL);  
  228.         }  
  229.     }  
  230.   
  231.     // This will distribute src to des1, des2, and des3. Assuming src is marked  
  232.     // with proper weigh 1, -1. des1 and des2 should have the same number of  
  233.     // balls with weigh 1, and should have the same number of balls of weigh  
  234.     // -1. The rest of src goes to des3, which should be the off scale group.  
  235.     // size is the size of des1, des2.  
  236.     private void evenlyDistribute(Set src, Set des1, Set des2, Set des3, int size)  
  237.     {  
  238.         int heavierSum1 = 0;  
  239.         int lighterSum1 = 0;  
  240.         int heavierSum2 = 0;  
  241.         int lighterSum2 = 0;  
  242.         Ball heavierPair = null;  
  243.         int heavierPairMarker = 0// 0 for no pair, 1 for pair  
  244.         Ball lighterPair = null;  
  245.         int lighterPairMarker = 0// 0 for no pair, 1 for pair  
  246.   
  247.         Iterator itm1 = src.iterator();  
  248.         while (itm1.hasNext())  
  249.         {  
  250.             Ball ball = (Ball)itm1.next();  
  251.             if (des1.size() >= size)  
  252.             {  
  253.                 des3.add(ball);  
  254.             }  
  255.             else if (ball.getStatus().equals(Ball.HEAVIER))  
  256.             {  
  257.                 if (heavierSum1 > heavierSum2)  
  258.                 {  
  259.                     des2.add(ball);  
  260.                     heavierSum2++;  
  261.                 }  
  262.                 else if (heavierSum1 < heavierSum2)  
  263.                 {  
  264.                     des1.add(ball);  
  265.                     heavierSum1++;  
  266.                 }  
  267.                 else // heavierSum1==heavierSum2  
  268.                 {  
  269.                     if (heavierPairMarker == 0// this is the first one  
  270.                     {  
  271.                         // save this, set marker, wait for the next one.  
  272.                         heavierPair = ball;  
  273.                         heavierPairMarker = 1;  
  274.                     }  
  275.                     else // ==1, already a ball there, now set one for each group  
  276.                     {  
  277.                         des1.add(heavierPair);  
  278.                         des2.add(ball);  
  279.                         // reset marker to 0  
  280.                         heavierPair = null;  
  281.                         heavierPairMarker = 0;  
  282.                     }  
  283.                 }  
  284.             }  
  285.             else if (ball.getStatus().equals(Ball.LIGHTER))  
  286.             {  
  287.                 if (lighterSum1 > lighterSum2)  
  288.                 {  
  289.                     des2.add(ball);  
  290.                     lighterSum2++;  
  291.                 }  
  292.                 else if (lighterSum1 < lighterSum2)  
  293.                 {  
  294.                     des1.add(ball);  
  295.                     lighterSum1++;  
  296.                 }  
  297.                 else // lighterSum1==lighterSum2  
  298.                 {  
  299.                     if (lighterPairMarker == 0// this is the first one  
  300.                     {  
  301.                         // save this, set marker, wait for the next one.  
  302.                         lighterPair = ball;  
  303.                         lighterPairMarker = 1;  
  304.                     }  
  305.                     else // ==1, already a ball there, now set one for each group  
  306.                     {  
  307.                         des1.add(lighterPair);  
  308.                         des2.add(ball);  
  309.                         // reset marker to 0  
  310.                         lighterPair = null;  
  311.                         lighterPairMarker = 0;  
  312.                     }  
  313.                 }  
  314.             }  
  315.             else  
  316.             {  
  317.                 System.out.println("This ball is not marked: " + ball + " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!");  
  318.             }  
  319.         }  
  320.         // At the very last, if there are any left, add them to des3 since des1 and des2 are full, by now.  
  321.         if (lighterPair != null) des3.add(lighterPair);  
  322.         if (heavierPair != null) des3.add(heavierPair);  
  323.     }  
  324.   
  325.     public Scale getScale() { return this.scale; }  
  326. }  

Though this is a direct translation of the algorithm described in the book. There are 3 trivial cases served as the basis for the recursion. Taking into account that they are the base cases, they are not as trivial as one thinks.
Sally Jones has a dozen Voyageur silver dollars. However, only eleven of the coins are true silver dollars; one coin is counterfeit even though its color and size make it indistinguishable from the real silver dollars. The counterfeit coin has a different weight from the other coins but Sally does not know if it is heavier or lighter than the real coins. Happily, Sally has a friend who loans her a very accurate balance scale. The friend will permit Sally three weighings to find the counterfeit coin. For instance, if Sally weighs two coins against each other and the scales balance then she knows these two coins are true. Now if Sally weighs one of the true coins against a third coin and the scales do not balance then Sally knows the third coin is counterfeit and she can tell whether it is light or heavy depending on whether the balance on which it is placed goes up or down, respectively. By choosing her weighings carefully, Sally is able to ensure that she will find the counterfeit coin with exactly three weighings. 输入 The first line of input is an integer n (n > 0) specifying the number of cases to follow. Each case consists of three lines of input, one for each weighing. Sally has identified each of the coins with the letters A--L. Information on a weighing will be given by two strings of letters and then one of the words ``up'', ``down'', or ``even''. The first string of letters will represent the coins on the left balance; the second string, the coins on the right balance. (Sally will always place the same number of coins on the right balance as on the left balance.) The word in the third position will tell whether the right side of the balance goes up, down, or remains even. 输出 For each case, the output will identify the counterfeit coin by its letter and tell whether it is heavy or light. The solution will always be uniquely determined. 样例输入 1 ABCD EFGH even ABCI EFJK up ABIJ EFGH even 样例输出 K is the counterfeit coin and it is light.用c语音写
04-03
内容概要:本文围绕EKF SLAM(扩展卡尔曼滤波同步定位与地图构建)的性能展开多项对比实验研究,重点分析在稀疏与稠密landmark环境下、预测与更新步骤同时进行与非同时进行的情况下的系统性能差异,并进一步探讨EKF SLAM在有色噪声干扰下的鲁棒性表现。实验考虑了不确定性因素的影响,旨在评估不同条件下算法的定位精度与地图构建质量,为实际应用中EKF SLAM的优化提供依据。文档还提及多智能体系统在遭受DoS攻击下的弹性控制研究,但核心内容聚焦于SLAM算法的性能测试与分析。; 适合人群:具备一定机器人学、状态估计或自动驾驶基础知识的科研人员及工程技术人员,尤其是从事SLAM算法研究或应用开发的硕士、博士研究生和相关领域研发人员。; 使用场景及目标:①用于比较EKF SLAM在不同landmark密度下的性能表现;②分析预测与更新机制同步与否对滤波器稳定性与精度的影响;③评估系统在有色噪声等非理想观测条件下的适应能力,提升实际部署中的可靠性。; 阅读建议:建议结合MATLAB仿真代码进行实验复现,重点关注状态协方差传播、观测更新频率与噪声模型设置等关键环节,深入理解EKF SLAM在复杂环境下的行为特性。稀疏 landmark 与稠密 landmark 下 EKF SLAM 性能对比实验,预测更新同时进行与非同时进行对比 EKF SLAM 性能对比实验,EKF SLAM 在有色噪声下性能实验
内容概要:本文围绕“基于主从博弈的售电商多元零售套餐设计与多级市场购电策略”展开,结合Matlab代码实现,提出了一种适用于电力市场化环境下的售电商优化决策模型。该模型采用主从博弈(Stackelberg Game)理论构建售电商与用户之间的互动关系,售电商作为领导者制定电价套餐策略,用户作为跟随者响应电价并调整用电行为。同时,模型综合考虑售电商在多级电力市场(如日前市场、实时市场)中的【顶级EI复现】基于主从博弈的售电商多元零售套餐设计与多级市场购电策略(Matlab代码实现)购电组合优化,兼顾成本最小化与收益最大化,并引入不确定性因素(如负荷波动、可再生能源出力变化)进行鲁棒或随机优化处理。文中提供了完整的Matlab仿真代码,涵盖博弈建模、优化求解(可能结合YALMIP+CPLEX/Gurobi等工具)、结果可视化等环节,具有较强的可复现性和工程应用价值。; 适合人群:具备一定电力系统基础知识、博弈论初步认知和Matlab编程能力的研究生、科研人员及电力市场从业人员,尤其适合从事电力市场运营、需求响应、售电策略研究的相关人员。; 使用场景及目标:① 掌握主从博弈在电力市场中的建模方法;② 学习售电商如何设计差异化零售套餐以引导用户用电行为;③ 实现多级市场购电成本与风险的协同优化;④ 借助Matlab代码快速复现顶级EI期刊论文成果,支撑科研项目或实际系统开发。; 阅读建议:建议读者结合提供的网盘资源下载完整代码与案例数据,按照文档目录顺序逐步学习,重点关注博弈模型的数学表达与Matlab实现逻辑,同时尝试对目标函数或约束条件进行扩展改进,以深化理解并提升科研创新能力。
内容概要:本文介绍了基于粒子群优化算法(PSO)的p-Hub选址优化问基于粒子群优化算法的p-Hub选址优化(Matlab代码实现)题的Matlab代码实现,旨在解决物流与交通网络中枢纽节点的最优选址问题。通过构建数学模型,结合粒子群算法的全局寻优能力,优化枢纽位置及分配策略,提升网络传输效率并降低运营成本。文中详细阐述了算法的设计思路、实现步骤以及关键参数设置,并提供了完整的Matlab仿真代码,便于读者复现和进一步改进。该方法适用于复杂的组合优化问题,尤其在大规模网络选址中展现出良好的收敛性和实用性。; 适合人群:具备一定Matlab编程基础,从事物流优化、智能算法研究或交通运输系统设计的研究生、科研人员及工程技术人员;熟悉优化算法基本原理并对实际应用场景感兴趣的从业者。; 使用场景及目标:①应用于物流中心、航空枢纽、快递分拣中心等p-Hub选址问题;②帮助理解粒子群算法在离散优化问题中的编码与迭代机制;③为复杂网络优化提供可扩展的算法框架,支持进一步融合约束条件或改进算法性能。; 阅读建议:建议读者结合文中提供的Matlab代码逐段调试运行,理解算法流程与模型构建逻辑,重点关注粒子编码方式、适应度函数设计及约束处理策略。可尝试替换数据集或引入其他智能算法进行对比实验,以深化对优化效果和算法差异的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值