繁体   English   中英

如何在我的backtracker(java)中实现呢?

[英]How can I implement that in my backtracker (java)?

我做了一个小的Java程序。 整数将是输入,然后将随机数打印到控制台,直到找到该整数输入为止。 该代码会作弊,因为它将知道输入数字有多少位数。

将使用随机数,我要排除的是已使用的每个随机数。 但是我不知道该怎么做。 好吧,我有一个主意,但这将是我不喜欢的廉价旁路。 它将从0开始,并且始终将其增加1的值,直到找到输入为止。

可以在Java中完成(排除使用的随机数)吗?

我想我们可以列出一个清单,以便每个使用的号码都在该清单中。 在每个循环中,访问列表以检查数字是否未使用。 但这仅仅是想象,在Java中真的可能吗?

import java.util.Scanner;
import java.util.Random;

public class Backtracker{
    public static void main(String[]args){
        int counter = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter integer here: ");
        int x = input.nextInt();
        Random rand = new Random();
        int a = rand.nextInt(100)+0;
        int b = rand.nextInt(1000)+100;
        int c = rand.nextInt(10000)+1000;
        int d = rand.nextInt(100000)+10000;
        int e = rand.nextInt(1000000)+10000;
        int f = rand.nextInt(10000000)+1000000;
        int g = rand.nextInt(100000000)+10000000;

        if(x<=100){
            while(x != a){
                a = rand.nextInt(100)+0;
                System.out.println(a);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }

        else if(x<=1000){
            while(x != b){
                b = rand.nextInt(1000)+100;
                System.out.println(b);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }

        else if(x<=10000){
            while(x != c){
                c = rand.nextInt(10000)+1000;
                System.out.println(c);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }

        else if(x<=100000){
            while(x != d){
                d = rand.nextInt(100000)+10000;
                System.out.println(d);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }

        else if(x<=1000000){
            while(x != e){
                e = rand.nextInt(1000000)+100000;
                System.out.println(e);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }

        else if(x<=10000000){
            while(x != f){
                f = rand.nextInt(10000000)+1000000;
                System.out.println(f);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }

        else if(x<=100000000){
            while(x != g){
                g = rand.nextInt(100000000)+10000000;
                System.out.println(g);
                counter++;
            }
            System.out.println("Tries: "+counter);
        }
    }
}

使用随机数听起来不是一个好的解决方案,也不是从1算起。一个好的简单的解决方案可能是:

a)给定一个约束,输入n必须为0

b)使用基本的二进制搜索

由于这听起来像是一项任务,所以我不会为该解决方案编写代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM