Advertisement
popovstefan

[NP 2 kol.] Komponenti

Dec 2nd, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.54 KB | None | 0 0
  1. Компоненти (40 поени) Problem 4 (3 / 47)
  2. Да се дефинира класа Component во која се чуваат:
  3.  
  4. бојата
  5. тежината
  6. колекција од внатрешни компоненти (референци од класата Component).
  7. Во оваа класа да се дефинираат методите:
  8.  
  9. Component(String color, int weight) - конструктор со аргументи боја и тежина
  10. void addComponent(Component component) - за додавање нова компонента во внатрешната колекција (во оваа колекција компонентите секогаш се подредени според тежината во растечки редослед, ако имаат иста тежина подредени се алфабетски според бојата).
  11. Да се дефинира класа Window во која се чуваат:
  12.  
  13. име
  14. компоненти.
  15. Во оваа класа да се дефинираат следните методи:
  16.  
  17. Window(String) - конструктор
  18. void addComponent(int position, Component component) - додава нова компонента на дадена позиција (цел број). На секоја позиција може да има само една компонента, ако се обидеме да додадеме компонента на зафатена позиција треба да се фрли исклучок од класата InvalidPositionException со порака Invalid position [pos], alredy taken!. Компонентите се подредени во растечки редослед според позицијата.
  19. String toString() - враќа стринг репрезентација на објектот (дадена во пример излезот)
  20. void changeColor(int weight, String color) - ја менува бојата на сите компоненти со тежина помала од проследената
  21. void swichComponents(int pos1, int pos2) - ги заменува компонените од проследените позиции.
  22.  
  23. =============================================================================================================
  24.  
  25. import java.util.Comparator;
  26. import java.util.Scanner;
  27. import java.util.TreeMap;
  28. import java.util.TreeSet;
  29.  
  30. @SuppressWarnings("serial")
  31. class InvalidPositionException extends RuntimeException {
  32.      InvalidPositionException(String msg) {
  33.         super(msg);
  34.     }
  35.     public String getMessage() {
  36.         return super.getMessage();
  37.     }
  38. }
  39.  
  40. class Component {
  41.     String colour;
  42.     int weight;
  43.     TreeSet<Component> inner;
  44.     final Comparator<Component> innerComparator = (c1, c2) -> {
  45.         if (Integer.compare(c1.weight, c2.weight) != 0)
  46.             return Integer.compare(c1.weight, c2.weight);
  47.         else
  48.             return c1.colour.compareTo(c2.colour);
  49.     };
  50.    
  51.     void changeColours(String colour, int weight) {
  52.         if (this.weight < weight)
  53.             this.colour = colour;
  54.         for (Component comp : inner)
  55.             comp.changeColours(colour, weight);
  56.     }
  57.    
  58.     Component(String colour, int weight) {
  59.         this.colour = colour;
  60.         this.weight = weight;
  61.         this.inner = new TreeSet<>(innerComparator);
  62.     }
  63.    
  64.     void addComponent(Component component) {
  65.         inner.add(component);
  66.     }
  67.    
  68.     @Override
  69.     public String toString() {
  70.         return String.format("%d:%s", weight, colour);
  71.     }
  72. }
  73.  
  74. class Window {
  75.     final String name;
  76.     TreeMap<Integer, Component> components;
  77.     Window(String name) {
  78.         this.name = name;
  79.         this.components = new TreeMap<>();
  80.     }
  81.    
  82.     void addComponent(int position, Component component) {
  83.         if (components.containsKey(position))
  84.             throw new InvalidPositionException
  85.             ("Invalid position " + position + ", alredy taken!");
  86.         components.put(position, component);
  87.     }
  88.    
  89.     @Override
  90.     public String toString() {
  91.         StringBuilder str = new StringBuilder();
  92.         str.append("WINDOW " + name + "\n" );
  93.         for (Integer position : components.keySet()) {
  94.             str.append(position + ":");
  95.             createString(components.get(position), str, 0);
  96.         }
  97.         return str.toString();
  98.     }
  99.    
  100.     void createString(Component component, StringBuilder str, int depth) {
  101.         str.append(crticki(depth) + component.toString() + "\n");
  102.         for (Component comp : component.inner)
  103.             createString(comp, str, depth + 1);
  104.     }
  105.    
  106.     private String crticki(int depth) {
  107.         String str = "";
  108.         while (depth > 0) {
  109.             str += "---";
  110.             depth--;
  111.         }
  112.         return str;
  113.     }
  114.    
  115.     void changeColor(int weight, String colour) {
  116.         components.entrySet()
  117.         .stream()
  118.         .forEach(t -> t.getValue().changeColours(colour, weight));
  119.     }
  120.    
  121.     void swichComponents(int position1, int position2) {
  122.         Component component = components.get(position1);
  123.         components.put(position1, components.get(position2));
  124.         components.put(position2, component);
  125.     }
  126. }
  127. public class ComponentTest {
  128.     public static void main(String[] args) {
  129.         Scanner scanner = new Scanner(System.in);
  130.         String name = scanner.nextLine();
  131.         Window window = new Window(name);
  132.         Component prev = null;
  133.         while (true) {
  134.             try {
  135.                 int what = scanner.nextInt();
  136.                 scanner.nextLine();
  137.                 if (what == 0) {
  138.                     int position = scanner.nextInt();
  139.                     window.addComponent(position, prev);
  140.                 } else if (what == 1) {
  141.                     String color = scanner.nextLine();
  142.                     int weight = scanner.nextInt();
  143.                     Component component = new Component(color, weight);
  144.                     prev = component;
  145.                 } else if (what == 2) {
  146.                     String color = scanner.nextLine();
  147.                     int weight = scanner.nextInt();
  148.                     Component component = new Component(color, weight);
  149.                     prev.addComponent(component);
  150.                     prev = component;
  151.                 } else if (what == 3) {
  152.                     String color = scanner.nextLine();
  153.                     int weight = scanner.nextInt();
  154.                     Component component = new Component(color, weight);
  155.                     prev.addComponent(component);
  156.                 } else if(what == 4) {
  157.                     break;
  158.                 }
  159.                
  160.             } catch (InvalidPositionException e) {
  161.                 System.out.println(e.getMessage());
  162.             }
  163.             scanner.nextLine();        
  164.         }
  165.        
  166.         System.out.println("=== ORIGINAL WINDOW ===");
  167.         System.out.println(window);
  168.         int weight = scanner.nextInt();
  169.         scanner.nextLine();
  170.         String color = scanner.nextLine();
  171.         window.changeColor(weight, color);
  172.         System.out.println(String.format("=== CHANGED COLOR (%d, %s) ===", weight, color));
  173.         System.out.println(window);
  174.         int pos1 = scanner.nextInt();
  175.         int pos2 = scanner.nextInt();
  176.         System.out.println(String.format("=== SWITCHED COMPONENTS %d <-> %d ===", pos1, pos2));
  177.         window.swichComponents(pos1, pos2);
  178.         System.out.println(window);
  179.     }
  180. }
  181. ===============================================================================================================
  182. Sample input
  183. FIREFOX
  184. 1
  185. RED
  186. 30
  187. 3
  188. MAGENTA
  189. 90
  190. 0
  191. 1
  192. 2
  193. GREEN
  194. 40
  195. 3
  196. RED
  197. 50
  198. 2
  199. BLUE
  200. 50
  201. 2
  202. CYAN
  203. 60
  204. 1
  205. YELLOW
  206. 80
  207. 3
  208. WHITE
  209. 35
  210. 0
  211. 2
  212. 4
  213. 60
  214. BLACK
  215. 1 2
  216. ===============================================================================================================
  217. Sample output
  218. === ORIGINAL WINDOW ===
  219. WINDOW FIREFOX
  220. 1:30:RED
  221. ---40:GREEN
  222. ------50:BLUE
  223. ---------60:CYAN
  224. ------50:RED
  225. ---90:MAGENTA
  226. 2:80:YELLOW
  227. ---35:WHITE
  228.  
  229. === CHANGED COLOR (60, BLACK) ===
  230. WINDOW FIREFOX
  231. 1:30:BLACK
  232. ---40:BLACK
  233. ------50:BLACK
  234. ---------60:CYAN
  235. ------50:BLACK
  236. ---90:MAGENTA
  237. 2:80:YELLOW
  238. ---35:BLACK
  239.  
  240. === SWITCHED COMPONENTS 1 <-> 2 ===
  241. WINDOW FIREFOX
  242. 1:80:YELLOW
  243. ---35:BLACK
  244. 2:30:BLACK
  245. ---40:BLACK
  246. ------50:BLACK
  247. ---------60:CYAN
  248. ------50:BLACK
  249. ---90:MAGENTA
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement