查找数字的最大重复次数

时间:2015-03-09 13:05:22

标签: java

我正在做大学课程练习,我似乎无法做其中一个。 我们要求输入一个数字,如1975333,该程序应返回"数字3出现3次"。它基本上应该告诉你数字的模式。

这就是我所拥有的,但无论我尝试什么,我似乎无法使其发挥作用:

import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Math.*;

public class Oblig5 {

    public static void main(String[] args) {

        int tall = input_tall();
        int siffervekt = 0;
        int t_siffervekt = 0;

        int lengde = (int) (Math.log10(tall) + 1);

        for (int siffer = 0; siffer == lengde; siffer++) {
            System.out.println("Siffer = " + siffer);
                for (int x = 0; x < lengde; x++) {
                    int asiffer = (tall % 10);
                    System.out.println("Asiffer = " + asiffer);
                    if (asiffer == siffer) {
                        siffervekt++;
                        out.println(siffervekt);
                    }
                    tall = tall / 10; 
                }
            t_siffervekt = max(siffervekt, t_siffervekt);   
        }
    }

    private static int input_tall() {
        return Integer.parseInt(showInputDialog(null, "Skriv inn ønsket tall"));
    }

}

8 个答案:

答案 0 :(得分:0)

通过计算每个特定数字,我觉得将数字保持为String(删除Integer.parseInt())然后计算char中的每个HashMap会更容易价值和数量。例如:

public int[] getMostCommon(String numbers){ //Returning int[] for [0] = digit and [1] = frequency
    HashMap<Character, Integer> digits = new HashMap<Character, Integer>();
    for (char myChar : numbers.toCharArray()){
        int count = digits.getOrDefault(myChar, 0);
        digits.put(myChar, count+1); //getOrDefault is Java 8+ only, see below if running earlier versions
    }
    int[] returnValue = new int[] {0, 0};
    for (int i = 0; i <= 9; i++){ //Loop through each digit to see which is most frequent
        if (digits.get((char) i+48) > returnValue[1]){ //+48 for ASCII conversion to char, see http://www.asciitable.com/
            returnValue[0] = i;
            returnValue[1] = digits.get((char) i+48);
        }
    }
    return returnValue;
}

如果您没有运行Java 8,则需要使用以下代码代替getOrDefault:

int count = 0;
if (digits.containsKey(myChar)){
    count = digits.get(myChar);
}

答案 1 :(得分:0)

一个可能的直接解决方案片段,用于查找计数最高的数字 这段代码不应该为所有边缘情况提供解决方案。而是展示找到解决方案的可行方法。

// the input number
int input = 1975333;

// check the last digit and increment the count for this digit
int[] digits = new int[10];
while (input > 0) {
    digits[input % 10]++;
    input /= 10;
}

// find the digit with the highest count
int maxCount = 0;
int maxIdx = 0;
for (int i = 0; i < digits.length; i++) {
    if (digits[i] > maxCount) {
        maxCount = digits[i];
        maxIdx = i;
    }
}
System.out.printf("max digit: %d  count: %d%n", maxIdx, maxCount);

答案 2 :(得分:0)

只需保持每个数字的总计,然后寻找最好的数字。使用val本身来控制循环,以避免误分析所分析值的长度。

    public Mode(long val) {
        long[] count = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        while(val > 0) {
            int digit = (int)(val % 10L);
            count[digit] ++;
            val /= 10;
        }
        int mode = 0;
        long maxVal = 0;
        for(int i = 0; i < 10; i++) {
            if(count[i] > mode) {
                mode = i;
                maxVal = count[i];
            }
        }
        System.out.println("Number " + mode + " appears " + maxVal + " times");
    }

答案 3 :(得分:0)

您可以使用新的Array[10]来保存每个数字[0-9]的频率,然后返回此数组的最大值:

public int mostFrequentVlaue(int number){
   String num=number.toString();
    int[] freqArray=new int[10];
   // initialize the frequency array with zeros
   for(int k=0;k<9;k++){
        freqArray[k]=0;
   }

   //loop throught our number string and count frequency of each digit
   for(int i=0;i<num.length();i++){
     switch (num.charAt(i)) {
        case '0':  freqArray[0]++;
                 break;
        case '1':  freqArray[1]++;
                 break;
        case '2': freqArray[2]++;
                 break;
        case '3':  freqArray[3]++;
                 break;
        case '4':  freqArray[4]++;
                 break;
        case '5':  freqArray[5]++;
                 break;
        case '6':  freqArray[6]++;
                 break;
        case '7':  freqArray[7]++;
                 break;
        case '8':  freqArray[8]++;
                 break;
        case '9':  freqArray[9]++;
                 break;
    }
  }
  int max=freqArray[0];
  int freq=0;
  for(int j=1;j<9;j++){
        if (freqArray[j] > max) {
            max = freqArray[j];
            freq=j;
        }
   }
  return freq;
}

这就是你所需要的一切。

答案 4 :(得分:0)

public static void getMode(int number){
    int[] countArray = new int[10];
    while(number > 0){
        //We take a single number from the number using modulo
        int n = number%10;
        countArray[n]++;
        //We remove the number we already used.
        number= number/10;
    }
    //Count cannot possibly be less than -1
    int max = -1;
    for(int i = 0; i< 10; i++){
        //Checking which number occurs the most and updates max
        if(countArray[i] > max)
            max = countArray[i];
    }
    System.out.println("Number " + getNumber(countArray, max) + " appears " + max + " times");
}

//Helping method I made in order to get which number was found the most
public static int getNumber(int [] array, int max){
    //Simply the array element which contained max is the element
    //that occured the most.
    for(int i = 0; i < array.length; i++){
        if(array[i] == max)
            return i;
    }
    return -1;
}

计算数字时,0-9的数组有很大帮助,因为它涵盖了所有可能数字的范围。那么,让我引导您完成我的代码。用户输入一个数字,假设它是123455.

你输入while循环,那个数字确实大于0.使用数字上的%给你5.countArray [5] ++表示位置5的countArray增加1.之后,数字应除以10为了摆脱你已经使用过的数字,它会被更新。

现在你的countArray看起来像{0,0,0,0,0,1,0,0,0,0}。 您的号码现在是12345,仍然大于0,您重新进入循环。 再次使用%会给你5.countArray [5]现在再次增加1。

您的countArray看起来像{0,0,0,0,0,2,0,0,0,0}。 您的号码现在是1234,仍然大于0,您重新进入循环。使用%会给你4.countArray [4]递增。您的countArray看起来像{0,0,0,0,1,2,0,0,0,0}。依此类推,直到没有剩余的数字可以计算,在这种情况下,数组看起来像{0,1,1,1,1,2,0,0,0,0}。

下一个for循环是关于找到找到的最大数量。它很简单,在数组上循环,如果找到大于max的数字,则max变为该数字。在这种情况下,max最终将变为2。

虽然我们已经找到了计算次数最多的次数,但我们仍然不知道这个数字是多少,即在我的例子中,我们知道计算次数最多的是2次,但我们仍然不知道它是因此,我创建的辅助方法发现哪个数字计数最多。它循环遍历数组,如果某个位置的数组包含最大计数数,则必须是数字。

答案 5 :(得分:0)

我尝试使用map来实现正确的输出。   希望这可以帮助你.. :)

package digit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

public class RecurringDigit {


public static void main(String args[]) throws IOException {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        char[] chars = str.toCharArray();
        //Created map for each digit
        final ConcurrentMap<Character, AtomicInteger> map = new  ConcurrentHashMap<>();
        for (char c : chars) {
            final char key = c;
            map.putIfAbsent(key, new AtomicInteger(0));
            map.get(key).incrementAndGet();
        }
        //To find max count of that digit
        Map.Entry<Character, AtomicInteger> maxEntry = null;

        for (Map.Entry<Character, AtomicInteger> entry : map.entrySet()) {

            if (maxEntry == null || entry.getValue().intValue() > maxEntry.getValue().intValue()) {
                maxEntry = entry;
            }
        }
        System.out.println("Number "+ maxEntry.getKey() + " appears " + maxEntry.getValue() +" times");
    } catch (Exception e) {
        e.printStackTrace();
    }

   }
 }

答案 6 :(得分:0)

Try this:

public class RecurringDigit {
    public static void main(String args []) {
        //--------Change input--------\\
        int input = 1975333;
        //----------------------------\\

        int[] digits = toDigitArray(input);
        int[] counts = new int[10];

        int mode = 1;
        int modeAmount = 1;
        boolean isMode = false;

        for(int i = 0; i < digits.length; i++) {
            int digit = digits[i];
            counts[digit]++;

            if(modeAmount < counts[digit]) {
                modeAmount = counts[digit];
                mode = digits[i];
                isMode = true;
            }
        }

        if(isMode) {
            System.out.println("Number " + mode + " appears " + counts[mode] + " times.");
        } else {
            System.out.println("All numbers appear an equal amount of times.");
        }
    }

    public static int[] toDigitArray(int number) {
        String temp = Integer.toString(number);
        int[] output = new int[temp.length()];
        for (int i = 0; i < temp.length(); i++)
        {
            output[i] = temp.charAt(i) - '0';
        }

        return output;
    }
}

The code first turns the int into an int array called digits which contains all of the digits, each in a different index. Then an int array called counts is created to hold the amount of times a number occurs, each index representing a different number (example: counts[5] equals the amount of times 5 occurs). Then a for loop is used to update the counts array and update the mode if the current occurrence amount is the largest. The for loop also sets the isMode boolean to true the first time the mode is updated. Finally the mode (from the mode variable) and the amount of times that the mode occurs (from counts[mode]) are printed. Also, if the boolean isMode is true, a message is printed saying that there is no mode. I hope code this helped you a little bit.

答案 7 :(得分:-1)

for (int siffer=0; siffer==lengde; siffer++)

更改为:

for (int siffer=0; siffer < lengde; siffer++)

因为siffer在开始时为0而lengde为7,所以你的for循环永远不会执行...