fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.Collectors;
  7. import java.util.Map;
  8. import java.util.LinkedHashMap;
  9. import java.util.HashMap;
  10.  
  11. /* Name of the class has to be "Main" only if the class is public. */
  12. class Ideone
  13. {
  14. static Map<String, Integer> myMap = new HashMap<>();
  15.  
  16. static void combinationUtil(int arr[], int data[], int start,
  17. int end, int index, int r) {
  18. int sum = 0;
  19. StringBuilder sb = new StringBuilder();
  20. if (index == r) {
  21. for (int j = 0; j < r; j++) {
  22.  
  23. sb.append(data[j]).append(",");
  24. sum += data[j];
  25.  
  26. System.out.print(data[j] + " ");
  27. }
  28. myMap.put(sb.toString(), sum);
  29. sum = 0;
  30. sb = new StringBuilder();
  31. System.out.println("");
  32. return;
  33. }
  34. for (int i = start; i <= end && end - i + 1 >= r - index; i++) {
  35. data[index] = arr[i];
  36. combinationUtil(arr, data, i + 1, end, index + 1, r);
  37. }
  38. }
  39.  
  40. static void printCombination(int arr[], int n, int r) {
  41. int data[] = new int[r];
  42. combinationUtil(arr, data, 0, n - 1, 0, r);
  43. }
  44.  
  45. public static void main(String[] args) {
  46. int arr[] = {1,2,3,4,5,6,7,8};
  47. int r = 3;
  48. int n = arr.length;
  49. printCombination(arr, n, r);
  50. myMap = sortByValue(myMap);
  51. System.out.println(searchClosest(myMap, 14));
  52. }
  53.  
  54. public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
  55. return map.entrySet()
  56. .stream()
  57. .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
  58. .collect(Collectors.toMap(
  59. Map.Entry::getKey,
  60. Map.Entry::getValue,
  61. (e1, e2) -> e1,
  62. LinkedHashMap::new
  63. ));
  64. }
  65.  
  66. public static String searchClosest(Map<String, Integer> map, int value) {
  67. double minDistance = Double.MAX_VALUE;
  68. String bestString = null;
  69.  
  70. for (Map.Entry<String, Integer> entry : map.entrySet()) {
  71. double distance = Math.abs(entry.getValue() - value);
  72. if (distance < minDistance) {
  73. minDistance = distance;
  74. bestString = entry.getKey();
  75. }
  76. }
  77. return bestString;
  78. }
  79. }
Success #stdin #stdout 0.2s 34088KB
stdin
Standard input is empty
stdout
1 2 3 
1 2 4 
1 2 5 
1 2 6 
1 2 7 
1 2 8 
1 3 4 
1 3 5 
1 3 6 
1 3 7 
1 3 8 
1 4 5 
1 4 6 
1 4 7 
1 4 8 
1 5 6 
1 5 7 
1 5 8 
1 6 7 
1 6 8 
1 7 8 
2 3 4 
2 3 5 
2 3 6 
2 3 7 
2 3 8 
2 4 5 
2 4 6 
2 4 7 
2 4 8 
2 5 6 
2 5 7 
2 5 8 
2 6 7 
2 6 8 
2 7 8 
3 4 5 
3 4 6 
3 4 7 
3 4 8 
3 5 6 
3 5 7 
3 5 8 
3 6 7 
3 6 8 
3 7 8 
4 5 6 
4 5 7 
4 5 8 
4 6 7 
4 6 8 
4 7 8 
5 6 7 
5 6 8 
5 7 8 
6 7 8 
1,6,7,