gpt4 book ai didi

java - 顺序搜索 Java

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:36:52 26 4
gpt4 key购买 nike

我在按顺序搜索时遇到问题,这是练习:

You are testing the physical endurance of a type of brick. The test is made to find the max height the brick can fall without breaking from and N stories building. You have k bricks and two cases:

Case 1. When k = 1 the tries begin from the current floor upwards, sequentially, until the brick breaks.

Case 2. For k > 1 one brick is dropped from floor N/2. If it breaks, case 2 is applied again between floors 1 and N/2 -1. If the brick does not break, case 2 is applied again between floors N/2 + 1 and N.

我对案例 1 的原因有疑问,因为我不知道如何处理它:

Initially you call dropBricks(k,1,N); Being k, and N introduced by the User(Keyboard).

public static boolean breakingFloor(int floor){
boolean breaks;
Random r =new Random();
int breakingFloor= r.nextInt(floor)+1;

if(floor>=breakingFloor){
breaks=true;
}else{
breaks=false;
}

return breaks;
}

dropBricks receives k(number of remaining bricks, first (first floor),last (last floor = N)) and the output would be the breakingFloor

public static int dropBricks(int k,int first,int last){
int result=0;

if (k==1){//CASE 1
//I KNOW THIS CODE IS WRONG, IS JUST O NOT LEAVE IT IN EMPTY
do{
dropBricks(k,first,last);
first++;
}while(breakingFloor(first));
System.out.println("Floor brick broke "+floor);

}else{//CASE 2
if(last-first<=1){
if(last==first){
result=first;
System.out.println("Floor brick broke "+result);
}else{
if(breakingFloor(first)){
result=first;
k--;
System.out.println("Floor brick broke "+result);
}else{
result=last;
k--;
System.out.println("Floor brick broke "+result);
}
}
}else{
int mid=((first+last)/2);
if(breakingFloor(mid)){
result=dropBricks(k-1,first,mid);
System.out.println("Floor brick broke "+result);
}else{
result=dropBricks(k,mid,last);
System.out.println("Floor brick broke "+result);
}
}
}
return result;
}

最佳答案

您的问题 - 或者至少其中之一 - 是每次您绕过这个循环...

do{
dropBricks(k,first,last);
first++;
} while( breakingFloor(first) );

...您正在选择一个新的随机楼层,它会在该楼层破裂(发生在 breakingFloor 方法中):

Random r =new Random();
int breakingFloor= r.nextInt(floor)+1;

这肯定会给您带来非常不一致的行为。它有时可能真的会侥幸成功。

您想选择它在开始时会破裂的地板并使其保持不变。

测试您的应用程序的明智方法可能是先对断层进行硬编码,然后再引入随机性。

关于java - 顺序搜索 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com