prog lab3

This commit is contained in:
2025-12-29 01:16:23 +03:00
parent 5dee130917
commit 7163a60498
69 changed files with 71 additions and 0 deletions

Binary file not shown.

View File

@@ -0,0 +1,28 @@
def to_negadecimal(num):
if isinstance(num, int):
return to_negadecimal_int(num)
else:
return to_negadecimal_notint(num)
def to_negadecimal_int(num):
if num == 0:
return 0
res = ""
while num != 0:
rem = num % (-10)
num //= (-10)
if rem < 0:
num += 1
rem += 10
res += str(rem)
return res[::-1]
def to_negadecimal_notint(num):
numm = int(num)
rem = int(str(round(num - numm, 10))[2:])
return f"{to_negadecimal_int(numm)}.{to_negadecimal_int(rem)}"
print(to_negadecimal(int(input("введите число:"))))

View File

@@ -0,0 +1,29 @@
def hamming(num):
bits = [int(i) for i in str(num)]
s1 = (bits[0] + bits[2] + bits[4] + bits[6]) % 2
s2 = (bits[1] + bits[2] + bits[5] + bits[6]) % 2
s3 = (bits[3] + bits[4] + bits[5] + bits[6]) % 2
syndr = s1 + s2 * 2 + s3 * 4
if syndr == 0:
corr = bits
else:
err = syndr - 1
corr = bits
if corr[err] == 1:
corr[err] = 0
else:
corr[err] = 1
info_bits = f"{corr[2]}{corr[4]}{corr[5]}{corr[6]}"
return info_bits
def main(num):
if len(num) == 7:
return hamming(num)
else:
return print("число не соответствует условию")
print(main(input("введите число: ")))

View File

@@ -0,0 +1,31 @@
import re
import unittest
def main(text):
pattern = r"(\w+)(\s+\1\b)"
return re.sub(pattern ,r"\1", text)
class task1_test(unittest.TestCase):
def test1(self):
text = "Довольно распространённая ошибка ошибка это лишний повтор повтор слова слова. Смешно, не не правда ли? Не нужно портить хор хоровод."
self.assertEqual(main(text), "Довольно распространённая ошибка это лишний повтор слова. Смешно, не правда ли? Не нужно портить хор хоровод.")
def test2(self):
text = "Да Да, пошли сходим сходим туда"
self.assertEqual(main(text), "Да, пошли сходим туда")
def test3(self):
text = "Он пошел пошел в магазин, вместе с мамой мамой за за мороженным"
self.assertEqual(main(text), "Он пошел в магазин, вместе с мамой за мороженным")
def test4(self):
text = "Я решил, что очень очень хочу наприсать ПСЖ ПСЖ"
self.assertEqual(main(text), "Я решил, что очень хочу наприсать ПСЖ")
def test5(self):
text = "P3116 P3116 лучшая группа группа в ИТМО ИТМО"
self.assertEqual(main(text), "P3116 лучшая группа в ИТМО")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,31 @@
import re
import unittest
# students.spam@yandex.ru => yandex.ru
# example@example => Fail!
# example@example.com => example.com
def main(text):
pattern = r"(?<=@)\w+\.\w+"
match = re.search(pattern, text)
if match:
return match.group(0)
else:
return "Fail!"
class task2_test(unittest.TestCase):
def test1(self):
text = "students.spam@yandex.ru"
self.assertEqual(main(text), "yandex.ru")
def test2(self):
text = "example@example"
self.assertEqual(main(text), "Fail!")
def test3(self):
text = "example@example.com"
self.assertEqual(main(text), "example.com")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,37 @@
import re
import unittest
class task3_test(unittest.TestCase):
text = str(input("введите текст:"))
def test1(self):
flag = False
if not re.search(r"\w{5}", self.text):
self.fail("Your password must be at least 5 characters.")
def test2(self):
if not re.search(r"[0-9]", self.text):
self.fail("Your password must include a number.")
def test3(self):
if not re.search(r"[A-Z]", self.text):
self.fail("Your password must include an uppercase letter.")
def test4(self):
if not re.search(r"\W", self.text):
self.fail("Your password must include a special character.")
def test5(self):
mas = re.findall(r"\d", self.text)
sum = 0
for i in range(len(mas)):
sum += int(mas[i])
if sum != 25:
self.fail("The digits in your password must add up to 25.")
def test6(self):
if not re.search(r"(january|febuary|march|april|may|june|july|august|september|october|november|december)", self.text):
self.fail("Your password must include a month of the year.")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,54 @@
import unittest
pszh = r"""
#5&1
$&#^!) dP""b8 ! # T #9g&2 f h b c b nc k p
w g dP `" %" @* &8 ! 1 5 $ / \ % @ d / o
# ! Yb @ &^ )s g4&8$ % 1 ^ 4 d % | %?4/2
d a @# !) o4a .o. 7# -1 % # # g +g<?6&$ n # 1 & n
( ! YboodP h @ % `"' f%s#6 # ) @ ! 0 d 1& v i ^
ййй
пппппп сссссс ж ж ж оооо н н л а й йй н н
п п сс сс жжж оо оо н н л л а а й й й н н
п п сс ж оо оо ннннн л л а а й й й ннннн
п п сс сс жжж .o. оо оо н н л л ааааааа й й й н н
п п сссссс ж ж ж `"' оооо н н л л а а йй й н н
"""
def task1():
load = unittest.TestLoader()
test = load.loadTestsFromName("Informatics_Lab3_Task1")
run = unittest.TextTestRunner()
res = run.run(test)
def task2():
loader = unittest.TestLoader()
test = loader.loadTestsFromName("Informatics_Lab3_Task2")
run = unittest.TextTestRunner()
res = run.run(test)
def task3():
loader = unittest.TestLoader()
test = loader.loadTestsFromName("Informatics_Lab3_Task3")
run = unittest.TextTestRunner()
res = run.run(test)
def menu():
print(pszh + "\n" + "1 - task1" + "\n" + "2 - task2" + "\n" + "3 - task3")
inp = int(input("Выберите задание:"))
match inp:
case 1:
task1()
case 2:
task2()
case 3:
task3()
if __name__ == "__main__":
while True:
menu()

View File

@@ -0,0 +1,7 @@
a = input("выбери: ")
match a:
case 1:
print(1)
case 2:
print(2)

View File

@@ -0,0 +1,23 @@
(
day: "Ср",
schedule: [
(
time: "11:30-13:00",
weeks: [2, 4, 6, 8, 10, 12, 14, 16],
group: "ИНФОРМ КСИТ 2",
subject: "ИНФОРМАТИКА (ЛЕК)",
type: "АКТОВЫЙ ЗАЛ",
class: "ул. Ломоносова, д.9, лит. М",
format: "Очно - дистанционный",
),
(
time: "11:30-13:00",
weeks: [2, 4, 6, 8, 10, 12, 14, 16],
group: "ИНФОРМ СИППО 1",
subject: "ИНФОРМАТИКА (ЛЕК)",
type: "АКТОВЫЙ ЗАЛ",
class: "ул. Ломоносова, д.9, лит. М",
format: "Очно - дистанционный",
),
]
)

View File

@@ -0,0 +1,77 @@
import time
from task1.ron_desirializer import RonDesirializer, Token
from task2.ini_serializer import IniSerializer
from task3.ini_serializer_lib import LibSerializer
from task4.xml_serializer import XmlSerializer
file = open("input.ron")
text = file.read()
# task1 ron => binary
print("task1")
tokens = Token.tokenize(text)
deserializer = RonDesirializer(tokens)
parsed = deserializer.parse()
print(parsed)
print("\n")
# task2 binary => ini
print("task2")
serializer = IniSerializer(parsed)
ini = serializer.serialize()
print(ini)
print("\n")
# task3
print("task3")
serializer_instance = LibSerializer()
serializer_instance.serializer(parsed)
print("вывод в файле")
print("\n")
# task4
print("task4")
serializer = XmlSerializer(parsed)
xml_output = serializer.serialize()
print(xml_output)
print("\n")
# task5
print("task5")
N = 100
# RON => INI
start_time = time.perf_counter()
for i in range(N):
tokens = Token.tokenize(text)
deserializer = RonDesirializer(tokens)
parsed_data = deserializer.parse()
# Сериализация
serializer = IniSerializer(parsed_data)
i = serializer.serialize()
time_ini = time.perf_counter() - start_time
print(time_ini)
# RON => INI LIB
start_time = time.perf_counter()
for i in range(N):
tokens = Token.tokenize(text)
deserializer = RonDesirializer(tokens)
parsed_data = deserializer.parse()
serializer_instance.serializer(parsed_data)
time_ini_lib = time.perf_counter() - start_time
print(time_ini_lib)
# RON => XML
start_time = time.perf_counter()
for i in range(N):
tokens = Token.tokenize(text)
deserializer = RonDesirializer(tokens)
parsed_data = deserializer.parse()
serializer = XmlSerializer(parsed_data)
i = serializer.serialize()
time_xml = time.perf_counter() - start_time
print(time_xml)

View File

@@ -0,0 +1,20 @@
[Genera Ср]
day of week = Ср
[Ср Lesson 1]
time = 11:30-13:00
weeks = 2, 4, 6, 8, 10, 12, 14, 16
group = ИНФОРМ КСИТ 2
subject = ИНФОРМАТИКА (ЛЕК)
type = АКТОВЫЙ ЗАЛ
class = ул. Ломоносова, д.9, лит. М
format = Очно - дистанционный
[Ср Lesson 2]
time = 11:30-13:00
weeks = 2, 4, 6, 8, 10, 12, 14, 16
group = ИНФОРМ СИППО 1
subject = ИНФОРМАТИКА (ЛЕК)
type = АКТОВЫЙ ЗАЛ
class = ул. Ломоносова, д.9, лит. М
format = Очно - дистанционный⏎

View File

View File

@@ -0,0 +1,89 @@
class Token:
def __init__(self, type, value=None):
self.type = type
self.value = value
def tokenize(text):
"""разбивает на токены"""
tokens, i, n = [], 0, len(text)
while i < n:
char = text[i]
# скип пробелов и переносов
if char.isspace():
i += 1
# разделяшки всякие
elif char in '(),:[]':
tokens.append(Token(char))
i += 1
# строки
elif char == '"':
start = i + 1
i += 1
while i < n and text[i] != '"': i += 1
tokens.append(Token('STRING', text[start:i]))
i += 1
# состоит ли число из буков или чисел
elif char.isalnum():
start = i
while i < n and text[i].isalnum(): i += 1
val = text[start:i]
tokens.append(Token('NUMBER', int(val)) if val.isdigit() else Token('KEY', val))
else:
i += 1
return tokens
class RonDesirializer:
def __init__(self, tokens):
self.tokens = tokens
self.index = 0
def look(self):
"""посмотреть на следующий токен"""
if self.index < len(self.tokens): return self.tokens[self.index]
def extract(self, _=None):
"""увеличивает индекс и возвращает настоящий токен. так же можно задать нужный токен и найти его"""
token = self.look()
self.index += 1
return token
def parse_obj(self):
"""парсит()"""
self.extract()
result = self.parse_keys()
self.extract()
return result
def parse_mas(self):
"""парсит массив"""
self.extract()
values = []
while self.look().type != ']':
values.append(self.what_parse())
if self.look().type == ',': self.extract()
self.extract()
return values
def parse_keys(self):
"""парсит пары ключ:значение"""
members = {}
while self.look().type != ')':
# парсит пару ключ:значение
key = self.extract().value
self.extract()
members[key] = self.what_parse()
if self.look().type == ',': self.extract()
return members
def what_parse(self):
"""что парсить"""
token = self.look()
if token.type in ('STRING', 'NUMBER'):
return self.extract().value
return self.parse_obj() if token.type == '(' else self.parse_mas()
def parse(self):
return self.parse_obj()

View File

View File

@@ -0,0 +1,32 @@
class IniSerializer:
def __init__(self, inp):
self.inp = inp
def to_ini_string(self, value):
"""конвертация в подходящий формат для ini"""
if isinstance(value, list):
parts = [str(v) for v in value]
return ", ".join(parts)
return str(value)
def serialize(self):
ini_lines = []
day = self.inp.get('day', '')
ini_lines.append("[General]")
ini_lines.append(f"day_of_week = {day}")
ini_lines.append("")
schedule = self.inp.get('schedule', [])
for index, lesson in enumerate(schedule, 1):
section_name = f"Lesson_{index}"
ini_lines.append(f"[{section_name}]")
for key, value in lesson.items():
ini_value = self.to_ini_string(value)
ini_lines.append(f"{key} = {ini_value}")
ini_lines.append("")
return "\n".join(ini_lines).strip()

View File

View File

@@ -0,0 +1,29 @@
import configparser
import json
class LibSerializer:
"""сериализация в ini при помощи библиотек"""
def serializer(self, inp, filename='schedule_output.ini'):
config = configparser.ConfigParser()
config.add_section('General')
if 'day' in inp:
config.set('General', 'day_of_week', str(inp['day']))
schedule = inp.get('schedule', [])
for index, lesson in enumerate(schedule, 1):
section_name = f"Lesson_{index}"
config.add_section(section_name)
for key, value in lesson.items():
if isinstance(value, list):
str_value = ', '.join(map(str, value))
else:
str_value = str(value)
config.set(section_name, key, str_value)
with open(filename, 'w', encoding='utf-8') as configfile:
config.write(configfile)

View File

@@ -0,0 +1,21 @@
[General]
day_of_week = Ср
[Lesson_1]
time = 11:30-13:00
weeks = 2, 4, 6, 8, 10, 12, 14, 16
group = ИНФОРМ КСИТ 2
subject = ИНФОРМАТИКА (ЛЕК)
type = АКТОВЫЙ ЗАЛ
class = ул. Ломоносова, д.9, лит. М
format = Очно - дистанционный
[Lesson_2]
time = 11:30-13:00
weeks = 2, 4, 6, 8, 10, 12, 14, 16
group = ИНФОРМ СИППО 1
subject = ИНФОРМАТИКА (ЛЕК)
type = АКТОВЫЙ ЗАЛ
class = ул. Ломоносова, д.9, лит. М
format = Очно - дистанционный

View File

View File

@@ -0,0 +1,37 @@
class XmlSerializer:
def __init__(self, data):
self.data = data
def escape(self, value):
"""замена не подходящих символов"""
return str(value).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def serialize(self):
xml_lines = []
xml_lines.append('<?xml version="1.0" encoding="UTF-8"?>')
day = self.data.get('day', '')
schedule_list = self.data.get('schedule', [])
xml_lines.append(f'<Schedule day="{self.escape(day)}">')
for index, lesson in enumerate(schedule_list, 1):
xml_lines.append(f' <Lesson id="{index}">')
for key, value in lesson.items():
if isinstance(value, list):
value_str = ", ".join(map(str, value))
else:
value_str = str(value)
content = self.escape(value_str)
xml_lines.append(f' <{key}>{content}</{key}>')
xml_lines.append(' </Lesson>')
xml_lines.append('</Schedule>')
return "\n".join(xml_lines).strip()

View File

@@ -0,0 +1,48 @@
1. Создать приведенное в варианте дерево каталогов и файлов с содержимым. В качестве корня дерева использовать каталог lab0 своего домашнего каталога. Для создания и навигации по дереву использовать команды: mkdir, echo, cat, touch, ls, pwd, cd, more, cp, rm, rmdir, mv.
<img width="594" height="967" alt="изображение" src="https://github.com/user-attachments/assets/832df166-8d85-420b-ab82-d0cd544cbb30" />
2. Установить согласно заданию права на файлы и каталоги при помощи команды chmod, используя различные способы указания прав.
- cleffa5: rwxrwxrwx
- bellsprout: права 006
- oshawott: r-xrwx-wx
- togetic: r-x-wxrwx
- pidove: r--------
- charmander: права 355
- servine: права 404
- porygon20: права 570
- mantyke: rw-r-----
- sandshrew: права 700
- alakazam: r--r--r--
- gligar: владелец должен не иметь никаких прав; группа-владелец должна читать и записывать файл; остальные пользователи должны записывать файл
- roserade5: владелец должен читать файл; группа-владелец должна не иметь никаких прав; остальные пользователи должны читать файл
- togepi2: права 666
- vanilluxe0: права 004
- vigoroth5: rwxrw-r--
- musharna: права 751
- fearow: права 666
- krokorok: r-xrwxrwx
3. Скопировать часть дерева и создать ссылки внутри дерева согласно заданию при помощи команд cp и ln, а также комманды cat и перенаправления ввода-вывода.
- cоздать жесткую ссылку для файла roserade5 с именем lab0/porygon20/mantykeroserade
- cоздать символическую ссылку для файла roserade5 с именем lab0/cleffa5/pidoveroserade
- скопировать содержимое файла vanilluxe0 в новый файл lab0/cleffa5/bellsproutvanilluxe
- скопировать рекурсивно директорию cleffa5 в директорию lab0/vigoroth5/musharna
- создать символическую ссылку c именем Copy_32 на директорию cleffa5 в каталоге lab0
- скопировать файл roserade5 в директорию lab0/porygon20/sandshrew
- объеденить содержимое файлов lab0/cleffa5/servine, lab0/porygon20/mantyke, в новый файл lab0/roserade5_90
4. Используя команды cat, wc, ls, head, tail, echo, sort, grep выполнить в соответствии с вариантом задания поиск и фильтрацию файлов, каталогов и содержащихся в них данных.
- Подсчитать количество символов содержимого файла roserade5, результат записать в файл в директории /tmp, ошибки доступа не подавлять и не перенаправлять
- Вывести рекурсивно список имен файлов в директории cleffa5, список отсортировать по имени a->z, ошибки доступа перенаправить в файл в директории /tmp
- Рекурсивно вывести содержимое файлов из директории lab0, имя которых начинается на 't', строки отсортировать по имени z->a, добавить вывод ошибок доступа в стандартный поток вывода
- Вывести содержимое файлов: bellsprout, pidove, servine, mantyke, alakazam, gligar с номерами строк, строки отсортировать по имени z->a, подавить вывод ошибок доступа
- Вывести список имен и атрибутов файлов в директории cleffa5, список отсортировать по убыванию даты модификации файла, ошибки доступа не подавлять и не перенаправлять
- Вывести содержимое файлов: bellsprout, pidove, servine, mantyke, alakazam, gligar, оставить только строки, заканчивающиеся на 'e', регистр символов игнорировать, ошибки доступа перенаправить в файл в директории /tmp
5. Выполнить удаление файлов и каталогов при помощи команд rm и rmdir согласно варианту задания.
- Удалить файл roserade5
- Удалить файл lab0/porygon20/mantyke
- удалить символические ссылки lab0/cleffa5/pidoverosera*
- удалить жесткие ссылки lab0/porygon20/mantykerosera*
- Удалить директорию porygon20
- Удалить директорию lab0/vigoroth5/musharna

Binary file not shown.

View File

@@ -0,0 +1,42 @@
mkdir lab0
cd lab0
mkdir cleffa5
mkdir porygon20
touch roserade5
touch togepi2
touch vanilluxe0
mkdir vigoroth5
mkdir cleffa5/oshawott
mkdir cleffa5/togetic
mkdir cleffa5/charmander
touch cleffa5/bellsprout
touch cleffa5/pidove
touch cleffa5/servine
mkdir porygon20/sandshrew
touch porygon20/mantyke
touch porygon20/alakazam
touch porygon20/gligar
mkdir vigoroth5/musharna
mkdir vigoroth5/krokorok
touch vigoroth5/fearow
echo "Тип покемона GRASS POISON" >> cleffa5/bellsprout
echo "weigth=4.6 height=12.0
atk=6 def=5" >> cleffa5/pidove
echo "weigth=35.3 height=31.0 atk=6
def=8" >> cleffa5/servine
echo "Живет Ocean" >> porygon20/mantyke
echo "Возможности Overland=7
Surface=3 Jump=2 Power=2 Intelligence=7 Aura=0 Telekinetic=0" >> porygon20/alakazam
echo "Возможности Overland=4 Sky=6 Burrow=4 Jump=4
Power2=0 Intelligence=4 Sinker=0" >> porygon20/gligar
echo "Тип покемона GRASS" >> roserade5
echo "Тип покемона NORMAL NONE" >> togepi2
echo "Живет Cave
Taiga Tundra" >> vanilluxe0
echo "Ходы Air Cutter Double-Edge Defog Drill Run Heat
Wave Mud-Slap Omnious Wind Pluck+ Roost Sky Attack Sleep Talk Snore
Steel Wing Swift Tailwind Twister Uproar" >> vigoroth5/fearow

View File

@@ -0,0 +1,20 @@
cd lab0
chmod 777 cleffa5
chmod 006 cleffa5/bellsprout
chmod u=rx,g=rwx,o=wx cleffa5/oshawott
chmod u=rx,g=wx,o=rwx cleffa5/togetic
chmod 400 cleffa5/pidove
chmod 355 cleffa5/charmander
chmod 404 cleffa5/servine
chmod 570 porygon20
chmod u=rw,g=r,o= porygon20/mantyke
chmod 700 porygon20/sandshrew
chmod 222 porygon20/alakazam
chmod u=,g=,o=r porygon20/gligar
chmod u=r,g=,o=r roserade5
chmod 666 togepi2
chmod 004 vanilluxe0
chmod u=rwx,g=rw,o=r vigoroth5
chmod 751 vigoroth5/musharna
chmod 666 vigoroth5/fearow
chmod 577 vigoroth5/krokorok

View File

@@ -0,0 +1,13 @@
cd lab0
chmod u+w porygon20
chmod u+rw vanilluxe0
chmod u+rw cleffa5
chmod u+r cleffa5/bellsprout
chmod u+r cleffa5/charmander
ln roserade5 porygon20/mantykeroserade
ln -s roserade5 cleffa5/pidoveroserade
cp vanilluxe0 cleffa5/bellsproutvanilluxe
cp -R cleffa5 vigoroth5/musharna/
ln -s cleffa5 Copy_32
cp roserade5 porygon20/sandshrew
cat cleffa5/servine porygon20/mantyke > roserade5_90g

View File

@@ -0,0 +1,9 @@
cd lab0
cat roserade5 | wc -m > /tmp/count
ls -R cleffa5 2>/tmp/errors | sort
cd ..
ls -R lab0 2>/dev/null | grep '^t' | sort -r
cd lab0
cat -n cleffa5/bellsprout cleffa5/pidove cleffa5/servine porygon20/mantyke porygon20/alakazam porygon20/gligar 2>/dev/null | sort -k2r
ls -l cleffa5 | sort -k6r
cat cleffa5/bellsprout cleffa5/pidove cleffa5/servine porygon20/mantyke porygon20/alakazam porygon20/gligar 2>/tmp/errors | grep -i 'e$'

View File

@@ -0,0 +1,7 @@
cd lab0
rm -rf roserade5
rm -rf porygon20/mantyke
rm -rf cleffa5/pidoverosera*
rm -rf porygon20/mantykerosera*
rm -rf porygon20
rm -rf vigoroth5/musharna

View File

@@ -0,0 +1,6 @@
1. Создать одномерный массив w типа int. Заполнить его нечётными числами от 7 до 15 включительно в порядке убывания.
2. Создать одномерный массив x типа double. Заполнить его 14-ю случайными числами в диапазоне от -10.0 до 15.0.
3. Создать двумерный массив l размером 5x14. Вычислить его элементы по следующей формуле (где x = x[j]):
<img width="738" height="222" alt="изображение" src="https://github.com/user-attachments/assets/8362caf4-0fcd-4685-a2ae-44bf91357e0d"/>
4. Напечатать полученный в результате массив в формате с тремя знаками после запятой.

Binary file not shown.

View File

@@ -0,0 +1,64 @@
import java.lang.Math;
public class Main {
public static void main(String[] args) {
// массив w
int[] w = new int[5];
// массив x
double[] x = new double[14];
// массив f 5x14
double[][] f = new double[5][14];
// счет нечетных чисел для массива w
int nech = 15;
// заполнение массива w
for (int i = 0; i < w.length; i++){
w[i] = nech;
nech -= 2;
}
// заполнение массива x
for (int i = 0; i < x.length; i++){
x[i] = (Math.random() * (14 + 10 + 1) - 10);
}
// проверка, выполнение выражений и заполнение массива f
for (int i = 0; i < w.length; i++){
for (int j = 0; j < 14; j++){
if (w[i] == 7){
f[i][j] = ifSeven(x[j]);
}
else if (w[i] >= 11 && w[i] <= 13){
f[i][j] = ifElevenThirteen(x[j]);
}
else {
f[i][j] = ifOther(x[j]);
}
}
}
matrix(f);
}
// методы для вычисления элементов массива
public static double ifSeven(double x){
return Math.sin(Math.sin(x/2));
}
public static double ifElevenThirteen(double x){
return Math.asin(Math.cos(Math.pow(Math.pow(x,3) / (Math.pow(x, 3) + 1),3)));
}
public static double ifOther(double x){
return Math.cos(Math.asin(0.25 * (1 / Math.pow(Math.E, Math.abs(x)))));
}
// вывод матрицы
public static void matrix(double[][] mas){
for (int i = 0; i < mas.length; i++){
for (int j = 0; j < mas[i].length; j++){
System.out.printf("%.3f" + " ",mas[i][j]);
}
System.out.println();
}
}
}

30
1st stage/prog/lab2/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
1st stage/prog/lab2/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@@ -0,0 +1,9 @@
<component name="ArtifactManager">
<artifact type="jar" name="lab2:jar">
<output-path>$PROJECT_DIR$/out/artifacts/lab2_jar</output-path>
<root id="archive" name="lab2.jar">
<element id="module-output" name="lab2" />
<element id="extracted-dir" path="$PROJECT_DIR$/Pokemon.jar" path-in-jar="/" />
</root>
</artifact>
</component>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
</profile>
</component>

View File

@@ -0,0 +1,9 @@
<component name="libraryTable">
<library name="Pokemon">
<CLASSES>
<root url="jar://$PROJECT_DIR$/Pokemon.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

6
1st stage/prog/lab2/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="ms-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
1st stage/prog/lab2/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/lab2.iml" filepath="$PROJECT_DIR$/lab2.iml" />
</modules>
</component>
</project>

6
1st stage/prog/lab2/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

Binary file not shown.

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Pokemon" level="project" />
</component>
</module>

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: main

View File

@@ -0,0 +1,22 @@
import ru.ifmo.se.pokemon.Battle;
import ru.ifmo.se.pokemon.Pokemon;
import pokemons.*;
class main {
public static void main(String[] args) {
Battle b = new Battle();
Pokemon a1 = new AegislashBlade("Игорь", 100);
Pokemon a2 = new Doublade("Святогор", 100);
Pokemon a3 = new Slowpoke("Родион", 100);
Pokemon f1 = new Slowbro("Медленныйчувак", 100);
Pokemon f2 = new Regice("Олег", 100);
Pokemon f3 = new Honedge("Хз", 100);
b.addAlly(a1);
b.addAlly(a2);
b.addAlly(a3);
b.addFoe(f1);
b.addFoe(f2);
b.addFoe(f3);
b.go();
}
}

View File

@@ -0,0 +1,18 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Bulldoze extends PhysicalMove {
public Bulldoze() {
super(Type.GROUND, 60, 100);
}
@Override
protected void applyOppEffects(Pokemon p) {
p.addEffect(new Effect().stat(Stat.SPEED, -1));
}
@Override
protected String describe() {
return "использует bulldoze и уменьшает скорость оппонента на 1";
}
}

View File

@@ -0,0 +1,27 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class FocusBlast extends SpecialMove {
boolean flag = false;
public FocusBlast() {
super(Type.FIGHTING, 120, 70);
}
@Override
protected void applyOppEffects(Pokemon p) {
Effect eff = new Effect();
p.addEffect(eff.chance(0.1));
if (eff.success()) {
flag = true;
p.addEffect(eff.stat(Stat.SPECIAL_DEFENSE, -1));
}
}
@Override
protected String describe() {
if (flag) {
return "использует FocusBlast и уменьшает special defense противника на 1";
}
else {
return "использует FocusBlast";
}
}
}

View File

@@ -0,0 +1,31 @@
package moves;
import ru.ifmo.se.pokemon.Effect;
import ru.ifmo.se.pokemon.Pokemon;
import ru.ifmo.se.pokemon.SpecialMove;
import ru.ifmo.se.pokemon.Type;
public class Headbutt extends SpecialMove {
boolean flag = false;
public Headbutt() {
super(Type.PSYCHIC, 50, 100);
}
@Override
protected void applyOppEffects(Pokemon p) {
Effect eff = new Effect();
p.addEffect(eff.chance(0.3));
if (eff.success()) {
flag = true;
Effect.flinch(p);
}
}
@Override
protected String describe() {
if (flag){
return "использует Headbutt и накладывает flinch на противника";
}
else {
return "использует headbutt";
}
}
}

View File

@@ -0,0 +1,17 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class IronDefense extends StatusMove {
public IronDefense() {
super(Type.STEEL, 0, 0);
}
@Override
protected void applySelfEffects(Pokemon p) {
p.addEffect(new Effect().stat(Stat.DEFENSE, +2));
}
@Override
protected String describe() {
return "использует Iron Defense";
}
}

View File

@@ -0,0 +1,29 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Scald extends SpecialMove {
boolean flag = false;
public Scald(){
super(Type.WATER, 80, 100);
}
@Override
protected void applyOppEffects(Pokemon p) {
Effect eff = new Effect();
p.addEffect(eff.chance(0.3));
if (eff.success()) {
flag = true;
Effect.burn(p);
}
}
@Override
protected String describe() {
if (flag) {
return "использует Scald и поджигает противника";
}
else {
return "использует Scald";
}
}
}

View File

@@ -0,0 +1,26 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class ShadowClaw extends PhysicalMove {
boolean flag = false;
public ShadowClaw() {
super(Type.GHOST, 70, 100);
}
@Override
protected double calcCriticalHit(Pokemon att, Pokemon def) {
if (att.getStat(Stat.SPEED) / (double)8.0F > Math.random()) {
flag = true;
return (double)2.0F;
} else {
return (double)1.0F;
}
}
@Override
protected String describe() {
if (flag) {
return "использует Shadow Claw с повышенным шансом на крит";}
else {
return "использует Shadow Claw";
}
}
}

View File

@@ -0,0 +1,17 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class SlackOff extends StatusMove {
public SlackOff() {
super(Type.NORMAL, 0, 0);
}
@Override
protected void applySelfEffects(Pokemon p) {
double hp = p.getHP() / 2;
p.addEffect(new Effect().stat(Stat.HP, (int) hp));
}
@Override
protected String describe() {
return "использует SlackOff восстанавливая половину hp";
}
}

View File

@@ -0,0 +1,27 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Slash extends PhysicalMove {
boolean flag = false;
public Slash() {
super(Type.NORMAL, 70, 100);
}
@Override
protected double calcCriticalHit(Pokemon att, Pokemon def) {
if (att.getStat(Stat.SPEED) / (double)8.0F > Math.random()) {
flag = true;
return (double)2.0F;
} else {
return (double)1.0F;
}
}
@Override
protected String describe() {
if (flag) {
return "использует Slash с повышенным шансом на крит";}
else {
return "использует Slash";
}
}
}

View File

@@ -0,0 +1,12 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Stomp extends PhysicalMove {
public Stomp() {
super(Type.NORMAL, 60, 100);
}
@Override
protected String describe() {
return "использует Stomp";
}
}

View File

@@ -0,0 +1,17 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Swagger extends StatusMove {
public Swagger() {
super(Type.NORMAL, 0, 85);
}
@Override
protected void applyOppEffects(Pokemon p) {
p.addEffect(new Effect().stat(Stat.ATTACK, +2));
Effect.confuse(p);
}
@Override
protected String describe() {
return "использует Swagger добавляя оппоненту 2 к аттаке и дает ему конфуз";
}
}

View File

@@ -0,0 +1,12 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Tackle extends PhysicalMove {
public Tackle() {
super(Type.NORMAL, 40, 100);
}
@Override
protected String describe() {
return "использует Tackle";
}
}

View File

@@ -0,0 +1,12 @@
package moves;
import ru.ifmo.se.pokemon.*;
public class Thunderbolt extends SpecialMove{
public Thunderbolt() {
super(Type.ELECTRIC, 90, 100);
}
@Override
protected String describe() {
return "использует Thunderbolt";
}
}

View File

@@ -0,0 +1,10 @@
package pokemons;
import moves.*;
public class AegislashBlade extends Doublade {
public AegislashBlade(String name, int level) {
super(name, level);
setStats(60, 150, 50, 150, 50, 60);
addMove(new ShadowClaw());
}
}

View File

@@ -0,0 +1,11 @@
package pokemons;
import moves.*;
public class Doublade extends Honedge {
public Doublade(String name, int level) {
super(name, level);
int baseAttack = 59;
setStats(baseAttack, 110, 150, 45, 49, 35);
addMove(new Tackle());
}
}

View File

@@ -0,0 +1,19 @@
package pokemons;
import ru.ifmo.se.pokemon.*;
import moves.*;
public class Honedge extends dop {
public Honedge(String name, int level) {
super(name, level, new Type[]{Type.STEEL, Type.GHOST});
int baseAttack = 45;
int bonusCount = 0;
setMove(new IronDefense(), new Slash());
setStats(baseAttack, 80, 100, 35, 37, 28);
if (level % 100 == 0 & !randType()) {
bonusCount = level / 100;
System.out.println(name + " урон увелчилися на 20 процентов");
baseAttack = (int) (baseAttack * Math.pow(1.2, bonusCount));
setStats(baseAttack, 80, 100, 35, 37, 28);
}
}
}

View File

@@ -0,0 +1,12 @@
package pokemons;
import moves.*;
import ru.ifmo.se.pokemon.*;
public class Regice extends Pokemon {
public Regice(String name, int level){
super(name, level);
setType(Type.ICE);
setStats(80, 50, 100, 100, 200, 50);
setMove(new Bulldoze(), new Thunderbolt(), new Stomp(), new Swagger());
}
}

View File

@@ -0,0 +1,10 @@
package pokemons;
import moves.*;
public class Slowbro extends Slowpoke {
public Slowbro(String name, int level) {
super(name, level);
setStats(95, 75, 110, 100, 80, 30);
setMove(new FocusBlast());
}
}

View File

@@ -0,0 +1,19 @@
package pokemons;
import moves.*;
import ru.ifmo.se.pokemon.*;
public class Slowpoke extends dop {
public Slowpoke(String name, int level) {
super(name, level, new Type[]{Type.WATER, Type.PSYCHIC});
int baseAttack = 90;
int bonusCount = 0;
setStats(baseAttack, 65, 65, 40, 40, 15);
setMove(new Scald(), new SlackOff(), new Headbutt());
if (level % 100 == 0 & !randType()) {
bonusCount = level / 100;
System.out.println(name + " урон увелчилися на 20 процентов");
baseAttack = (int) (baseAttack * Math.pow(1.2, bonusCount));
setStats(baseAttack, 65, 65, 40, 40, 15);
}
}
}

View File

@@ -0,0 +1,62 @@
package pokemons;
import ru.ifmo.se.pokemon.*;
import java.util.Arrays;
public class dop extends Pokemon {
public dop(String name, int level, Type[] types) {
super(name, level);
setType(types);
}
private final Type[][] hz = {
{Type.FIRE, Type.WATER},
{Type.NORMAL, Type.GHOST},
{Type.ELECTRIC, Type.GRASS},
{Type.ICE, Type.FIRE},
{Type.FIGHTING, Type.GHOST},
{Type.DARK, Type.PSYCHIC}
};
protected boolean randType() {
Type[] currTypes = this.getTypes();
if (currTypes.length >= 2) {
return false;
}
final Type[] allTypes = Type.values();
// удалить none из массива
int rand = (int) (Math.random() * allTypes.length) - 1;
Type newType = allTypes[rand];
boolean allowed = true;
for (Type[] pair : hz) {
boolean oneInPair = false;
boolean newTypeInPair = false;
for (Type oneOfPair : pair) {
if (oneOfPair == newType) {
newTypeInPair = true;
}
for (Type ct : currTypes) {
if (ct == oneOfPair) {
oneInPair = true;
}
}
}
if (oneInPair && newTypeInPair) {
allowed = false;
break;
}
}
if (allowed) {
addType(newType);
Type[] jlj = this.getTypes();
System.out.println("получает случайный тип");
System.out.println(Arrays.toString(jlj));
return true;
}
return false;
}
}

30
1st stage/prog/lab3/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
1st stage/prog/lab3/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AgentMigrationStateService">
<option name="migrationStatus" value="COMPLETED" />
</component>
</project>

6
1st stage/prog/lab3/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
1st stage/prog/lab3/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/lab3.iml" filepath="$PROJECT_DIR$/lab3.iml" />
</modules>
</component>
</project>

6
1st stage/prog/lab3/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/src" vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

Submodule 1st stage/prog/lab3/src added at d94032efcb