java 如何显示可以从一串数字创建的IP地址的所有组合?

1zmg4dgp  于 2023-01-01  发布在  Java
关注(0)|答案(7)|浏览(171)

我需要将输入字符串格式化为IP地址格式,所以我有以下代码;然而,数字是固定的,我不确定如何为单个输入生成不同的值。
其他的限制是确保没有一组数字超过255,但在这种情况下,我只想把它们放在四个单独的组中,每个组必须有1到3个成员。

**Vimal's question:**From provided string 19216801, I think you cant identify exact ip. It can be 192.168.0.1 or 19.216.80.1 or any other combination.

    • 回答:**我不需要查找任何特定的IP,我只需要显示所有可能的组合。
    • 示例格式**

其中一些组合如下所示

Expected result | number of input characters

   1.1.1.1             4 
     ....
   1.1.1.2             5
   1.1.2.1  
   1.2.1.1  
   2.1.1.1 
     ....       
   1.1.1.3             6
   1.1.3.1  
   1.3.1.1   
   3.1.1.1  
     ....
   2.2.2.1             7
   2.2.1.2 
     ....
   2.2.2.2             8
   3.2.2.1 
   1.2.2.3 
     ....
   2.2.2.3             9 
   3.3.2.1 
   1.2.3.3 
     ....
   3.3.3.1             10
   3.3.1.3  
   3.1.3.3
   1.3.3.3 
     ....
   3.3.3.2             11
   3.3.2.3 
   3.2.3.3 
     ....
   3.3.3.3             12
    • 代码**
String number = "19216801";
if (number.length() == 4) {
    StringBuilder sb = new StringBuilder(number)
            .insert(1, ".")
            .insert(1, ".")
            .insert(1, ".")
            .insert(1, ".");
    String output = sb.toString();
    System.out.println(output);
}
 if (number.length() == 8) {
    StringBuilder sb = new StringBuilder(number)
            .insert(2, ".")
            .insert(2, ".")
            .insert(2, ".")
            .insert(2, ".");
    String output = sb.toString();
    System.out.println(output);
}
  if (number.length() == 12) {
    StringBuilder sb = new StringBuilder(number)
            .insert(3, ".")
            .insert(3, ".")
            .insert(3, ".")
            .insert(3, ".");
    String output = sb.toString();
    System.out.println(output);
}
vzgqcmou

vzgqcmou1#

用下一种方法重新表述任务。
1.假设IP部分可以具有零数字,因此...是有效
1.然后我们有number.length()- 3个元素,需要在任意位置放置3个点
1.设abc为部件长度
1.第一部分可以是任意长度for(int a = 0; a < l; a++)
1.第二个必须更短for(int b = 0; b < l-a; b++)
1.与第三个相同,总长度必须为l。因此l〉=a+b+c是约束。c
1.把点放在它的地方。
1.第一个点在第一部分之后(不要忘记达特第一步我们从每一部分中删去一个数字)。
1.第二部分在第一部分、第一点和第二部分之后((a +1)+ 1 +(B+1))
1.第三个相同。跳过第一部分(a+1)、点(+1)、第二部分(+B+1)、第二点(+1)和第三部分(c+1)= a+b+c+5

String number = "19216801";
int l = number.length() - 3;
for(int a = 0; a < l; a++) {
    for(int b = 0; b < l-a; b++){
        for(int c = 0; c <l-a-b; c++){
            StringBuilder sb = new StringBuilder(number);
            sb.insert(a+1, ".");
            sb.insert(a+b+3, ".");
            sb.insert(a+b+c+5, ".");
            System.out.println(sb);
        }
    }
}

这很难解释,大多数代码来自我的思想背景,我只是写它。

nwo49xxi

nwo49xxi2#

在没有进一步信息的情况下,您必须依靠推测来从可变长度字符串形成IP地址。
您应该不允许这样做,并确保字符串长度为12个字符。
一旦您形成了一个候选IP地址,您可以使用以下 * 正则表达式 *(使用String.matches)验证它

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
  (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
  (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
  (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
kq0g1dla

kq0g1dla3#

public class IPAddress {
    static Queue<List<StringBuilder>> queue=new LinkedList<List<StringBuilder>>();
    static int count =0;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try(Scanner reader=new Scanner(System.in)){
            String str=reader.nextLine();
            if(init(str)==-1)
                System.out.println("IPAddress cannot be formed");
            ipAddress();
        }

    }

    private static void ipAddress() {
        // TODO Auto-generated method stub

        int noOfGroups=4;

        int group=noOfGroups-1;
        int countInOneLevel=1, childCount=0;
            while(!queue.isEmpty() && countInOneLevel>0 && group>0){
                List<StringBuilder> list=queue.poll();
                countInOneLevel--;
                StringBuilder currentGroup=list.get(group);
                StringBuilder prevGroup=list.get(group-1);
                while(currentGroup.length()>1){
                    prevGroup.append(currentGroup.charAt(0));
                    currentGroup=currentGroup.deleteCharAt(0);
                    if(makeIPAdress(list, group)==1 ){
                        childCount++;
                    }

                }
                if(countInOneLevel==0){//current level complete
                    countInOneLevel=childCount;
                    group--;
                    childCount=0;
                }

            }

        System.out.println("No. of possible IPAddress: "+count);

}

    private static int init(String str) {
        // TODO Auto-generated method stub
        int length=str.length();
        if(length<4 || length>12)
            return -1;
        StringBuilder strgroup[]= new StringBuilder[4];
        int groups=4;
        for(int i=0;i<groups-1;i++){
            strgroup[i]=new StringBuilder(str.substring(i,i+1));
        }
        strgroup[groups-1]=new StringBuilder(str.substring(3,length));
        List<StringBuilder> list=new ArrayList<StringBuilder>();
        for(int i=0;i<groups;i++){
            list.add(strgroup[i]);
        }
        return makeIPAdress(list,groups-1);

    }

    private static int makeIPAdress(List<StringBuilder> list, int i) {
        // TODO Auto-generated method stub
        if(isValidIPAdress(list)){
            List<StringBuilder> list1=new ArrayList<StringBuilder>();
            for(int k=0;k<4;k++){
                StringBuilder s=new StringBuilder(list.get(k).toString());
                list1.add(s);
            }
            queue.offer(list1);
            display(list);
            count++;
            return 1;
        }
        for(int group=i;group>0;group--){
            StringBuilder currentGroup=list.get(group);
            StringBuilder prevGroup=list.get(group-1);
            int num=Integer.parseInt(currentGroup.toString());
            while(num<0|| num>255){
                prevGroup.append(currentGroup.charAt(0));
                currentGroup=currentGroup.deleteCharAt(0);
                num=Integer.parseInt(currentGroup.toString());
            }

        }
        StringBuilder firstGroup=list.get(0);
        int num=Integer.parseInt(firstGroup.toString());
        if(num>=0 && num<=255){
            List<StringBuilder> list1=new ArrayList<StringBuilder>();
            for(int k=0;k<4;k++){
                StringBuilder s=new StringBuilder(list.get(k).toString());
                list1.add(s);
            }

            queue.offer(list1);
            display(list);
            count++;
            return 1;
        }
        return -1;

    }

    private static boolean isValidIPAdress(List<StringBuilder> list) {
        // TODO Auto-generated method stub
        for(int group=0;group<4;group++){
            int num=Integer.parseInt(list.get(group).toString());
            if(num<0 || num>255)
                return false;
        }
        return true;
    }

    private static void display(List<StringBuilder> list) {
        // TODO Auto-generated method stub
        Iterator<StringBuilder> i=list.iterator();
        while(i.hasNext()){
            StringBuilder s=i.next();
            if(!i.hasNext())
                System.out.print(s);
            else
                System.out.print(s+".");

        }
        System.out.println();
    }

}

Sample Input:
2252555

Sample Output:
2.25.25.55
2.25.255.5
2.252.55.5
225.25.5.5
22.52.55.5
225.2.55.5
No. of possible IPAddress: 6
643ylb08

643ylb084#

下面是一个递归解决方案:

public static void main(String[] args){

    System.out.println(findIPs("1234567", 3));
}

public static List<String> findIPs(String s,int dots){

    List<String> ips = new ArrayList<>();

    for(int i =1 ;i<=3 && i < s.length(); i++){

        String cip = s.substring(0,i);

        if(Integer.parseInt(cip) < 256){
            if(dots == 1){
                if( Integer.parseInt(s.substring(i)) < 256) {
                    ips.add(cip + "." + s.substring(i));
                }
            }else {
                for (String ip : findIPs(s.substring(i), dots - 1)) {
                    ips.add(cip + "." + ip);
                }
            }
        }
    }

    return ips;

}
gmxoilav

gmxoilav5#

下面是解决上述解决方案之一的错误ips问题的解决方案

private static List<String> ips = new ArrayList<>();
    public static void main(String[] args) {

        Date d = new Date();
        System.out.println(posIps("19216801"));
        System.out.println(new Date().getTime() - d.getTime());

    }

    private static List<String> posIps(String number) {
        int l = number.length() - 3;
        for (int a = 0; a < 3 && a < l; a++) {
            for (int b = 0; b < 3 && b < l - a; b++) {
                for (int c = 0; c < 3 && c < l - a - b; c++) {
                    StringBuilder sb = new StringBuilder(number);
                    if (Integer.parseInt(sb.substring(0, a + 1 )) < 256
                            && Integer.parseInt(sb.substring(a + 1, a + b + 2)) < 256
                            && Integer.parseInt(sb.substring(a + b + 2, a + b + c + 3)) < 256
                            && Integer.parseInt(sb.substring(a + b + c + 3)) < 256) {
                        sb.insert(a + 1, ".");
                        sb.insert(a + b + 3, ".");
                        sb.insert(a + b + c + 5, ".");
                        ips.add(sb.toString());
                    }
                }
            }
        }
        return ips;
    }
edqdpe6u

edqdpe6u6#

此代码工作正常,请检查。

public static void main(String[] args) {
    String input = "121212111";
    for (String ipAddress : generatePossibleIpAddresses(input, 3)) {
        System.out.println(ipAddress);
    }
}

public static ArrayList<String> generatePossibleIpAddresses(String ipAddress, int dot) {
    ArrayList<String> list = new ArrayList<String>();

    if (ipAddress == null || ipAddress.length() == 0) {
        return list;
    }

    if (dot == 0) {
        int i = Integer.parseInt(ipAddress);
        if (i < 256) {
            list.add(ipAddress);
        }
        return list;
    }

    for (int i = 1; i <= 3; i++) {
        int num = Integer.parseInt(ipAddress.substring(0, i));
        if (num < 256) {
            for (String str : generatePossibleIpAddresses(ipAddress.substring(i), dot - 1)) {
                list.add(num + "." + str);
            }
        }
    }
    return list;
}
70gysomp

70gysomp7#

干净和清晰的代码工作正常。公共类IPGenerator {

private String getValidIp(List<Integer> combination, String ip) {
    int from = 0;
    int to = 0;
    String finalIp = "";
    for (int digit : combination) {
        to += digit;
        String ipPart = ip.substring(from, to);
        if (!isValidIp(ipPart)) {
            return null;
        }
        finalIp += ipPart + ".";
        from = to;
    }
    return finalIp.replaceAll(".$", "");
}

public List<List<Integer>> getOptions(String ip) {
    List<Integer> baseOption = Arrays.asList(1, 2, 3);
    List<List<Integer>> options = new ArrayList<>();
    baseOption.forEach(i -> {
        baseOption.forEach(i2 -> {
            baseOption.forEach(i3 -> {
                baseOption.forEach(i4 -> {
                    if (isRelevantOption(ip, i + i2 + i3 + i4)) {
                        options.add(Arrays.asList(i, i2, i3, i4));
                    }
                });
            });
        });
    });
    return options;
}

private boolean isRelevantOption(String ip, int sum) {
    return ip.length() == sum;
}

private boolean isValidIp(String ip) {
    return Integer.parseInt(ip) < 256;
}

public List<String> GetAllValidIpAddress(String ip) {
    if (ip.length() > 12) {
        System.out.println("IP is not valid");
    }
    List<List<Integer>> options = getOptions(ip);
    return options.stream().map(c -> getValidIp(c, ip)).filter(Objects::nonNull).collect(Collectors.toList());
}

public static void main(String args[]) {
    IPGenerator ipGenerator = new IPGenerator();
    ipGenerator.GetAllValidIpAddress("2562547").forEach(ip -> System.out.println(ip));
}

}
输入:2562547
输出:2.56.25.47 2.56.254.7 25.6.25.47 25.6.254.7 25.62.5.4725.62.54.7

相关问题