最少重复/项目在阵列中出现一次

时间:2018-10-29 21:39:21

标签: java arrays

我正在尝试打印唯一的项目,重复次数最多的项目和重复次数最少的项目,即一次出现一次。在最少重复的部分中,由于标志设置为1而不是预期的0,因此我没有得到任何输出。

样本输入:

10
watch
laptop
iphone
watch
car
headset
laptop
watch
shoe
mobile

样本输出:

The unique items are
watch
laptop
iphone
car
headset
shoe
mobile
The maximum purchased item(s) are
watch
The minimum purchased item(s) are
iphone
car
headset
shoe
mobile 
import java.util.Arrays;
import java.text.ParseException;
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;

public class ItemDetails {
    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        int flag=0, flag1=0, count = 0, count1 = 0, count2 = 0;
        String maxname = null;
        int k;
//      String[] max = new String[k];
        Integer x = sn.nextInt();

        sn.nextLine(); 
        String[] names=new String[x];
        for (int i = 0; i<x; i++)
        {
            names[i] = sn.nextLine();
        }
        System.out.println("The unique items are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                        if (names[i].equals(names[j]))
                        { 
                    // got the unique element 
                            flag = 0;
                            break;
                        }
                        else 
                        {
                            flag = 1;
//                          break;
                        }
//                  break;
                }
                if (flag==1)
                {
                    ++count;
                    System.out.println(names[i]);

                }
            }
            System.out.println(count);  
        }
        System.out.println("The maximum purchased item(s) are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                    if (names[i].equals(names[j]))
                    {
                        count1++;
                        maxname = names[i];
                    }
                    else
                    {
                        count1 = 0;
                    }
                }

            }
            System.out.println(maxname);    
        }

        System.out.println("The minimum purchased item(s) are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                    if (names[i].equals(names[j]))
                    {
                        flag1 = 1;
                        break;
                    }
                }

                if (flag1==0)
                {
                    count2++;
                    System.out.println(names[i]);
                }
            }
            //System.out.println(maxname);  
        }
    }
}

3 个答案:

答案 0 :(得分:0)

@艾伦 使用Java流可能会更简单,例如:

    List<String> items = new ArrayList<String>();
    // Fill List items with your data

    Map<String, Long> processed =items.stream()
            .collect(Collectors.groupingBy(
                            Function.identity(), Collectors.counting())                        
    );

    System.out.println ("Distinct items");
    processed.keySet().stream().forEach(item -> System.out.println(item));

    Long minCount = Collections.min(processed.values());
    Long maxCount = Collections.max(processed.values());

    System.out.println ("Least repeated items");
    processed.entrySet().stream().filter(entry -> entry.getValue().equals(minCount)).forEach(item -> System.out.println(item));        

    System.out.println ("Most repeated items");
    processed.entrySet().stream().filter(entry -> entry.getValue().equals(maxCount)).forEach(item -> System.out.println(item));

答案 1 :(得分:0)

检索唯一项:

public static Set<String> getUniqueItems(Collection<String> items) {
    return new HashSet<>(items);
}

使用给定的Function(使用Streams)检索购买的商品:

private static Set<String> getPurchasedItems(Collection<String> items, Function<Collection<Long>, Long> function) {
    Map<String, Long> map = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    final long count = function.apply(map.values());

    return map.entrySet().stream()
              .filter(entry -> entry.getValue() == count)
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

使用给定的Function(使用POJO)检索购买的商品:

private static Set<String> getPurchasedItems(Collection<String> items, Function<Collection<Long>, Long> function) {
    Map<String, Long> map = new HashMap<>();

    for (String item : items)
        map.compute(item, (key, count) -> Optional.ofNullable(count).orElse(0L) + 1);

    final long count = function.apply(map.values());

    Set<String> res = new HashSet<>();

    for (Map.Entry<String, Long> entry : map.entrySet())
        if (entry.getValue() == count)
            res.add(entry.getKey());

    return res;
}

获取最大购买商品:

public static Set<String> getMaximumPurchasedItems(Collection<String> items) {
    return getPurchasedItems(items, Collections::max);
}

检索最低购买商品:

public static Set<String> getMinimumPurchasedItems(Collection<String> items) {
    return getPurchasedItems(items, Collections::min);
}

答案 2 :(得分:-1)

在最小的代码位置,将flag1=0;设置在第二个循环之前,还应该对数组进行排序以能够应用此算法。除了这两个之外,您还需要先与进行比较,以确保算法能够正常工作

    System.out.println("The minimum purchased item(s) are");
    {
        Arrays.sort(names);
        for (int i = 0; i < x-1; i++) {
            flag1 = 0;
            for (int j = i + 1; j < x; j++) {
                if (names[i].equals(names[j]) || (i>1 && names[i].equals(names[i-1])) ) {
                    flag1 = 1;
                    break;
                }
            }

            if (flag1 == 0) {
                count2++;
                System.out.println(names[i]);
            }
        }
    }