1
0
This commit is contained in:
2024-05-10 10:38:11 +03:00
parent ea7c09cdd2
commit 6fcee9ce9b
6 changed files with 513 additions and 0 deletions

Binary file not shown.

187
Лаб6/Сайт/index.html Normal file
View File

@@ -0,0 +1,187 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books Information</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<div>
<label for="N">Количество книг: </label>
<input type="number" id="N" value="10">
<button onclick="createBooksTable()">Сгенерировать</button>
<br>
<br>
<button onclick="loadBooksFromJSON()">Загрузить из JSON</button>
<br>
<br>
<button onclick="calculateBooksAge()">Посчитать возраст</button>
<br>
<br>
<label for="pages">Количество страниц: </label>
<input type="number" id="pages" value="0">
<button onclick="deletePagesInfo()">Удалить информацию о количестве страниц</button>
<br>
<br>
<h3>Поиск книг:</h3>
<label for="author">Фамилия автора: </label>
<input type="text" id="author">
<button onclick="searchBooksByAuthorSurname()">Найти</button>
<br>
<label for="genre">Жанр: </label>
<input type="text" id="genre">
<button onclick="searchBooksByGenre()">Найти</button>
<br>
<label for="yearMin">Минимальное значение года: </label>
<input type="number" id="yearMin">
<label for="yearMax">Максимальное значение года: </label>
<input type="number" id="yearMax">
<button onclick="searchBooksByYear()">Найти</button>
<br>
<br>
<button onclick="fillBooksTable(books)">Обновить</button>
<button onclick="cancel()">Отмена</button>
<br>
<br>
<button onclick="clearBooksTable()">Очистить</button>
</div>
<h1>Информация о книгах</h1>
<table id="books-table">
<thead>
<tr>
<th>Название</th>
<th>Автор</th>
<th>Жанр</th>
<th>Дата издания</th>
<th>Количество страниц</th>
<th>Возраст</th>
</tr>
</thead>
<tbody id="books-table-body">
</tbody>
</table>
<div>
<label for="json">JSON: </label>
<br>
<textarea id="json" cols="60" rows="40"></textarea>
</div>
<script src="script.js"></script>
<script>
let lastBooks = [];
let books = [];
function cancel() {
books = structuredClone(lastBooks);
fillBooksTable(books);
}
function searchBooksByAuthorSurname() {
const author = document.getElementById("author").value;
const filteredBooks = findBooksByAuthor(books, author);
fillBooksTable(filteredBooks);
}
function searchBooksByGenre() {
const genre = document.getElementById("genre").value;
const filteredBooks = findBooksByGenre(books, genre);
fillBooksTable(filteredBooks);
}
function searchBooksByYear() {
const yearMin = document.getElementById("yearMin").value;
const yearMax = document.getElementById("yearMax").value;
const filteredBooks = findBooksByPublishYearRange(books, yearMin, yearMax);
fillBooksTable(filteredBooks);
}
function createBooksTable() {
lastBooks = structuredClone(books);
const N = document.getElementById("N").value;
books = createBooksArray(N);
fillBooksTable(books);
}
function loadBooksFromJSON() {
lastBooks = structuredClone(books);
const json = document.getElementById("json").value;
books = JSON.parse(json);
books.map(book => {
book.publishDate = new Date(book.publishDate);
});
fillBooksTable(books);
}
function calculateBooksAge() {
lastBooks = structuredClone(books);
books = addAgeInfoToBooks(books);
fillBooksTable(books);
}
function clearBooksTable() {
lastBooks = structuredClone(books);
books = [];
fillBooksTable(books);
}
function deletePagesInfo() {
lastBooks = structuredClone(books);
books = removeBooksPageCount(books, document.getElementById("pages").value);
fillBooksTable(books);
}
function fillBooksTable(books) {
const tableBody = document.getElementById("books-table-body");
tableBody.innerHTML = "";
books.forEach(book => {
const row = document.createElement("tr");
let bookAge = 'Не просчитано';
if (book.age) {
bookAge = book.age;
}
row.innerHTML = `
<td>${book.title}</td>
<td>${book.author.name} ${book.author.surname}</td>
<td>${book.genre}</td>
<td>${book.publishDate.toISOString().split('T')[0]}</td>
<td>${book.pageCount}</td>
<td>${bookAge}</td>
`;
tableBody.appendChild(row);
});
const json = JSON.stringify(books);
document.getElementById("json").value = json;
}
fillBooksTable(books);
</script>
</body>
</html>

128
Лаб6/Сайт/script.js Normal file
View File

@@ -0,0 +1,128 @@
function generateRandomDate() {
const year = Math.floor(Math.random() * (2024 - 1900)) + 1900;
const month = Math.floor(Math.random() * 12) + 1;
const day = Math.floor(Math.random() * 28) + 1;
return new Date(year, month - 1, day);
}
function generateRandomAuthor() {
const names = [
'Александр',
'Екатерина',
'Дмитрий',
'Анна',
'Иван',
'Мария',
'Сергей',
'Ольга',
'Павел',
'Наталья',
];
const surnames = [
'Иванов',
'Петров',
'Смирнов',
'Кузнецов',
'Васильев',
'Соколов',
'Михайлов',
'Новиков',
'Федоров',
'Морозов',
];
const randomName = names[Math.floor(Math.random() * names.length)];
const randomSurname = surnames[Math.floor(Math.random() * surnames.length)];
return {
name: randomName,
surname: randomSurname,
};
}
function generateRandomBook() {
return {
title: 'Книга ' + Math.floor(Math.random() * 1000),
genre: [
'Фантастика',
'Роман',
'Детектив',
'Фэнтези',
'Приключения',
'Исторический роман',
'Триллер',
'Поэзия',
'Научно-популярная литература',
'Юмористическая проза',
][Math.floor(Math.random() * 6)],
publishDate: generateRandomDate(),
author: generateRandomAuthor(),
pageCount: Math.floor(Math.random() * 500) + 100,
};
}
function createBooksArray(N) {
const books = [];
for (let i = 0; i < N; i++) {
books.push(generateRandomBook());
}
return books;
}
function findBooksByAuthor(books, authorLastName) {
const filteredBooks = books.filter((book) => {
return book.author.surname === authorLastName;
});
return filteredBooks;
}
function findBooksByGenre(books, genre) {
const filteredBooks = books.filter((book) => book.genre === genre);
return filteredBooks;
}
function findBooksByPublishYearRange(books, startYear, endYear) {
const filteredBooks = books.filter((book) => {
const publishYear = book.publishDate.getFullYear();
return publishYear >= startYear && publishYear <= endYear;
});
return filteredBooks;
}
function removeBooksPageCount(books, minPageCount) {
for (let i = 0; i < books.length; i++) {
if (books[i].pageCount < minPageCount) {
delete books[i].pageCount;
}
}
return books;
}
function addAgeInfoToBooks(books) {
const currentDate = new Date();
books.forEach((book) => {
const yearsSincePublication =
currentDate.getFullYear() - book.publishDate.getFullYear();
book.age = yearsSincePublication;
});
return books;
}
// const booksArray = createBooksArray(10);
// console.log('Initial array of books:');
// displayBooks(booksArray);
// findBooksByAuthor(booksArray, 'Smith');
// findBooksByGenre(booksArray, 'Fantasy');
// findBooksByPublishYearRange(booksArray, 2000, 2010);
// booksArray = removeBooksByPageCount(booksArray, 200);
// console.log('Array after removing books by page count:');
// displayBooks(booksArray);
// booksArray = addAgeInfoToBooks(booksArray);
// console.log('Array after adding age info:');
// displayBooks(booksArray);

Binary file not shown.

View File

@@ -0,0 +1,90 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Лабораторная работа No7</title>
</head>
<body>
<div>
<label for="xMin">X min: </label>
<input type="number" id="xMin" value="5">
<label for="xMax">X max: </label>
<input type="number" id="xMax" value="10">
<label for="h">Шаг: </label>
<input type="number" id="h" value="0.1">
<br><br>
<label for="fn">Функция: </label>
<select id="fn">
<option value="f_1">f_1</option>
<option value="f_2">f_2</option>
<option value="f_3">f_3</option>
</select>
<br><br>
<h3>Характеристики</h3>
<label for="findMin">Найти минимум</label>
<input type="checkbox" id="findMin">
<label for="countPositive">Подсчитать количество положительных элементов</label>
<input type="checkbox" id="countPositive">
<label for="isMonotonous">Проверить монотонность</label>
<input type="checkbox" id="isMonotonous">
<br><br>
<h3>Варианты функции</h3>
<label for="memoization">Мемоизация</label>
<input type="checkbox" id="memoization">
<label for="debug">Отладка</label>
<input type="checkbox" id="debug">
<label for="countCalls">Подсчет количества вызовов</label>
<input type="checkbox" id="countCalls">
<br><br>
<button onclick="run()">Выполнить</button>
</div>
<script src="script.js"></script>
<script>
function run() {
const xMin = document.getElementById('xMin').value;
const xMax = document.getElementById('xMax').value;
const h = document.getElementById('h').value;
const fn = document.getElementById('fn').value;
const isFindMin = document.getElementById('findMin').checked;
const isCountPositive = document.getElementById('countPositive').checked;
const isIsMonotonous = document.getElementById('isMonotonous').checked;
const isMemoization = document.getElementById('memoization').checked;
const isDebug = document.getElementById('debug').checked;
const isCountCalls = document.getElementById('countCalls').checked;
func = f_1;
if (fn == 'f_1')
func = f_1;
else if (fn == 'f_2')
func = f_2;
else if (fn == 'f_3')
func = f_3;
if (isMemoization)
func = memoize(func);
if (isDebug)
func = debug(func);
if (isCountCalls)
func = countCalls(func);
characteristics = [];
if (isFindMin)
characteristics.push(findMin);
if (isCountPositive)
characteristics.push(countPositive);
if (isIsMonotonous)
characteristics.push(isMonotonous);
const chars = calculateCharacteristics(func, Number(xMin), Number(xMax), Number(h), characteristics);
console.log(chars);
}
</script>
</body>
</html>

108
Лаб7/Сайт/script.js Normal file
View File

@@ -0,0 +1,108 @@
function f_1(x) {
return x + (x * x * x - Math.log(x)) / Math.sqrt(x + 5);
}
function f_2(x) {
return Math.pow(Math.sin(x), 2) - Math.abs(5 - Math.log10(x - 4));
}
function f_3(x) {
return Math.exp(x - 2) + (x * x * x + 2 * x) / 4;
}
function memoize(fn) {
const cache = new Map();
const memoized = function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log('Using cache');
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
memoized.countMemoized = function () {
return cache.size;
};
return memoized;
}
function debug(fn) {
return function (...args) {
const result = fn(...args);
console.log(
`Called ${
fn.name
} at ${new Date().toISOString()} with args ${args}. Result: ${result}`
);
return result;
};
}
function countCalls(fn) {
let count = 0;
const wrapped = function (...args) {
count++;
return fn(...args);
};
wrapped.countCalls = function () {
return count;
};
wrapped.resetCount = function () {
count = 0;
};
return wrapped;
}
function findMin(fn, start, end, h) {
let min = Infinity;
for (let x = start; x < end; x += h) {
const curr = fn(x);
if (curr < min) {
min = curr;
}
}
return min;
}
function countPositive(fn, start, end, h) {
let count = 0;
for (let x = start; x < end; x += h) {
if (fn(x) > 0) {
count++;
}
}
return count;
}
function isMonotonous(fn, start, end, h) {
let prev = fn(start);
for (let x = start; x < end; x += h) {
const curr = fn(x);
if (curr < prev) {
return false;
}
prev = curr;
}
return true;
}
function calculateCharacteristics(fn, start, end, h, characteristics) {
chars = [];
for (let i = 0; i < characteristics.length; i++) {
chars.push(characteristics[i](fn, start, end, h));
}
return chars;
}