【问题标题】:Making numbers and then find duplicate numbers in the String + Counting valid Strings制作数字,然后在字符串中找到重复的数字 + 计算有效字符串
【发布时间】:2015-09-10 15:25:32
【问题描述】:

所以我正在制作一个用 10000 到 55555 的数字填充字符串的方法。这些数字在 6 位数字系统中。这意味着当我们有 10005 时,下一个数字是 10010,并且 11555 -> 12000。 在我填满字符串之后,我将遍历字符串并计算字符串中只有 2 个或更少相等数字的每个数字(或计算每个数字,并从计数中删除那些具有 3 个或更多相等数字的数字)。

我做了一个 for 循环,用所有数字填充字符串,但我不知道如何找到 3 og 更多相等数字的数字。 我猜我需要另一个带有 If 语句的 for 循环,但我只是想不通。试图同时使用 char 和 int 进行循环,但我显然做错了。

这是我目前所拥有的:

public class TestProgram {
public static void main(String... args)
{
    System.out.println(membersnumbers());
}

public static int membersnumbers()
{
    int count = 0;
    for (int i = 1296; i < 7776; i++) //fills the String with numbers from 1000 to 5555
    {                                  //without numbers over 6
        String number = Integer.toString(i,6); //making the String and fills it with numbers  

        for (<run through all the numbers>)
        {
            if (<number has less than 3 equal digits )
            {
                count++;
            }
        }
    }  
    return count;
}
}

有什么想法吗?

【问题讨论】:

    标签: java string if-statement for-loop count


    【解决方案1】:

    您将需要两个额外的 for 循环,一个用于迭代字符串中的字符,另一个用于计算相等的字符。

    for(int i = 0; i < string.length(); i++){
       char curChar = string.charAt(i);
       int charCount = 0;
       for(int j = 0; j < string.length(); j++){
          if(j != i && curChar == string.charAt(j)) charCount++;
        }
       if(count >= 3) count++;
       charCount = 0;
    }
    

    【讨论】:

      【解决方案2】:

      使用以下方法获取字符串中相同字母的最大数量 -

      public static int getMaxCount(String s) {
              Map<Character, Integer> map = new HashMap<Character, Integer>();
              for(int i = 0; i < s.length(); i++) {
                  char c = s.charAt(i);
                  Integer val = map.get(new Character(c));
                  if(val != null){
                      map.put(c, new Integer(val + 1));
                  } else {
                      map.put(c,1);
                  }
              }
      
              List<Integer> countList = new ArrayList<Integer>(map.values());
              Collections.sort(countList);
              Collections.reverse(countList);
              return countList.get(0);
          }
      

      在将数字作为字符串迭代的循环中调用此方法,并检查此方法是否返回大于等于 3 进行过滤。

      【讨论】:

        【解决方案3】:

        如果你能向我们展示你迄今为止所做的尝试,那就太好了。这是我使用流的稍微疯狂的实现(ab)。

        import java.util.stream.IntStream;
        import static java.util.function.Function.identity;
        import static java.util.stream.Collectors.groupingBy;
        
        public static long membersnumbers() {
            return IntStream.range(1296, 7776)
                    .mapToObj(integer -> Integer.toString(integer, 6))
                    .filter(string -> string.chars()
                            .mapToObj(String::valueOf)
                            .collect(groupingBy(identity()))
                            .values()
                            .stream()
                            .anyMatch(list -> list.size() > 1))
                    .count();
        }
        

        尝试将部分代码提取为有意义的方法,将问题拆分为更小的问题,例如:

        public static int membersnumbers() {
            int count = 0;
            for (int i = 1296; i < 7776; i++) {
                if (hasAtLeastTwoSameCharacters(Integer.toString(i, 6))) {
                    count++;
                }
            }
            return count;
        }
        

        此时您不必担心hasAtLeastTwoSameCharacters 的工作原理。只需定义您需要的下一个较小的步骤。

        private static boolean hasAtLeastTwoSameCharacters(String string) {
            for (char c : string.toCharArray()) {
                if (countCharactersInString(c, string) > 1) {
                    return true;
                }
            }
            return false;
        }
        

        再说一次,不用担心countCharactersInString,只需将问题替换为较小的问题,直到“问题”小到可以通过单一方法轻松解决。

        private static int countCharactersInString(char characterToCount, String string) {
            int count = 0;
            for (char c : string.toCharArray()) {
                if (c == characterToCount) {
                    count++;
                }
            }
            return count;
        }
        

        PS 将左括号 { 留在行尾 - 它大大降低了在行尾添加分号的风险。可能需要很长时间才能弄清楚为什么下面代码中的条件不起作用:

        if (1 == 2);
        {
            System.out.println("should be never printed but always is");
        }
        

        【讨论】:

          【解决方案4】:

          试试这个功能:

          public static int findDuplicateDitigs(String str){
          
              int occurrence = 0;
              Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
              char[] chrs = str.toCharArray();
              for(Character ch:chrs){
                  if(dupMap.containsKey(ch)){
                      dupMap.put(ch, dupMap.get(ch)+1);
                  } else {
                      dupMap.put(ch, 1);
                  }
              }
              Set<Character> keys = dupMap.keySet();
              for(Character ch:keys){
                  if(dupMap.get(ch) > 1){
                      occurrence = dupMap.get(ch);
                  }
              }
              return occurrence;
          }
          

          主要:

          List<String> listNumber = new ArrayList<String>();
          int count = 0;
              for (int i = 1296; i < 7776; i++) //fills the String with numbers from 1000 to 5555
              {                                  //without numbers over 6
                  String number = Integer.toString(i,6); //making the String and fills it with numbers  
                  listNumber.add(number);
              }  
              List<String> newListNumber = new ArrayList<String>();
              for(String s : listNumber)
              {
                  int counter = 0;
                  counter = findDuplicateDitigs(s);
                  if(counter == 0)
                  {
                      newListNumber.add(s);
                  }
              }
              for(String s : newListNumber)
              {
                  System.out.println(s);
              }
          

          这是输出的一部分:

          32540

          32541

          34012

          34015

          34021

          34025

          34051

          34052

          34152

          【讨论】:

            【解决方案5】:

            首先,您的循环嵌套错误 - 您正在遍历循环体中创建每个数字的所有数字。

            你应该这样做:

            for (int i = 1296; i < 7776; i++) { //fills the String with numbers from 1000 to 5555
                                                //without numbers over 6
                String number = Integer.toString(i,6); //making the String and fills it with numbers  
                <store number in some array/collection>
            }
            
            for (<run through all the numbers>) {
                if (<number has less than 3 equal digits>) {
                    count++;
                }
            }
            

            或者只是这个,因为您不需要存储数字:

            for (int i = 1296; i < 7776; i++) { //fills the String with numbers from 1000 to 5555
                                                //without numbers over 6
                String number = Integer.toString(i,6); //making the String and fills it with numbers  
            
                if (<number has less than 3 equal digits>) {
                    count++;
                }
            }
            

            关于测试数字的方法,你可以这样做:

            boolean hasLessThan3EqualDigits(String number) {
            
                int[] digitCount = new int[6]; // counters for digits 0 1 2 3 4 5
            
                for (<run through the characters (digits) in the string 'number'>) {
                    <increase the corresponding digitCount element>
                }
            
                int maxEqualDigits = <find maximum value in digitCount>
            
                return maxEqualDigits < 3;
            }
            

            【讨论】:

              猜你喜欢
              • 2014-05-06
              • 2017-09-03
              • 2011-03-02
              • 2017-07-09
              • 2016-05-20
              • 1970-01-01
              • 2014-04-07
              • 2017-01-14
              相关资源
              最近更新 更多