Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package javaapplication28;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Map;
- import java.util.Random;
- import java.util.TreeMap;
- public class JavaApplication28 {
- public static void main(String[] args) {
- int[] tab1 = new int[100];
- int[] tab2 = new int[100];
- Map<Integer, Integer> licznosc;
- wypelnijTab(tab1);
- wypelnijTab(tab2);
- licznosc = licznosc(tab1, tab2);
- zapiszLicznosc(licznosc);
- }
- static Map licznosc(int[] tab1, int[] tab2) {
- Map<Integer, Integer> licznosc = new TreeMap<>();
- for (int liczba : tab1) {
- if (jestPierwsza(liczba)) {
- if (licznosc.containsKey(liczba)) {
- int ilosc = licznosc.get(liczba);
- ilosc++;
- licznosc.put(liczba, ilosc);
- } else {
- licznosc.put(liczba, 1);
- }
- }
- }
- for (int liczba : tab2) {
- if (jestPierwsza(liczba)) {
- if (licznosc.containsKey(liczba)) {
- int ilosc = licznosc.get(liczba);
- ilosc++;
- licznosc.put(liczba, ilosc);
- } else {
- licznosc.put(liczba, 1);
- }
- }
- }
- return licznosc;
- }
- static <K, V> void zapiszLicznosc(Map<K, V> licznosc) {
- File plik = new File("licznosc.txt");
- BufferedWriter br = null;
- try {
- br = new BufferedWriter(new FileWriter(plik));
- for (Map.Entry<K, V> wiersz : licznosc.entrySet()) {
- br.write(wiersz.getKey() + ":" + wiersz.getValue());
- br.newLine();
- }
- } catch (IOException ex) {
- }
- if (br != null) {
- try {
- br.close();
- } catch (IOException ex) {
- }
- }
- }
- static void wypelnijTab(int[] tab) {
- Random rng = new Random();
- for (int i = 0; i < tab.length; i++) {
- tab[i] = rng.nextInt(20) + 1;
- }
- }
- static boolean jestPierwsza(int n) {
- if (n == 1) {
- return false;
- }
- for (int i = 2; i < n; i++) {
- if (n % i == 0) {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement