| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
|* |
Run Code Online (Sandbox Code Playgroud)
我需要为Gambler's Ruin问题打印类似上面的ASCII图.利益和目标被视为args.最左边的 代表0美元,最右边| 代表目标,*代表现金.我的计划如下:
public class RuinPath {
public static void main(String[] args) {
// TODO - Your solution
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
{
int i = 0;
if (i == 0) {
System.out.print("|");
i++;
while (i < stake) {
System.out.print(" ");
i++;
if (i == stake) {
System.out.print("*");
i++;
while (i > stake && i < goal) {
System.out.print(" ");
i++;
if (i == goal) {
System.out.print("|");
i = 0;
System.out.println();
{
if (Math.random() < 0.5) {
stake++; // win $1
} else {
stake--; // lose $1
}
if (stake == 1 || stake == goal - 1);
break;
}
}
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序打印的是:
| * |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
*
Run Code Online (Sandbox Code Playgroud)
为什么我的程序没有循环,所以我可以得到最左边的| 似乎代表0美元一路走来?我有它所以我= 0; 在循环结束时,当它返回时它应该重新循环,直到赌注是1或小于目标.相反,它从程序的中间重新循环.
这是一个可能更容易推理的突破性解决方案:
import java.io.PrintStream;
public class SO {
private static int gambleWithCaution(int stake) {
if (Math.random() < 0.5) {
return stake+1; // win $1
} else {
return stake-1; // lose $1
}
}
private static void renderStanding(int stake, int goal) {
System.out.print('|');
for(int dollar = 1; dollar< goal; dollar++) {
if(dollar == stake) {
System.out.print('*');
} else {
System.out.print(' ');
}
}
System.out.println('|');
}
public static void main(String ... args) {
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
while(stake > 0 && stake < goal) {
renderStanding(stake, goal);
stake = gambleWithCaution(stake);
}
System.out.println((stake > goal) ? "You Won!" : "You Lost");
}
}
Run Code Online (Sandbox Code Playgroud)
通过这些值3,5您将得到以下输出:
| * |
| * |
|* |
| * |
| * |
| *|
| * |
| *|
You Won!
Run Code Online (Sandbox Code Playgroud)
现在这已经被分开了,你可以享受一些乐趣,比如创建一个赌博函数,如下所示:
private static int gambleWithReclessAbandon(int stake, int goal, double abandon) {
int onTheLine = (int)(Math.random() * (int)(stake * abandon));
if(stake < (0.5)*goal) {
//If you are at less than 50% of your goal then just put it all on the line
//and let it ride :)
onTheLine = stake;
}
if (Math.random() < 0.5) {
return stake+onTheLine; // win $
} else {
return stake-onTheLine; // lose $
}
}
Run Code Online (Sandbox Code Playgroud)
可以这样调用:
//Gamble up to 80% of your current stake
stake = gambleWithReclessAbandon(stake, goal, 0.80);
Run Code Online (Sandbox Code Playgroud)
具有相同的两个值,这是我在第一次通过时看到的(我非常接近:)):
| * |
| * |
| *|
| * |
| *|
You Lost
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
691 次 |
| 最近记录: |