Advertisement
Xesevi

תשע שאלה 4

Jul 6th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.Map.Entry;
  3.  
  4. public class Program {
  5.     public static <T> HashMap<T, Collection<Integer>> createIndexMap(
  6.             Collection<T> c) {
  7.         HashMap<T, Collection<Integer>> m = new HashMap<T, Collection<Integer>>();
  8.  
  9.         int i = 0;
  10.         for (T x : c) {
  11.             if (m.containsKey(x)) {
  12.                 Collection<Integer> ci = m.get(x);
  13.                 ci.add(i);
  14.             } else {
  15.                 Collection<Integer> ci = new Vector<Integer>();
  16.                 ci.add(i);
  17.                 m.put(x, ci);
  18.             }
  19.             i++;
  20.         }
  21.         return m;
  22.     }
  23.  
  24.     public static void main(String[] args) {
  25.  
  26.         List<Integer> l = new LinkedList<Integer>();
  27.         l.add(2);
  28.         l.add(5);
  29.         l.add(2);
  30.         l.add(2);
  31.         l.add(8);
  32.         l.add(7);
  33.         l.add(5);
  34.         l.add(7);
  35.         HashMap<Integer, Collection<Integer>> m = createIndexMap(l);
  36.  
  37.         for (Integer x : m.keySet()) {
  38.             System.out.print(x + ":");
  39.             for (Integer y : m.get(x))
  40.                 System.out.print(y + " ");
  41.             System.out.println();
  42.  
  43.         }
  44.        
  45.        
  46.         List<Point>  ll = new LinkedList<Point>();
  47.         ll.add(new Point(2,1));
  48.         ll.add(new Point(3,1));
  49.         ll.add(new Point(2,1));
  50.         ll.add(new Point(4,1));
  51.         ll.add(new Point(3,1));
  52.         ll.add(new Point(2,1));
  53.         ll.add(new Point(2,1));
  54.         ll.add(new Point(4,1));
  55.        
  56.         HashMap<Point, Collection<Integer>> mm = createIndexMap(ll);
  57.        
  58.         for (Point x : mm.keySet()) {
  59.             System.out.print(x + ":");
  60.             for (Integer y : mm.get(x))
  61.                 System.out.print(y + " ");
  62.             System.out.println();
  63.  
  64.         }
  65.        
  66.  
  67.  
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement