简体   繁体   English

如何摆脱打印线内的重复项

[英]how to get rid of duplicates inside a printline

ive been trying to solve this for the last 5 hours and i'm exhausted ..在过去的 5 个小时里,我一直试图解决这个问题,但我已经筋疲力尽了..
i need to build a method that takes an array of numbers and determaines which right digit was shown the least times in an thr array.我需要构建一个方法,该方法采用一组数字并确定哪个正确的数字在 thr 数组中显示的次数最少。 for example if the array is [134,12634,124,5667] the number that will be shown is 7 .. i hope i'm clear enough:(例如,如果数组是 [134,12634,124,5667] 将显示的数字是 7 .. 我希望我足够清楚:(

anyways this is the code.反正这是代码。 i manged to get to the part where it show the number but it will show it as many times as the loop runs for.我设法到达它显示数字的部分,但它会在循环运行时显示它的次数。

please help请帮忙

public static boolean QuestionD(int[] arr)
    {
        int counter = 0;
        int printNum = 0;
        String[] arr2 = new String[arr.length];
        int[] arr3 = new int[arr.length];
        for (int i = 0; i < arr.length; i++)
            if (arr[i] < 0)
                return false;//if the numbers are negative return false;
        for (int j = 0; j < arr.length; j++)
        {
            printNum = arr[j] % 10;// get the right digit of the number
            {
                for (int i = 0; i < arr.length; i++)
                    if (arr[i] % 10 == printNum)// if the right digit of the first index matches the other index then counter ++;
                        counter++;// to count how many times the right digit is shown
                arr2[j] = printNum + "" + counter;// to make the number as a string and will be 2 digits , the first digit from the left
                //will be the digit that appears on the right , and the second digit will be the times that the digit appeared
                arr3[j] = Integer.parseInt(arr2[j]);//make it back to an int
                counter = 0;// setting counter back to zero to check the other numbers
            }
        }
        
        for (int i = 0; i < arr.length; i++)
        {
            for (int j = i + 1; j < arr.length; j++)
                if (arr3[i] % 10 < arr3[j] % 10)
                    System.out.print((arr3[i] / 10 % 10) + " ");// here i take the digits that were shown the less but will duplicates 
            //as many times as the for loop runs for.
        
        }
        
        return true;
    }

Well, I think your solution can be much simpler.好吧,我认为您的解决方案可以简单得多。

If I understand correctly, you want:如果我理解正确,你想要:

  • For each number, extract the rightmost digit;对于每个数字,提取最右边的数字;
  • Record the frequency of each digit;记录每个数字的频率;
  • Show the one occurring the least number of times.显示出现次数最少的那个。

Here's how you could do this.这是您如何做到这一点。 Since the number of options is fairly small – there are only 10 digits – you could simply create an array with size 10, to keep track of the number of all occurrences of each digit 1 .由于选项的数量相当少——只有 10 个数字——您可以简单地创建一个大小为 10 的数组,以跟踪每个数字1的所有出现次数。

// First, we'll define an integer array with size 10 with indexes from 0 to
// 9. We can use the indexes to store the frequencies of each of the digits
// from 0 to 9.
int[] frequencies = new int[10];

// Then we collect the frequencies of all numbers. We walk over each element
// of the array
for (int number : numbers) {
    // We use the remainder operator to get the rightmost digit. This
    // guarantees that the result of the operation never exceeds 9.
    int digit = number % 10;

    // We increment the counter for that specific integer
    frequencies[digit]++;
}

// Now we have the frequencies of all digits. Now all we have to do is walk
// over our collected frequencies, and check which one has the lowest
// frequency.

// We initialize the digit and its frequency with -1, which means in our case
// that we have not yet recorded a least frequency.
int leastQuantity = -1;
int leastNumber = -1;

// Now we must check all digits
for (int i = 0; i < 10; i++) {
    // A composite if statement, doing some magic. How it works, see below.
    if (frequencies[i] > 0 && (frequencies[i] < leastQuantity || leastNumber == -1)) {
        leastQuantity = frequencies[i];
        leastNumber = i;
    }
}

System.out.println("The rightmost digit " + leastNumber + " occurs " + leastQuantity + " times");
// Or if you want to list all numbers with the least frequency:
for (int i = 0; i < frequencies.length; i++) {
    if (frequencies[i] == leastQuantity) {
        System.out.println(leastNumber);
    }
}

That if statement :那个if语句

  • frequencies[i] > 0 — The frequency must be greater than 0. If the frequency of a number is 0, then it doesn't occur at all, that is, it was never a rightmost digit of any number within the array. frequencies[i] > 0 — 频率必须大于 0。如果一个数字的频率为 0,那么它根本不会出现,也就是说,它从来不是数组中任何数字的最右边的数字。 So we must only count frequencies greater than 0.所以我们必须只计算大于 0 的频率。

  • Either of the following must be true:以下任何一项必须为真:

    • leastNumber == -1 — Meaning we have not yet recorded a frequency, so if the frequency is greater than 0, we must record it. leastNumber == -1 — 意味着我们还没有记录频率,所以如果频率大于 0,我们必须记录它。
    • frequencies[i] < leastQuantity — If the current frequency is lower than the last one recorded, update both the number and its frequency. frequencies[i] < leastQuantity — 如果当前频率低于记录的最后一个频率,则更新数字及其频率。

There are some assumptions here:这里有一些假设:

  • numbers is not null . numbers不为null You may want to write Objects.requireNonNull(numbers) as the first statement of the method body, in order to fast-fail .您可能希望将Objects.requireNonNull(numbers)编写为方法主体的第一条语句,以便快速失败

  • numbers.length > 0 . numbers.length > 0 You may want to write你可能想写

    if (numbers.length == 0) { throw new IllegalArgumentException("Given array has no elements"); }
  • None of the numbers within numbers is negative.数字中的numbers都不是负数。 If any of the numbers is, then the code tries to write at a negative array index, causing an ArrayIndexOutOfBoundsException to be thrown.如果任何数字是,则代码尝试在负数组索引处写入,导致抛出ArrayIndexOutOfBoundsException We could allow negative numbers, but then we must make sure digit is absolute:我们可以允许负数,但我们必须确保digit是绝对的:

     int digit = Math.abs(number % 10);

1 There may be digits which never occur as the rightmost digit, leaving unused array positions. 1可能有一些数字永远不会作为最右边的数字出现,留下未使用的阵列位置。 In your specific example, that would be all digits except 4 and 7. For small values such as 10, this is entirely fine.在您的具体示例中,这将是除 4 和 7 之外的所有数字。对于诸如 10 之类的小值,这完全没问题。 However, if you were to extract the four rightmost digits and count the frequencies, then you ended up with a very large array, possibly with many unused positions.但是,如果您要提取最右边的四个数字并计算频率,那么您最终会得到一个非常大的数组,可能有许多未使用的位置。 In such cases, you may be better off using a ( Hash ) Map to map a certain number to their frequency.在这种情况下,你可能会关闭使用(更好的HashMap绘制一定数量他们的频率。 With such a map, it'll no longer contain unused values, instead, it'll contain only numbers where the frequency is greater than 0. See Rohan Kumar's answer for an example.使用这样的地图,它将不再包含未使用的值,而是仅包含频率大于 0 的数字。请参阅Rohan Kumar 的回答示例。

In case you're interested in using Map for storing frequencies instead of an array(You won't need to deal with digits with zero frequencies in this case).如果您有兴趣使用 Map 来存储频率而不是数组(在这种情况下,您不需要处理频率为零的数字)。 You might find this solution helpful.您可能会发现此解决方案很有帮助。 Here I'm just populating frequency map and then getting the entry with minimum value:在这里,我只是填充频率图,然后获取最小值的条目:

private static int getLeastFrequentDigit(int[] array) {
    Map<Integer, Integer> digitFrequencyMap = new HashMap<>();

    for (int j : array) {
        int key = j % 10;
        digitFrequencyMap.merge(key, 1, Integer::sum);
    }

    Map.Entry<Integer, Integer> minEntry = digitFrequencyMap.entrySet().stream()
            .min(Comparator.comparingInt(Map.Entry::getValue))
            .orElse(null);
    return minEntry != null ? minEntry.getKey() : -1;
}

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

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