Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Seminar06 #4

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions Seminar05/Seminar05task01.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//Реализуйте структуру телефонной книги с помощью HashMap, учитывая, что 1 человек может иметь несколько телефонов.
package Seminar05;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class Seminar05task01 {
public static void main(String[] args) {
ArrayList<HashMap<String, ArrayList<String>>> phoneBook = new ArrayList<>();
String[] fieldsArray = {"ID", "First Name", "Last Name", "Address", "Phone"};
Scanner input = new Scanner(System.in);
boolean flag = true;
System.out.println("Добро пожаловать в телефонный справочник!");
while (flag) {
int menuChoice = choiceMenu(input);
switch (menuChoice) {
case 1 -> printPhoneBook(phoneBook, fieldsArray);
case 2 -> fillMap(input, phoneBook, fieldsArray);
case 3 -> deleteEntry(input, phoneBook);
case 0 -> flag = false;
}
}

}

private static void fillMap(Scanner scan, ArrayList<HashMap<String, ArrayList<String>>> book, String[] fields) {
HashMap<String, ArrayList<String>> userInput = new HashMap<>();

ArrayList<String> bookSize = new ArrayList<>();
bookSize.add(String.valueOf(book.size()));
userInput.put("ID", bookSize);

ArrayList<String> phones = new ArrayList<>();
String tmp = "";
for (String field : fields) {
if (!field.equals("ID") && !field.equals("Phone")) {
System.out.printf("Введите значение поля %s: ", field);
ArrayList<String> value = new ArrayList<>();
tmp = scan.nextLine();
value.add(tmp);
userInput.put(field, value);
}
while (field.equals("Phone")) {
System.out.printf("Введите значение поля %s: ", field);
tmp = scan.nextLine();
phones.add(tmp);
System.out.print("Добавить ещё один номер телефона? Д/Н?: ");
String choice = scan.nextLine().toUpperCase();
if (choice.equals("Н") || choice.equals("N")) {
userInput.put(field, phones);
break;
}
}
}
book.add(userInput);
}

private static void printPhoneBook(ArrayList<HashMap<String, ArrayList<String>>> book, String[] fields) {
if (book.size() == 0) {
System.out.println("Записей не обнаружено.");
}
for (HashMap<String, ArrayList<String>> map : book) {
for (String field : fields) {
if (!field.equals("Phone")) {
System.out.printf("%s = %s\n", field, map.get(field).get(0));
} else {
for (int i = 0; i < map.get(field).size(); i++) {
System.out.printf("%s%d = %s\n", field, i + 1, map.get(field).get(i));
}
}
}
System.out.println("===================");
}
System.out.println();
}

private static int choiceMenu(Scanner scan) {
System.out.println();
System.out.print("""
Выберете пункт меню:
1 - Отобразить справочник
2 - Добавить запись в справочник
3 - Удалить запись из справочника
0 - Выход
:""");
int choice = scan.nextInt();
scan.nextLine();
System.out.println();
return choice;
}

private static void deleteEntry(Scanner inp, ArrayList<HashMap<String, ArrayList<String>>> book) {
System.out.print("Введите ID записи для удаления: ");
int deletion = inp.nextInt();
inp.nextLine();
book.remove(deletion);
System.out.println();
}
}
83 changes: 83 additions & 0 deletions Seminar05/Seminar05task02.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//Пусть дан список сотрудников:
// Иван Иванов
// Светлана Петрова
// Кристина Белова
// Анна Мусина
// Анна Крутова
// Иван Юрин
// Петр Лыков
// Павел Чернов
// Петр Чернышов
// Мария Федорова
// Марина Светлова
// Мария Савина
// Мария Рыкова
// Марина Лугова
// Анна Владимирова
// Иван Мечников
// Петр Петин
// Иван Ежов
// Написать программу, которая найдет и выведет повторяющиеся имена с количеством повторений.
// Отсортировать по убыванию популярности.
package Seminar05;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Seminar05task02 {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> db = new ArrayList<>();
HashMap<String, Integer> dbData = new HashMap<>();
getFromFile(dbData, db);
System.out.println("Исходный список: ");
System.out.println(db);
System.out.println("\nКоличество повторяющихся имён в файле: ");
printDuplicates(dbData);
LinkedHashMap<String, Integer> sortedData = new LinkedHashMap<>();
sortedDB(dbData, sortedData);
System.out.println("\nОтсортированное количество повторяющихся имён в файле: ");
printDuplicates(sortedData);
}

private static void getFromFile(HashMap<String, Integer> data, ArrayList<String> original) throws FileNotFoundException {
File reader = new File("Seminar05/list.txt");
Scanner scanner = new Scanner(reader);
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
String[] temp = input.split(" ");
original.add(input);
if (data.containsKey(temp[0])) {
data.put(temp[0], data.get(temp[0]) + 1);
} else {
data.put(temp[0], 1);
}
}
}

private static void printDuplicates(HashMap<String, Integer> data) {
Set<Map.Entry<String, Integer>> entries = data.entrySet();

for (Map.Entry<String, Integer> entry : entries) {
System.out.printf("%10s %s %d\n", entry.getKey(), ":", entry.getValue());
}
}

private static void sortedDB(HashMap<String, Integer> data, LinkedHashMap<String, Integer> sorted) {
String maxKey = "";
int maxValue = 0;
while (data.size() > 0) {
Set<Map.Entry<String, Integer>> entries = data.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
if (entry.getValue() > maxValue) {
maxValue = entry.getValue();
maxKey = entry.getKey();
}
}
sorted.put(maxKey, maxValue);
data.remove(maxKey);
maxKey = "";
maxValue = 0;
}
}
}
61 changes: 61 additions & 0 deletions Seminar05/Seminar05task03.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//Реализовать алгоритм пирамидальной сортировки (HeapSort). (Можно использовать массивы)
package Seminar05;

import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class Seminar05task03 {
public static void main(String[] args) {
ThreadLocalRandom randint = ThreadLocalRandom.current();
Scanner scanner = new Scanner(System.in);
System.out.print("Введите размер массива: ");
int arraySize = scanner.nextInt();
int[] arr = new int[arraySize];
System.out.println("Сгенерированный массив:");
createArray(arr, randint, arraySize);
System.out.println(Arrays.toString(arr));
heapSort(arr);
System.out.println("\nОтсортированный массив: ");
System.out.println(Arrays.toString(arr));
}

private static void createArray(int[] array, ThreadLocalRandom rand, int size) {
for (int i = 0; i < size; i++) {
array[i] = rand.nextInt(0, 1000);
}
}

private static void heapSort(int[] array) {
int arraySize = array.length - 1;
for (int i = 0; i < arraySize; i++) {
if (2 * i + 2 < arraySize) {
if (array[i] > array[2 * i + 1] && i % 2 == 0) {
int temp = array[i];
array[i] = array[2 * i + 1];
array[2 * i + 1] = temp;
} else if (array[i] > array[2 * i + 2] && i % 2 != 0) {
int temp = array[i];
array[i] = array[2 * i + 2];
array[2 * i + 2] = temp;
}
}
}
int max;
int maxi = 0;
for (int i = arraySize; i > 0; i--) {
max = array[i];
for (int j = 0; j < i; j++) {
if (array[j] > max) {
max = array[j];
maxi = j;
}
}
if (max > array[i]) {
int temp = array[i];
array[i] = array[maxi];
array[maxi] = temp;
}
}
}
}
101 changes: 101 additions & 0 deletions Seminar05/Seminar05task04.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//На шахматной доске расставить 8 ферзей так, чтобы они не били друг друга.
package Seminar05;

import java.util.ArrayList;

public class Seminar05task04 {
public static void main(String[] args) {
String[][] chessBoard = new String[9][9];
fillBoard(chessBoard);
placeQueen(chessBoard);
printBoard(chessBoard);
}

private static void fillBoard(String[][] board) {
String[] fields = {"A", "B", "C", "D", "E", "F", "G", "H"};
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (i == 0 && j != 0) {
board[i][j] = String.valueOf(j);
} else if (j == 0 && i != 0) {
board[i][j] = fields[i - 1];
} else {
board[i][j] = ".";
}
}
}
}

private static void printBoard(String[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (i == 0 && j == 0) {
System.out.print(" ");
} else {
System.out.print("|");
System.out.print(board[i][j]);
}
}
System.out.println("|");
}
}

private static void placeQueen(String[][] board) {
ArrayList<int[]> positions = new ArrayList<>();
int x = 1;
int y = 1;
while (true) {
for (int i = x; i < board.length; i++) {
for (int j = y; j < board[i].length; j++) {
board[i][j] = "Q";
if (checkPositions(board, i, j)) {
int[] current = new int[2];
current[0] = i;
current[1] = j;
positions.add(current);
break;
} else {
board[i][j] = ".";
}
}
}
if (positions.size() < 7) {
int[] temp = positions.get(positions.size() - 1);
if (temp[1] + 1 == 9 || temp[0] + 1 == 9) {
x = temp[0] + 1;
y = 1;
} else {
x = temp[0];
y = temp[1] + 1;
}
positions.remove(positions.size() - 1);
for (int i = x; i < 9; i++) {
for (int j = 1; j < 9; j++) {
board[i][j] = ".";
}
}
} else {
break;
}
}
}

private static boolean checkPositions(String[][] board, int row, int col) {
for (int i = 1; i < board.length; i++) {
for (int j = 1; j < board[i].length; j++) {
if (i == row || j == col) {
if (!(i == row && j == col)) {
if (board[i][j].equals("Q")) {
return false;
}
}
} else if (Math.abs(i - row) == Math.abs(j - col)) {
if (board[i][j].equals("Q")) {
return false;
}
}
}
}
return true;
}
}
18 changes: 18 additions & 0 deletions Seminar05/list.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Иван Иванов
Светлана Петрова
Кристина Белова
Анна Мусина
Анна Крутова
Иван Юрин
Петр Лыков
Павел Чернов
Петр Чернышов
Мария Федорова
Марина Светлова
Мария Савина
Мария Рыкова
Марина Лугова
Анна Владимирова
Иван Мечников
Петр Петин
Иван Ежов
Loading