fix: correct shebang and executable permissions

- Add +x to Python scripts with shebangs (3 files)
- Remove -x from non-script files like .cpp, .txt, makefile (23 files)
- Move shebang to first line in C/imageViewer/lint.sh
This commit is contained in:
Krzysztof kuhy Rudnicki 2025-11-30 13:42:16 +01:00
parent 74f2e24eab
commit 5966821bad
53 changed files with 2484 additions and 278 deletions

View File

@ -1,168 +1,168 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define LINE_LENGTH 100
void C()
{
printf("\nCheck\n");
return;
}
void printAcceleration(int acceleration)
{
printf("The value of acceleration is: %d\n", acceleration);
system("PAUSE");
return;
}
void pauseSystem() { system("PAUSE"); }
void clearScreen()
{
system("CLS");
return;
}
void pauseForASecond()
{
Sleep(1000);
return;
}
void pauseForGivenTime(float given_time)
{
Sleep(fabs(given_time * 1000));
return;
}
float calculateVelocity(float starting_velocity, unsigned int physics_time, int *acceleration)
{
return (*acceleration) * physics_time + starting_velocity;
}
int calculateDisplacement(float starting_velocity, int *acceleration, unsigned int physics_time)
{
return starting_velocity * physics_time + ((1 / 2) * (*acceleration) * (physics_time ^ 2));
}
void printXPosition(int position)
{
printf("\nx position is: %d\n", position);
return;
}
void printClock(unsigned int *time)
{
printf("%d seconds passed\n", *time);
return;
}
float calculateStopTime(float velocity) { return 1 / velocity; }
void printLine(int position)
{
clearScreen();
for (int i = -(LINE_LENGTH / 2); i < LINE_LENGTH / 2; i++)
{
if (i == position)
printf("x");
else
printf("-");
}
return;
}
void printVelocity(float velocity)
{
printf("Velocity is: %f\n", velocity);
return;
}
int calculateTimePassed(float velocity)
{
if (velocity >= 1 || velocity <= -1)
return 1;
else
{
printf("Time passed is: %f\n", fabs(1 / velocity));
return fabs(1 / velocity);
}
}
void printAllInfo(int position, unsigned int *time, float *velocity)
{
pauseForGivenTime(calculateStopTime(*velocity));
printLine(position);
printXPosition(position);
*time += calculateTimePassed(*velocity);
printClock(time);
printVelocity(*velocity);
// pauseForASecond();
return;
}
float chooseVelocity()
{
float velocity;
printf("Write velocity of the object in m / s: ");
scanf("%f", &velocity);
return velocity;
}
int chooseAcceleration()
{
int acceleration;
printf("Choose acceleration of the object in m / (s ^ 2):");
scanf("%d", &acceleration);
return acceleration;
}
int outOfLine(int position)
{
if ((position < LINE_LENGTH / 2) && (position > -1 * (LINE_LENGTH / 2)))
{
return 0;
}
else
return 1;
}
void moveUntillOutOfLine(int position, unsigned int *time)
{
while (!outOfLine(position))
{
float velocity = chooseVelocity();
float *Pvelocity = &velocity;
position += calculateDisplacement(velocity, 0, 1);
printAllInfo(position, time, Pvelocity);
}
return;
}
void moveUntillOutOfVelocity(int position, int *acceleration, unsigned int *time)
{
float velocity = 0;
float *Pvelocity = &velocity;
while (!outOfLine(position))
{
position += calculateDisplacement(velocity, acceleration, 1);
printXPosition(position);
pauseSystem();
velocity = calculateVelocity(velocity, 1, acceleration);
printAllInfo(position, time, Pvelocity);
}
return;
}
int main()
{
int position = 0, acceleration = -1;
int *Pacceleration = &acceleration;
unsigned int time = 0;
unsigned int *Ptime = &time;
moveUntillOutOfLine(position, Ptime);
// moveUntillOutOfVelocity(position, Pacceleration, Ptime);
return 0;
}
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define LINE_LENGTH 100
void C()
{
printf("\nCheck\n");
return;
}
void printAcceleration(int acceleration)
{
printf("The value of acceleration is: %d\n", acceleration);
system("PAUSE");
return;
}
void pauseSystem() { system("PAUSE"); }
void clearScreen()
{
system("CLS");
return;
}
void pauseForASecond()
{
Sleep(1000);
return;
}
void pauseForGivenTime(float given_time)
{
Sleep(fabs(given_time * 1000));
return;
}
float calculateVelocity(float starting_velocity, unsigned int physics_time, int *acceleration)
{
return (*acceleration) * physics_time + starting_velocity;
}
int calculateDisplacement(float starting_velocity, int *acceleration, unsigned int physics_time)
{
return starting_velocity * physics_time + ((1 / 2) * (*acceleration) * (physics_time ^ 2));
}
void printXPosition(int position)
{
printf("\nx position is: %d\n", position);
return;
}
void printClock(unsigned int *time)
{
printf("%d seconds passed\n", *time);
return;
}
float calculateStopTime(float velocity) { return 1 / velocity; }
void printLine(int position)
{
clearScreen();
for (int i = -(LINE_LENGTH / 2); i < LINE_LENGTH / 2; i++)
{
if (i == position)
printf("x");
else
printf("-");
}
return;
}
void printVelocity(float velocity)
{
printf("Velocity is: %f\n", velocity);
return;
}
int calculateTimePassed(float velocity)
{
if (velocity >= 1 || velocity <= -1)
return 1;
else
{
printf("Time passed is: %f\n", fabs(1 / velocity));
return fabs(1 / velocity);
}
}
void printAllInfo(int position, unsigned int *time, float *velocity)
{
pauseForGivenTime(calculateStopTime(*velocity));
printLine(position);
printXPosition(position);
*time += calculateTimePassed(*velocity);
printClock(time);
printVelocity(*velocity);
// pauseForASecond();
return;
}
float chooseVelocity()
{
float velocity;
printf("Write velocity of the object in m / s: ");
scanf("%f", &velocity);
return velocity;
}
int chooseAcceleration()
{
int acceleration;
printf("Choose acceleration of the object in m / (s ^ 2):");
scanf("%d", &acceleration);
return acceleration;
}
int outOfLine(int position)
{
if ((position < LINE_LENGTH / 2) && (position > -1 * (LINE_LENGTH / 2)))
{
return 0;
}
else
return 1;
}
void moveUntillOutOfLine(int position, unsigned int *time)
{
while (!outOfLine(position))
{
float velocity = chooseVelocity();
float *Pvelocity = &velocity;
position += calculateDisplacement(velocity, 0, 1);
printAllInfo(position, time, Pvelocity);
}
return;
}
void moveUntillOutOfVelocity(int position, int *acceleration, unsigned int *time)
{
float velocity = 0;
float *Pvelocity = &velocity;
while (!outOfLine(position))
{
position += calculateDisplacement(velocity, acceleration, 1);
printXPosition(position);
pauseSystem();
velocity = calculateVelocity(velocity, 1, acceleration);
printAllInfo(position, time, Pvelocity);
}
return;
}
int main()
{
int position = 0, acceleration = -1;
int *Pacceleration = &acceleration;
unsigned int time = 0;
unsigned int *Ptime = &time;
moveUntillOutOfLine(position, Ptime);
// moveUntillOutOfVelocity(position, Pacceleration, Ptime);
return 0;
}

View File

@ -1,6 +1,7 @@
# Simple OpenGL FPS (C + FreeGLUT)
A tiny first-person demo using legacy OpenGL (compat) and FreeGLUT:
- Move with WASD, hold Tab or Q to sprint
- Aim with mouse (captured by default). Press M to toggle capture
- Shoot with Left Mouse or Space. Hit the red cube to score; it respawns
@ -24,9 +25,11 @@ make -C C/fps run
```
If your distro uses different package names, install the equivalents of:
- libgl1, libglu1, freeglut (dev headers)
## Notes
- This uses old-school fixed-function OpenGL for simplicity and broad compatibility.
- Mouse is confined via glutWarpPointer; press M if you need to release it.
- SDL2 is used only for simple procedurally generated sound effects (shoot, hit, game over).

View File

@ -11,21 +11,21 @@
"C_Cpp.default.compilerPath": "/usr/bin/gcc",
"C_Cpp.clang_format_style": "file",
"C_Cpp.clang_format_fallbackStyle": "LLVM",
"files.associations": {
"*.h": "c",
"*.c": "c"
},
"editor.formatOnSave": true,
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.rulers": [100],
"clang-tidy.executable": "clang-tidy",
"clang-tidy.checks": [
"clang-diagnostic-*",
"clang-analyzer-*",
"clang-analyzer-*",
"bugprone-*",
"cert-*",
"misc-*",
@ -33,7 +33,7 @@
"portability-*",
"readability-*"
],
"cppcheck.enable": true,
"cppcheck.standard": ["c99"],
"cppcheck.suppress": [

View File

@ -7,7 +7,7 @@ The imageviewer project uses secure coding practices with proper bounds checking
### Why These Warnings Appear
The static analyzer flags standard C library functions like:
- `memcpy()` - suggests using `memcpy_s()`
- `memcpy()` - suggests using `memcpy_s()`
- `snprintf()` - suggests using `snprintf_s()`
- `strncpy()` - suggests using `strncpy_s()`

View File

@ -112,16 +112,16 @@ install_dependencies() {
build_imageviewer() {
print_step "Building imageviewer..."
# Check if we're in the right directory
if [[ ! -f "main.c" ]] || [[ ! -f "Makefile" ]]; then
print_error "main.c or Makefile not found. Please run this script from the imageViewer directory."
exit 1
fi
# Clean any previous builds
make clean 2>/dev/null || true
# Build the project
if make; then
print_success "Build completed successfully"
@ -129,35 +129,35 @@ build_imageviewer() {
print_error "Build failed"
exit 1
fi
# Verify the binary was created
if [[ ! -f "imageviewer" ]]; then
print_error "imageviewer binary not found after build"
exit 1
fi
print_success "imageviewer binary created"
}
install_binary() {
print_step "Installing imageviewer to ${INSTALL_DIR}..."
# Create install directory if it doesn't exist
sudo mkdir -p "${INSTALL_DIR}"
# Copy the binary
sudo cp imageviewer "${INSTALL_DIR}/"
sudo chmod +x "${INSTALL_DIR}/imageviewer"
print_success "imageviewer installed to ${INSTALL_DIR}/imageviewer"
}
create_desktop_entry() {
print_step "Creating desktop entry..."
# Create applications directory if it doesn't exist
sudo mkdir -p "${DESKTOP_FILE_DIR}"
# Create desktop file
sudo tee "${DESKTOP_FILE_DIR}/imageviewer.desktop" > /dev/null << EOF
[Desktop Entry]
@ -179,10 +179,10 @@ EOF
create_simple_icon() {
print_step "Creating application icon..."
# Create icon directory if it doesn't exist
sudo mkdir -p "${ICON_DIR}"
# Create a simple text-based icon (SVG)
sudo tee "${ICON_DIR}/imageviewer.svg" > /dev/null << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
@ -201,7 +201,7 @@ EOF
update_desktop_database() {
print_step "Updating desktop database..."
if command -v update-desktop-database &> /dev/null; then
sudo update-desktop-database "${DESKTOP_FILE_DIR}" 2>/dev/null || true
print_success "Desktop database updated"
@ -212,11 +212,11 @@ update_desktop_database() {
set_default_image_viewer() {
print_step "Setting imageviewer as default image viewer..."
# List of MIME types for images
local mime_types=(
"image/jpeg"
"image/jpg"
"image/jpg"
"image/png"
"image/bmp"
"image/gif"
@ -224,34 +224,34 @@ set_default_image_viewer() {
"image/tif"
"image/webp"
)
# Set default application for each MIME type
for mime_type in "${mime_types[@]}"; do
if command -v xdg-mime &> /dev/null; then
xdg-mime default imageviewer.desktop "$mime_type" 2>/dev/null || true
fi
done
# Also update MIME database if available
if command -v update-mime-database &> /dev/null; then
sudo update-mime-database /usr/share/mime 2>/dev/null || true
fi
print_success "imageviewer set as default image viewer"
}
test_installation() {
print_step "Testing installation..."
# Check if binary is in PATH
if command -v imageviewer &> /dev/null; then
print_success "imageviewer is available in PATH"
# Show version/help
echo -e "${BLUE}Running imageviewer --help equivalent:${NC}"
echo "Usage: imageviewer <image_file_or_directory>"
echo "Supported formats: JPG, JPEG, PNG, BMP, GIF, TIF"
# Test default application association
if command -v xdg-mime &> /dev/null; then
local default_app=$(xdg-mime query default image/jpeg 2>/dev/null)
@ -261,7 +261,7 @@ test_installation() {
print_warning "Default image viewer association may not have been set correctly"
fi
fi
else
print_error "imageviewer not found in PATH. Installation may have failed."
exit 1
@ -311,10 +311,10 @@ main() {
echo -e "${BLUE}ImageViewer Installation Script for Arch Linux${NC}"
echo "=============================================="
echo
check_arch
check_permissions
# Show what the script will do
echo -e "${YELLOW}This script will:${NC}"
echo " 1. Install SDL2 dependencies via pacman"
@ -323,7 +323,7 @@ main() {
echo " 4. Create a desktop entry"
echo " 5. Set imageviewer as default image viewer"
echo
install_dependencies
build_imageviewer
install_binary

View File

@ -1,5 +1,5 @@
# Lint script for imageViewer project
#!/bin/bash
# Lint script for imageViewer project
set -e
@ -29,25 +29,25 @@ print_error() {
# Check if required tools are installed
check_tools() {
print_step "Checking required tools..."
local missing_tools=()
if ! command -v clang-tidy &> /dev/null; then
missing_tools+=("clang-tidy")
fi
if ! command -v cppcheck &> /dev/null; then
missing_tools+=("cppcheck")
fi
if ! command -v clang-format &> /dev/null; then
missing_tools+=("clang-format")
fi
if [ ${#missing_tools[@]} -ne 0 ]; then
print_error "Missing required tools: ${missing_tools[*]}"
print_step "Installing missing tools..."
# Check if we're on Arch Linux
if command -v pacman &> /dev/null; then
sudo pacman -S --needed clang cppcheck
@ -60,14 +60,14 @@ check_tools() {
exit 1
fi
fi
print_success "All required tools are available"
}
# Run clang-tidy
run_clang_tidy() {
print_step "Running clang-tidy analysis..."
if [ -f ".clang-tidy" ]; then
clang-tidy main.c -- -I/usr/include/SDL2 -D_REENTRANT 2>/dev/null || {
print_warning "clang-tidy found issues (see output above)"
@ -78,26 +78,26 @@ run_clang_tidy() {
print_warning "clang-tidy found issues (see output above)"
}
fi
print_success "clang-tidy analysis completed"
}
# Run cppcheck
run_cppcheck() {
print_step "Running cppcheck analysis..."
cppcheck --enable=all --check-level=exhaustive --suppress=missingIncludeSystem \
--quiet --std=c23 main.c || {
print_warning "cppcheck found issues (see output above)"
}
print_success "cppcheck analysis completed"
}
# Check code formatting
check_formatting() {
print_step "Checking code formatting..."
if [ -f ".clang-format" ]; then
if clang-format --dry-run --Werror main.c 2>/dev/null; then
print_success "Code formatting is correct"
@ -113,7 +113,7 @@ check_formatting() {
# Run basic compile check
compile_check() {
print_step "Running compile check..."
# Try to compile with extra warnings
if gcc -Wall -Wextra -Wpedantic -std=c99 -O2 \
$(pkg-config --cflags sdl2 2>/dev/null || echo "-I/usr/include/SDL2") \
@ -132,27 +132,27 @@ compile_check() {
# Check for common C issues
check_common_issues() {
print_step "Checking for common C issues..."
local issues=0
# Check for TODO/FIXME comments
if grep -n "TODO\|FIXME\|XXX\|HACK" main.c 2>/dev/null; then
print_warning "Found TODO/FIXME comments"
issues=$((issues + 1))
fi
# Check for potential buffer overflows
if grep -n "strcpy\|strcat\|sprintf\|gets" main.c 2>/dev/null; then
print_warning "Found potentially unsafe string functions"
issues=$((issues + 1))
fi
# Check for magic numbers (basic check)
if grep -E "\b[0-9]{3,}\b" main.c | grep -v "printf\|#define" 2>/dev/null; then
print_warning "Found potential magic numbers"
issues=$((issues + 1))
fi
if [ $issues -eq 0 ]; then
print_success "No common issues found"
fi
@ -163,31 +163,31 @@ main() {
echo -e "${BLUE}C Language Linter for imageViewer Project${NC}"
echo "=========================================="
echo
# Check if we're in the right directory
if [ ! -f "main.c" ]; then
print_error "main.c not found. Please run this script from the imageViewer directory."
exit 1
fi
check_tools
echo
compile_check
echo
run_clang_tidy
echo
run_cppcheck
echo
check_formatting
echo
check_common_issues
echo
print_success "Linting completed!"
echo
echo -e "${BLUE}Available commands:${NC}"

View File

@ -1415,4 +1415,4 @@ static int save_processed_image(const ImageViewer *viewer) {
printf("Saved %s image: %s\n", any_trim ? "trimmed" : "rotated", out_path);
}
return 1;
}
}

View File

@ -34,7 +34,7 @@ print_error() {
remove_files() {
print_step "Removing imageviewer files..."
# Remove binary
if [[ -f "${INSTALL_DIR}/imageviewer" ]]; then
sudo rm "${INSTALL_DIR}/imageviewer"
@ -42,7 +42,7 @@ remove_files() {
else
print_warning "Binary not found at ${INSTALL_DIR}/imageviewer"
fi
# Remove desktop entry
if [[ -f "${DESKTOP_FILE_DIR}/imageviewer.desktop" ]]; then
sudo rm "${DESKTOP_FILE_DIR}/imageviewer.desktop"
@ -50,7 +50,7 @@ remove_files() {
else
print_warning "Desktop entry not found"
fi
# Remove icon
if [[ -f "${ICON_DIR}/imageviewer.svg" ]]; then
sudo rm "${ICON_DIR}/imageviewer.svg"
@ -62,11 +62,11 @@ remove_files() {
reset_default_associations() {
print_step "Resetting default image viewer associations..."
# List of MIME types for images
local mime_types=(
"image/jpeg"
"image/jpg"
"image/jpg"
"image/png"
"image/bmp"
"image/gif"
@ -74,7 +74,7 @@ reset_default_associations() {
"image/tif"
"image/webp"
)
# Reset default application for each MIME type
for mime_type in "${mime_types[@]}"; do
if command -v xdg-mime &> /dev/null; then
@ -89,13 +89,13 @@ reset_default_associations() {
fi
fi
done
print_success "Default image viewer associations reset"
}
update_desktop_database() {
print_step "Updating desktop database..."
if command -v update-desktop-database &> /dev/null; then
sudo update-desktop-database "${DESKTOP_FILE_DIR}" 2>/dev/null || true
print_success "Desktop database updated"
@ -108,7 +108,7 @@ main() {
echo -e "${BLUE}ImageViewer Uninstallation Script${NC}"
echo "================================="
echo
# Show what will be removed
echo -e "${YELLOW}This script will remove:${NC}"
echo " - ${INSTALL_DIR}/imageviewer"
@ -117,11 +117,11 @@ main() {
echo
echo -e "${YELLOW}Note: Dependencies (SDL2 libraries) will NOT be removed.${NC}"
echo
remove_files
reset_default_associations
update_desktop_database
echo
echo -e "${GREEN}ImageViewer has been successfully uninstalled!${NC}"
echo

View File

@ -747,4 +747,4 @@ int main(int argc, char **argv)
printf("}\n");
free(arr);
return 0;
}
}

View File

@ -69,4 +69,4 @@ int in_check(const Position *pos, Color side);
int gen_moves(const Position *pos, Move *moves, int max_moves, int captures_only);
int gen_moves_pseudo(const Position *pos, Move *moves, int max_moves, int captures_only);
#endif // MOVEGEN_H
#endif // MOVEGEN_H

View File

@ -21,4 +21,4 @@ int evaluate(const Position *pos);
// Negamax alpha-beta returning score in centipawns from side-to-move perspective.
int alphabeta(Position pos, int depth, int alpha, int beta, PrincipalVariation *pv);
#endif // SEARCH_H
#endif // SEARCH_H

View File

@ -1,12 +1,12 @@
#include <stdio.h>
const int NUMBER_FOR_POLISH_SMALL_L = 136;
int main(void)
{
for (char i = 'a'; i < 'z' + 1; ++i)
{
printf("%ca%cka\n", i, NUMBER_FOR_POLISH_SMALL_L);
}
return 0;
}
#include <stdio.h>
const int NUMBER_FOR_POLISH_SMALL_L = 136;
int main(void)
{
for (char i = 'a'; i < 'z' + 1; ++i)
{
printf("%ca%cka\n", i, NUMBER_FOR_POLISH_SMALL_L);
}
return 0;
}

4
C/misc/randomJPG/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.jpeg
*.jpg
generated_images*/*
generate_images

View File

@ -0,0 +1,6 @@
Did you ever need to generate random jpg images with huge file size? Now you can! \\
Compilation: Install libjpeg-dev \\
sudo apt-get install libjpeg-dev \\
Run make \\
make \\
Run ./generate_images

1
C/misc/split/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
split

View File

@ -18,9 +18,11 @@ Run:
```
Tips:
- ESC clears selection.
- Press `m` to cycle to a stored mistake position and practice the best move there.
- If you play Black, the board flips so Black is at the bottom.
Notes:
- Rendering avoids TTF dependency; pieces are clear, high-contrast geometric glyphs.

65
C/scrapeWebsite/.gitignore vendored Normal file
View File

@ -0,0 +1,65 @@
# JPEG
*.jpg
*.jpeg
*.jpe
*.jif
*.jfif
*.jfi
# JPEG 2000
*.jp2
*.j2k
*.jpf
*.jpx
*.jpm
*.mj2
# JPEG XR
*.jxr
*.hdp
*.wdp
# Graphics Interchange Format
*.gif
# RAW
*.raw
# Web P
*.webp
# Portable Network Graphics
*.png
# Animated Portable Network Graphics
*.apng
# Multiple-image Network Graphics
*.mng
# Tagged Image File Format
*.tiff
*.tif
# Scalable Vector Graphics
*.svg
*.svgz
# Portable Document Format
*.pdf
# X BitMap
*.xbm
# BMP
*.bmp
*.dib
# ICO
*.ico
# 3D Images
*.3dm
*.max
scrape

View File

@ -1,10 +1,10 @@
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
printf("Henlo\n");
sleep(20);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
printf("Henlo\n");
sleep(20);
return 0;
}

5
CPP/SFMLEngine/readme.md Normal file
View File

@ -0,0 +1,5 @@
# Textures and Audio used:
## Space Game Starter Set by [hc](https://opengameart.org/users/hc) - https://opengameart.org/content/space-game-starter-set
## 100 seamless textures by [Mitch Featherston](http://pdtextures.blogspot.com/) (Submitted by [Clint Bellanger](https://opengameart.org/users/clint-bellanger) - https://opengameart.org/content/100-seamless-textures

View File

@ -0,0 +1,25 @@
#include <math.h>
#include <iostream>
#include <iomanip>
const unsigned long long int ITERATIONS = 10000;
long double getPi()
{
long double pi = 4;
bool negative = 1;
for(unsigned int i = 3; i < ITERATIONS; i += 2)
{
if(negative) pi -= 4.0 / i;
else pi += 4.0 / i;
negative = !negative;
}
std::cout << std::setprecision(2000) << pi << std::endl;
return pi;
}
int main()
{
getPi();
return 0;
}

View File

@ -0,0 +1,410 @@
#include <iostream>
#include <vector>
const std::vector <std::string> ATUTY = {"BA", "Trefl", "Karo", "Kier", "Pik"};
const bool A_ID = 0;
const bool B_ID = 1;
const std::vector <std::string> GRACZE = {};
const std::vector <std::string> PO_PARTII {"Nikt", GRACZE[A_ID], GRACZE[B_ID], "Obaj Gracze"};
const int DOMYSLNE_LEWY = 6;
const int BEZ_ATUTU_ID = 1;
const int TREFL_ID = 2;
const int KARO_ID = 3;
const int KIER_ID = 4;
const int PIK_ID = 5;
const int SZLEMIK = 6;
const int SZLEM = 7;
const int CYKL_PO_PARTII = 4;
const int MAKSYMALNY_LEW = 7;
const int MINIMALNY_LEW = 1;
const int ILOSC_LEW = 13;
void print(const std::string s)
{
std::cout << s << std::endl;
}
void tabela(std::vector <int> punktyA, std::vector <int> punktyB)
{
std::cout << "Numer Gry" << " Po Partii" << " " << GRACZE[A_ID] << " " << GRACZE[B_ID] << std::endl;
for(int i = 0; i < punktyA.size(); i++)
{
std::cout << i + 1 << " " << PO_PARTII[i % CYKL_PO_PARTII] << " " << punktyA[i] << " " << punktyB[i] << std::endl;
}
}
void lwyAtut(int lwy, int atut)
{
if(lwy == SZLEMIK)
{
print("Wybrano szlemik!");
return;
}
if(lwy == SZLEM)
{
print("Wybrano szlema!");
return;
}
std::cout << "Wybrano kontrakt: " << lwy << " " << ATUTY[atut - 1] << std::endl;
}
int zagraneLwy()
{
int lwy;
bool flagaLwy;
do
{
flagaLwy = 0;
print("Ile lew?");
char lwyC;
std::cin >> lwyC;
lwy = lwyC - '0';
if(lwy < MINIMALNY_LEW)
{
print("Podales za malo lew!");
flagaLwy = 1;
}
if(lwy > MAKSYMALNY_LEW)
{
print("Podales za duzo lew!");
flagaLwy = 1;
}
}while(flagaLwy);
return lwy;
}
int zagranyAtut(int lwy)
{
int atut;
bool flagaAtut;
if(lwy > 6) return 1;
do
{
flagaAtut = 0;
print("Jaki atut?");
print("1 - BA");
print("2 - Trefl");
print("3 - Karo");
print("4 - Kier");
print("5 - Pik");
char atutC;
std::cin >> atutC;
atut = atutC - '0';
if(atut < 1 || atut > 5)
{
print("Wybrales zla liczbe!");
flagaAtut = 1;
}
}while(flagaAtut);
return atut;
}
bool zagranaKontra()
{
char kontraC = '0';
print("Czy zostala zagrana kontra?");
print("1 - TAK");
print("0 - NIE");
std::cin >> kontraC;
bool kontraBool = kontraC - '0';
return kontraBool;
}
bool zagranaRekontra()
{
char rekontraC = '0';
print("Czy zostala zagrana rekontra?");
print("1 - TAK");
print("0 - NIE");
std::cin >> rekontraC;
bool rekontraBool = rekontraC - '0';
return rekontraBool;
}
void stanGry(int lwy, int atut, bool kontraBool, bool rekontraBool, int ktoraGra, int ktoKontrakt)
{
std::cout << "Kontrakt Wygrali: " << GRACZE[ktoKontrakt] << std::endl;
lwyAtut(lwy, atut);
if(kontraBool)
{
if(rekontraBool) print("Zostala zagrana REkontra!");
else print("Zostala zagrana Kontra!");
}
std::cout << "Po partii sa: " << PO_PARTII[ktoraGra % 4] << std::endl;
}
int ktoKontrakt()
{
char ktoKontraktC;
print("Kto wygral Kontrakt?");
std::cout << "1. " << GRACZE[A_ID] << std::endl;
std::cout << "2. " << GRACZE[B_ID] << std::endl;
std::cin >> ktoKontraktC;
int ktoKontraktI = ktoKontraktC - '1';
std::cout << "ktoKontraktI " << ktoKontraktI;
return ktoKontraktI;
}
int ileWpadek()
{
std::string ileWpadekS;
print("ile lew wygrali obroncy?");
std::cin >> ileWpadekS;
int ileWpadek = stoi(ileWpadekS);
return ileWpadek;
}
void punkty(std::vector <int> &punktyA, std::vector <int> &punktyB, int lwy, int atut, bool kontraBool, bool rekontraBool,
int ktoraGra, int ktoKontraktI, bool rozgrywajacyWygral, int wpadki)
{
int sumaPunktow = 0;
if(rozgrywajacyWygral)
{
int zdobyteLewy = ILOSC_LEW - wpadki - DOMYSLNE_LEWY;
int nadrobki = zdobyteLewy - lwy;
int punktyZaLew;
std::cout << "wartosc kontraBool: " << kontraBool << "; wartosc rekontraBool: " << rekontraBool << std::endl;
// Lewy Deklarowane
if(atut == TREFL_ID || atut == KARO_ID)
{
print("kontrakt TREFL lub KARO kazda karta kontraktowa za 20");
punktyZaLew = 20;
if(kontraBool)
{
print("kontra TREFL lub KARO, kazda karta kontraktowa za 40");
punktyZaLew = 40;
}
if(rekontraBool)
{
print("rekontra TREFL lub KARO, kazda karta kontraktowa za 80");
punktyZaLew = 80;
}
std::cout << "Ilosc lew w kontrakcie: " << lwy << " do punktow dodaje sie " << lwy * punktyZaLew << std::endl;
sumaPunktow += (lwy * punktyZaLew);
}
if(atut == KIER_ID || atut == PIK_ID)
{
print("kontrakt KIER lub PIK, kazda kontraktowa 30");
punktyZaLew = 30;
if(kontraBool)
{
print("kontra KIER lub PIK, kazda kontraktowa za 60");
punktyZaLew = 60;
}
if(rekontraBool)
{
print("rekontra KIER lub PIK, kazda kontraktowa za 120");
punktyZaLew = 120;
}
std::cout << "Ilosc lew w kontrakcie: " << lwy << " do punktow dodaje sie " << lwy * punktyZaLew << std::endl;
sumaPunktow += (lwy * punktyZaLew);
}
if(atut == BEZ_ATUTU_ID)
{
punktyZaLew = 30;
print("kontrakt BEZ_ATUTU, pierwsza lewa za 40, kazda nastepna za 30");
sumaPunktow = 40;
if(kontraBool)
{
print("kontrakt BEZ_ATUTU, pierwsza lewa za 80, kazda nastepna za 60");
sumaPunktow = 80;
punktyZaLew = 60;
}
if(rekontraBool)
{
print("kontrakt BEZ_ATUTU, pierwsza lewa za 160, kazda nastepna za 120");
sumaPunktow = 160;
punktyZaLew = 120;
}
sumaPunktow += ( (lwy - 1) * punktyZaLew);
}
bool czyRozgrywajacyPoPartii = ( ( (ktoraGra % CYKL_PO_PARTII) - 1) == ktoKontraktI || ktoraGra % CYKL_PO_PARTII == 3);
if(lwy == SZLEMIK)
{
if(czyRozgrywajacyPoPartii) sumaPunktow += 750;
else sumaPunktow += 500;
}
if(lwy == SZLEM)
{
if(czyRozgrywajacyPoPartii) sumaPunktow += 1500;
else sumaPunktow += 1000;
}
bool dograna = (sumaPunktow >= 100);
if(dograna)
{
if(czyRozgrywajacyPoPartii) sumaPunktow += 500;
else sumaPunktow += 300;
}else sumaPunktow += 50;
// Nadrobki
if(!kontraBool && !rekontraBool)
{
int punktyZaNadrobki = punktyZaLew;
sumaPunktow += nadrobki * punktyZaNadrobki;
}
if(kontraBool && !rekontraBool)
{
int punktyZaNadrobki = 100;
if(czyRozgrywajacyPoPartii) punktyZaNadrobki = 200;
sumaPunktow += nadrobki * punktyZaNadrobki;
}
if(kontraBool && rekontraBool)
{
int punktyZaNadrobki = 200;
if(czyRozgrywajacyPoPartii) punktyZaNadrobki = 400;
sumaPunktow += nadrobki * punktyZaNadrobki;
}
if(kontraBool && !rekontraBool) sumaPunktow += 50;
if(kontraBool && rekontraBool) sumaPunktow += 100;
std::cout << "Rozgrywajacy zdobyl: " << sumaPunktow << std::endl;
if(ktoKontraktI == A_ID)
{
punktyA.push_back(sumaPunktow);
punktyB.push_back(0);
}
else
{
punktyB.push_back(sumaPunktow);
punktyA.push_back(0);
}
return;
}else
{
int zebraneLewy = ILOSC_LEW - wpadki;
int lewyWpadkowe = (lwy + DOMYSLNE_LEWY) - zebraneLewy;
int sumaPunktow = 0;
bool broniacyPoPartii = ( ((ktoraGra % CYKL_PO_PARTII) - 1) == !ktoKontraktI || ktoraGra % CYKL_PO_PARTII == 3);
if(broniacyPoPartii)
{
if(!kontraBool && !rekontraBool)
{
sumaPunktow = 100;
for(int i = 1; i < lewyWpadkowe; i++)
{
if(i < 4) sumaPunktow += 100;
else sumaPunktow += 0;
}
}
if(kontraBool && !rekontraBool)
{
sumaPunktow = 200;
for(int i = 1; i < lewyWpadkowe; i++)
{
if(i < 4) sumaPunktow += 300;
else sumaPunktow += 0;
}
}
if(kontraBool && rekontraBool)
{
sumaPunktow = 400;
for(int i = 1; i < lewyWpadkowe; i++)
{
if(i < 4) sumaPunktow += 600;
else sumaPunktow += 0;
}
}
}else
{
if(!kontraBool && !rekontraBool)
{
sumaPunktow = 50;
for(int i = 1; i < lewyWpadkowe; i++)
{
if(i < 4) sumaPunktow += 50;
else sumaPunktow += 0;
}
}
if(kontraBool && !rekontraBool)
{
sumaPunktow = 100;
for(int i = 1; i < lewyWpadkowe; i++)
{
if(i < 4) sumaPunktow += 200;
else sumaPunktow += 100;
}
}
if(kontraBool && rekontraBool)
{
sumaPunktow = 200;
for(int i = 1; i < lewyWpadkowe; i++)
{
if(i < 4) sumaPunktow += 400;
else sumaPunktow += 200;
}
}
}
std::cout << "Broniacy zdobyli: " << sumaPunktow << std::endl;
if(ktoKontraktI == A_ID)
{
punktyB.push_back(sumaPunktow);
punktyA.push_back(0);
}
else
{
punktyA.push_back(sumaPunktow);
punktyB.push_back(0);
}
return;
}
}
bool gra()
{
bool koniecGry = 0;
std::vector <int> punktyA;
std::vector <int> punktyB;
do{
int ktoraGra = 0;
tabela(punktyA, punktyB);
int ktoKontraktI = ktoKontrakt();
int lwy = zagraneLwy();
int atut = zagranyAtut(lwy);
bool kontraBool = zagranaKontra();
bool rekontraBool = 0;
if(kontraBool) rekontraBool = zagranaRekontra();
stanGry(lwy, atut, kontraBool, rekontraBool, ktoraGra, ktoKontraktI);
int wpadki = ileWpadek();
int zebraneLewy = ILOSC_LEW - wpadki;
bool rozgrywajacyWygral = 1;
if( zebraneLewy >= lwy + DOMYSLNE_LEWY) rozgrywajacyWygral = 1;
else rozgrywajacyWygral = 0;
punkty(punktyA, punktyB, lwy, atut, kontraBool, rekontraBool, ktoraGra, ktoKontraktI, rozgrywajacyWygral, wpadki);
print("Czy koniec gry? 1 - TAK, 0 - NIE");
std::cin >> koniecGry;
}while(!koniecGry);
tabela(punktyA, punktyB);
return 0;
}
int main()
{
while(gra());
return 0;
}

View File

@ -0,0 +1,91 @@
#ifndef BASIC_CPP
#define BASIC_CPP
#include <string>
#include <vector>
#include <iostream>
#include <windows.h>
void print(const std::string s) { std::cout << s << std::endl; }
void printErrorStringContainsNotNumber(const std::string s)
{
std::cout << "string: \"" << s
<< "\" contains character different than number " << std::endl;
}
void printNumberTooLow(const int number, const int min)
{
std::cout << "number: " << number
<< " is too low. Minimal number is: " << min << std::endl;
}
void printNumberTooHigh(const int number, const int max)
{
std::cout << "number: " << number
<< " is too high. Maximal number is: " << max << std::endl;
}
void printNotValidStringLength(const std::string s, const int desiredLength)
{
std::cout << "String: \"" << s << "\" is too short/too long, it is: "
<< s.length() << " characters long but should be: " << desiredLength
<< " characters long " << std::endl;
}
void printInvalidCharacter(const char c, const char desiredCharacter)
{
std::cout << "[ " << c << " ] Is invalid character, expected: [ "
<< desiredCharacter << " ]" << std::endl;
}
void printContainsIllegalCharacter( const std::string s,
const char illegalCharacter )
{
std::cout << "String: " << s << " consists of illegal sign: ["
<< illegalCharacter << "]!" << std::endl;
}
bool numberTooLow(const int number, const int min)
{
if(number < min)
{
printNumberTooLow(number, min);
return 1;
}
return 0;
}
bool numberTooHigh(const int number, const int max)
{
if(number > max)
{
printNumberTooHigh(number, max);
return 1;
}
return 0;
}
bool containsIllegalCharacter(const std::string s, const char illegalCharacter)
{
if( s.find(illegalCharacter) != std::string::npos)
{
printContainsIllegalCharacter(s, illegalCharacter);
return 1;
}
return 0;
}
void e()
{
print("Poor man breakboint");
}
bool charIsNumber(const char c)
{
return c >= '0' && c <= '9';
}
#endif

View File

@ -0,0 +1,89 @@
#ifndef MAIN_CPP
#define MAIN_CPP
#include <iostream>
#include <string>
#include <vector>
#include "basic.cpp"
std::vector <int> fillVector(const int min, const int max)
{
std::vector <int> newVector;
for(int i = min; i <= max; i++)
{
newVector.push_back(i);
}
return newVector;
}
const int MAX_SPOT = 20;
const int MIN_SPOT = 1;
const std::vector <int> NORMAL_POINTS = fillVector(MIN_SPOT, MAX_SPOT);
std::vector <int> multiplyVector(const std::vector <int> v, int multiplyBy)
{
std::vector <int> newVector;
for(unsigned int i = 0; i < v.size(); i++)
{
newVector.push_back(v.at(i)*multiplyBy);
}
return newVector;
}
const std::vector <int> DOUBLE_POINTS = multiplyVector(NORMAL_POINTS, 2);
const std::vector <int> TRIPLE_POINTS = multiplyVector(NORMAL_POINTS, 3);
const int MAX_ONE_HIT = TRIPLE_POINTS.at(TRIPLE_POINTS.size() - 1);
const int THROWS_IN_ONE_HIT = 3;
const int MAX_POINTS_TURN = THROWS_IN_ONE_HIT * MAX_ONE_HIT;
const int STARTING_POINTS = 501;
const int FINAL_POINTS = 0;
bool validString(const std::string s)
{
for(unsigned int i = 0; i < s.length(); i++)
{
if(!charIsNumber(s.at(i)))
{
printErrorStringContainsNotNumber(s);
return 0;
}
}
return 1;
}
bool validNumberInput(const std::string input, const int min, const int max)
{
if(!validString(input)) return 0;
int inputInt = std::stoi(input);
if(numberTooLow(inputInt, min)) return 0;
if(numberTooHigh(inputInt, max)) return 0;
return 1;
}
bool validInput(const std::string s)
{
if(s.length() > 3) return 0;
if(!validNumberInput(s, FINAL_POINTS, STARTING_POINTS)) return 0;
return 1;
}
std::vector <int> requiredShoots(const int pointsLeft)
{
}
int main()
{
print("Enter points left: ");
std::string pointsLeft;
do{
getline(std::cin, pointsLeft);
}while(!validInput(pointsLeft));
int pointsLeftInt = std::stoi(pointsLeft);
requiredShoots(pointsLeftInt);
return 0;
}
#endif

View File

@ -0,0 +1,60 @@
#include <iostream>
#include <cmath>
const int PERCENTAGE = 44;
const float PERCENTAGE_DENOMINATOR = 100;
const int NUMBERS_TO_CHECK = 200;
const bool DEBUG = 0;
bool isInteger(const float number)
{
return number == std::floor(number);
}
void printIsInteger(const int i, const int inputPercentage,
const float calculatedPercentage)
{
std::cout << i << "*" << inputPercentage << "% is an integer number: "
<< i*calculatedPercentage << std::endl;
}
void printDebug(const int i, const float calculatedPercentage)
{
std::cout << "i = " << i << std::endl;
std::cout << i*calculatedPercentage << std::endl;
}
void isIntegerLoop( const bool debugOn = DEBUG,
const int maxNumber = NUMBERS_TO_CHECK,
const int inputPercentage = PERCENTAGE )
{
float actualPercentage = inputPercentage / PERCENTAGE_DENOMINATOR;
for(int i = 1; i <= maxNumber; i++)
{
if(isInteger(i*actualPercentage))
{
printIsInteger(i, inputPercentage, actualPercentage);
}
else if(debugOn) printDebug(i, actualPercentage);
}
}
void printStartingMessage(const int maxNumber = NUMBERS_TO_CHECK,
const int inputPercentage = PERCENTAGE)
{
std::cout << "For max number = " << maxNumber
<< "; and a percentage: " << inputPercentage
<< "; Found following integer numbers: " << std::endl;
}
void mainFunctions()
{
printStartingMessage();
isIntegerLoop();
}
int main()
{
mainFunctions();
return 0;
}

View File

@ -0,0 +1,133 @@
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#ifndef CHECK_ISBN_CPP
#define CHECK_ISBN_CPP
const bool DEBUG = 0;
const int ISBN_LENGTH = 10;
const int CHECK_NUMBER = 11;
const unsigned long long int HIGHEST_ISBN = 9999999999;
void printVector(std::vector <int> v)
{
for(unsigned int i = 0; i < v.size(); i++)
{
std::cout << v[i] << "; ";
}
}
void print(const std::string printMe)
{
std::cout << printMe << std::endl;
}
void e()
{
print("PRINT");
}
bool checkInput(const std::string input)
{
if(input.length() != ISBN_LENGTH)
{
print("Your number is too short/too long");
return 0;
}
for(int i = 0; i <= ISBN_LENGTH - 1; i++)
{
if(input.at(i) < '0' || input.at(i) > '9')
{
print("Your number consists of illegal characters");
return 0;
}
}
return 1;
}
std::vector <int> stringToIntVector(const std::string input)
{
std::vector <int> vector;
for(int i = input.length() - 1; i >= 0; i--)
{
vector.push_back(input.at(i) - '0');
}
return vector;
}
std::vector <int> userISBN()
{
std::string input;
do{
std::cout << "Enter the ISBN number (10 digits): ";
getline(std::cin, input);
}while(!checkInput(input));
return stringToIntVector(input);
}
bool checkISBN(const std::vector <int> isbn)
{
int sum = 0, t = 0;
for(int i = 0; i < ISBN_LENGTH; i++)
{
t += isbn[i];
sum += t;
}
/*if(DEBUG)
{
if(!(sum % CHECK_NUMBER)) print("^^^ VALID NUMBER ^^^");
} */
return !(sum % CHECK_NUMBER);
}
std::vector <int> intToVector(unsigned long long int number)
{
std::vector <int> numbers;
while(number > 0)
{
numbers.push_back(number % 10);
number /= 10;
}
std::reverse(numbers.begin(), numbers.end());
return numbers;
}
int checkAll()
{
int sum = 0;
std::ofstream file;
file.open("ISBN.txt");
for(unsigned long long int i = HIGHEST_ISBN; i >= 1; i--)
{
//if(DEBUG) std::cout << i << std::endl;
if( checkISBN(intToVector(i)) )
{
++sum;
file << std::to_string(i) << "\n";
}
}
file << "There are " << sum << " valid ISBN numbers\n";
file.close();
return sum;
}
int main()
{
checkAll();
return 0;
}
#endif

View File

@ -0,0 +1,48 @@
#include <iostream>
#include <vector>
struct charOccurence
{
char c;
int occurrence;
};
void printCharOccurenceVector(const std::vector <charOccurence> v)
{
std::cout << "[";
for(unsigned int i = 0; i < v.size(); i++)
{
std::cout << "(\"" << v.at(i).c << "\", " << v.at(i).occurrence << ")" << (i + 1 == v.size() ? "" : ", ");
}
std::cout << "]" << std::endl;
}
int main()
{
std::vector <charOccurence> list;
std::string userInput = "aaaabbbcca";
charOccurence newCharOccurence;
newCharOccurence.c = userInput.at(0);
newCharOccurence.occurrence = 1;
for(unsigned int i = 1, j = 1; i < userInput.length(); i++)
{
char newCharacter = userInput.at(i);
if(newCharacter != newCharOccurence.c)
{
list.push_back(newCharOccurence);
j = 1;
newCharOccurence.c = newCharacter;
newCharOccurence.occurrence = j;
}else
{
newCharOccurence.occurrence++;
}
}
list.push_back(newCharOccurence);
printCharOccurenceVector(list);
return 0;
}

View File

@ -0,0 +1,177 @@
#ifndef BASIC_CPP
#define BASIC_CPP
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
void print(const std::string s) { std::cout << s << std::endl; }
int charToInt(const char c) { return c - '0'; }
void e() { print("Poor man breakboint"); }
bool charIsNumber(const char c) { return c >= '0' && c <= '9'; }
void printStringNewLine(const std::string s)
{
std::cout << "string: " << std::endl;
std::cout << "\"" << s << "\"" << std::endl;
}
void printStringContainsNotNumbers(const std::string s, const int position)
{
printStringNewLine(s);
std::cout << "contains character different than number at position: " << position
<< "; this character is: " << s.at(position) << std::endl;
}
void printStringContainsNumbers(const std::string s, const int position)
{
printStringNewLine(s);
std::cout << "contains number at postion: " << position
<< "; this number is: " << s.at(position) << std::endl;
}
void printNumberTooLow(const int number, const int min)
{
std::cout << "number: " << number
<< " is too low. Minimal number is: " << min << std::endl;
}
void printNumberTooHigh(const int number, const int max)
{
std::cout << "number: " << number
<< " is too high. Maximal number is: " << max << std::endl;
}
void printNotValidStringLength(const std::string s, const int desiredLength)
{
printStringNewLine(s);
std::cout << "is too short/too long, it is: "
<< s.length() << " characters long but should be: " << desiredLength
<< " characters long " << std::endl;
}
void printInvalidCharacter(const char c, const char desiredCharacter)
{
std::cout << "[ " << c << " ] Is invalid character, expected: [ "
<< desiredCharacter << " ]" << std::endl;
}
void printContainsIllegalCharacter( const std::string s,
const char illegalCharacter )
{
printStringNewLine(s);
std::cout << " consists of illegal sign: ["
<< illegalCharacter << "]!" << std::endl;
}
bool numberTooLow(const int number, const int min)
{
if(number < min)
{
printNumberTooLow(number, min);
return 1;
}
return 0;
}
bool numberTooHigh(const int number, const int max)
{
if(number > max)
{
printNumberTooHigh(number, max);
return 1;
}
return 0;
}
bool containsIllegalCharacter(const std::string s, const char illegalCharacter)
{
if( s.find(illegalCharacter) != std::string::npos)
{
printContainsIllegalCharacter(s, illegalCharacter);
return 1;
}
return 0;
}
void printStringVector(const std::vector <std::string> vector)
{
for(unsigned int i = 0; i < vector.size(); i++) print(vector.at(i));
}
bool stringContainsNotNumbers(const std::string s)
{
for(unsigned int i = 0; i < s.length(); i++)
{
if(!charIsNumber(s.at(i)))
{
printStringContainsNotNumbers(s, i);
return 1;
}
}
return 0;
}
bool stringContainsNumbers(const std::string s)
{
for(unsigned int i = 0; i < s.length(); i++)
{
if(charIsNumber(s.at(i)))
{
printStringContainsNumbers(s, i);
return 1;
}
}
return 0;
}
bool validStringLength(const std::string s, const int desiredLength)
{
int stringLength = s.length();
if(stringLength != desiredLength)
{
printNotValidStringLength(s, desiredLength);
return 0;
}
return 1;
}
bool validCharacter(const char inputC, const char desiredC)
{
if(inputC != desiredC)
{
printInvalidCharacter(inputC, desiredC);
return 0;
}
return 1;
}
void vectorToFile(const std::vector <std::string> strings, std::ofstream &file)
{
for(unsigned int i = 0; i < strings.size(); i++)
{
file << strings.at(i) << std::endl;
}
}
std::vector <std::string> fileToVector(std::ifstream &file,
std::vector <std::string> strings)
{
std::string line;
if(file.is_open())
{
while(getline(file, line))
{
strings.push_back(line);
}
file.close();
}
return strings;
}
#endif

View File

@ -0,0 +1,11 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris fermentum ac mi quis porta. Aenean vehicula dolor sed leo tristique, ut semper sem sagittis. Nam et faucibus urna. Nam ut neque vitae nisl blandit euismod. Morbi et odio eget ante egestas tempor. Aenean vehicula quis lectus et convallis. Quisque dictum, augue ut ultricies elementum, felis quam rhoncus purus, accumsan tincidunt nunc orci vel nulla. Quisque eros est, tempus nec erat pellentesque, accumsan maximus massa. Aliquam non ante in ex fringilla vehicula in eu magna. Sed aliquet egestas tincidunt. Mauris at libero et nulla mollis bibendum accumsan id metus. Vestibulum ornare nibh ac cursus posuere. Proin efficitur fermentum sapien sit amet porta.
Maecenas luctus neque sed aliquam iaculis. Maecenas turpis metus, fermentum et vehicula eu, consequat ac nisi. Curabitur porta mauris vel nisi vehicula scelerisque. Mauris dolor ex, mattis sit amet porta quis, consectetur volutpat velit. Maecenas sit amet vehicula metus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum ligula mauris, iaculis in porttitor in, viverra quis est. Sed mattis, turpis non facilisis interdum, sem risus volutpat lacus, sed molestie metus tellus vel diam. In nec eleifend ipsum. Donec auctor, dolor fringilla laoreet hendrerit, est tortor luctus nunc, et malesuada lorem diam quis sem. In hac habitasse platea dictumst. Interdum et malesuada fames ac ante ipsum primis in faucibus.
Mauris mollis massa ac massa laoreet posuere. In ullamcorper nunc eu lobortis facilisis. Mauris et risus non ipsum tempus mattis eget a enim. In congue faucibus ante quis iaculis. Vestibulum dictum ultricies augue sed auctor. Maecenas ut mattis leo. Suspendisse quis nisl et elit congue consequat. Fusce tincidunt lacus a tellus lobortis, et tristique diam lacinia.
Aliquam congue enim justo, ac scelerisque risus pharetra quis. Curabitur nec tincidunt nunc, in molestie magna. Maecenas quis tincidunt orci. Ut rutrum ut ex rhoncus accumsan. Nunc sed ligula hendrerit, venenatis urna sit amet, commodo ante. Mauris ac urna viverra, fringilla turpis eu, ornare turpis. Curabitur sodales, sapien sed tristique tristique, dolor leo mollis est, at blandit neque est id mi.
Donec euismod venenatis mauris non bibendum. Duis tellus eros, maximus vel tristique at, congue nec lorem. Vivamus cursus, magna quis lacinia blandit, leo magna varius libero, at pharetra velit metus id massa. Quisque ullamcorper erat eget lacus rhoncus, id imperdiet orci tempus. Sed placerat rutrum vehicula. Suspendisse at sodales dui. Praesent tortor est, ornare vitae cursus sed, hendrerit nec justo. Nam at rhoncus lacus, vitae lobortis nunc. Nunc ac ligula et mauris consequat laoreet. Proin id nulla porttitor, rhoncus massa vel, pretium odio. Aenean in purus velit. Phasellus molestie luctus blandit. Integer nec auctor risus, eu molestie odio. Aliquam ipsum urna, eleifend non ultricies sit amet, blandit sed risus. Pellentesque vitae gravida lacus, vel pellentesque nisi.

View File

@ -0,0 +1,138 @@
#ifndef MAIN_CPP
#define MAIN_CPP
#include <string>
#include <iostream>
#include <vector>
#include "basic.cpp"
struct wordOccurences
{
std::string word;
int occurences;
}
struct previousWords
{
std::string word;
std::vector <wordOccurences> previousWords;
};
struct wordProbabiliy
{
std::string previousWord;
std::string nextWord;
float probability;
}
bool validInput(const std::string userInput)
{
if(stringContainsNumbers(userInput)) return 0;
return 1;
}
std::vector <std::string> divideIntoWords(const std::string userInput)
{
std::vector <std::string> words;
int inputLength = userInput.length();
int wordLength = 0;
for(int i = 0; i < inputLength; i++)
{
if(userInput.at(i) == ' ')
{
words.push_back(userInput.substr(i - wordLength, wordLength));
wordLength = 0;
}else wordLength++;
if(i + 1 == inputLength)
{
words.push_back(userInput.substr(i - wordLength + 1, wordLength + 1));
wordLength = 0;
}
}
return words;
}
int wordRepeats(const std::vector <previousWords> wordsList, const std::string word)
{
int wordsSize = wordsList.size();
for(int i = 0; i < wordsSize; i++)
{
if(wordsList.at(i).word == word) return i;
}
return -1;
}
bool alreadyExists(const std::vector <previousWords> wordsList, const std::string s)
{
for(unsigned int i = 0; i < wordsList.size(); i++)
{
if(s == wordsList.previousWOrds
}
}
std::vector <previousWords> getWordsAndTheirPrevious(const std::vector <std::string> words)
{
std::vector <previousWords> wordsList;
int wordsSize = words.size();
for(int i = 1; i < wordsSize; i++)
{
previousWords temp;
temp.word = words.at(i);
wordOccurences tempTwo;
tempTwo.word = words.at(i - 1));
tempTwo.occurences = 1;
temp.previousWords.push_back(tempTwo);
int position = wordRepeats(wordsList, temp.word);
if(position == -1)
{
wordsList.push_back(temp);
}else
{
wordsList.at(position).previousWords.push_back(temp.previousWords.at(0));
}
}
return wordsList;
}
void printPreviousWord(const previousWords word)
{
std::cout << "The word is \"" << word.word << "\" Words before it are: " << std::endl;
for(unsigned int i = 0; i < word.previousWords.size(); i++)
{
print(word.previousWords.at(i));
}
}
void printPreviousWordsVector(const std::vector <previousWords> v)
{
for(unsigned int i = 0; i < v.size(); i++)
{
printPreviousWord(v.at(i));
}
}
std::vector <wordProbability> getWordProbability(const std::vector <previousWords> wordsList)
{
std::vector <wordProbability> probalityVector;
for(unsigned int i = 0; i - 1 < wordsList.size(); i++)
{
pro
}
}
int main()
{
std::string userInput;
do{
getline(std::cin, userInput);
}while(!validInput(userInput));
std::vector <std::string> words = divideIntoWords(userInput);
std::vector <previousWords> prev = getWordsAndTheirPrevious(words);
printPreviousWordsVector(prev);
return 0;
}
#endif

View File

@ -0,0 +1,27 @@
#include <iostream>
int multiplication(int a, int b)
{
int answer = 0;
for(int i = 0; i < a; i++)
{
answer += b;
}
if(answer != a*b)
{
std::cout << "There is a mistake in your code!" << std::endl;
return -1;
} else return answer;
}
int main()
{
int a,b;
std::cout << "Enter number a" << std::endl;
std::cin >> a;
std::cout << "Enter number b" << std::endl;
std::cin >> b;
std::cout << multiplication(a, b) << std::endl;
return 0;
}

View File

@ -0,0 +1,96 @@
#include <iostream>
#include <vector>
int sumStartEnd(int start, int end)
{
int sum = 0;
for(int i = start; i <= end; i++)
{
sum += i;
}
return sum;
}
int main()
{
std::cout << "Krzysztof" << std::endl;
for(int i = 700; i >= 200; i -= 13) std::cout << i << std::endl;
std::vector <int> array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// if SECOND means 0, 1, TWO
std::cout << array[2] << std::endl;
// if SECOND means 1, TWO
std::cout << array[1] << std::endl;
std::cout << sumStartEnd(0, 1000);
std::string userName;
std::cout << std::endl;
getline(std::cin, userName);
if(userName == "Jack") std::cout << "Hi Jack!" << std::endl;
else std::cout << "Hello, " << userName << std::endl;
for(int i = 0; i <= 100; i++)
{
if(i % 2 == 0) std::cout << i << " is an even number" << std::endl;
else std::cout << i << " is an odd number" << std::endl;
}
bool flag = 1;
for(int i = 0; i <= 100; i++)
{
if(flag) std::cout << i << " is an even number" << std::endl;
else std::cout << i << " is an odd number" << std::endl;
flag = -flag;
}
for(int i = 0; i <= 100; i += 2) std::cout << i << " is an even number " << std::endl;
for(int i = 1; i <= 99; i += 2) std::cout << i << " is an odd number " << std::endl;
for(int i = 1, j = 1; j <= 12; i++)
{
std::cout << i * j << " ";
if(i == 12)
{
i = 1;
j++;
std::cout << std::endl;
}
}
std::cout << std::endl;
std::string sentence;
getline(std::cin, sentence);
std::vector <std::string> words;
std::string temp;
for(unsigned int i = 0; i < sentence.length(); i++)
{
if(sentence.at(i) == ' ' || i + 1 == sentence.length())
{
if(i + 1 == sentence.length()) temp.push_back(sentence.at(i));
words.push_back(temp);
temp = "";
}else temp.push_back(sentence.at(i));
}
for(unsigned int i = 0; i < words.size(); i++)
{
std::cout << words[i] << std::endl;
}
int score;
char project;
std::vector <char> GRADES = {'F', 'C', 'B', 'A'};
std::cin >> score;
std::cout << std::endl;
std::cin >> project;
std::cout << std::endl;
bool doneProject = 0;
if(project == 'Y') doneProject = 1;
if(score < 50) std::cout << GRADES[0 + doneProject];
else if(score < 70) std::cout << GRADES[1 + doneProject];
else if(score < 90) std::cout << GRADES[2 + doneProject];
else std::cout << GRADES[3];
}

View File

@ -0,0 +1,10 @@
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::uniform_real_distribution<double> dist(1.0, 10.0);
for (int i=0; i<16; ++i)
std::cout << dist(rd) << "\n";
}

View File

@ -0,0 +1,22 @@
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string userString;
getline(std::cin, userString);
int sLength = userString.length();
std::string tempString = userString;
for(int i = 0; i < sLength/2; i++)
{
char temp = tempString[sLength - 1 - i];
tempString[sLength - 1 - i] = tempString[i];
tempString[i] = temp;
}
reverse(userString.begin(), userString.end());
bool correct = tempString == userString;
std::cout << correct << std::endl;
std::cout << tempString << std::endl;
return 0;
}

View File

@ -0,0 +1,48 @@
#include <iostream>
#include <string>
#include <math.h>
const std::string ENTER = "Enter quadratic equation constants: ";
const std::string WHAT_TO_INPUT = "a, b, c as in: ax^2 + bx + c = 0";
const std::string START = ENTER + WHAT_TO_INPUT;
void print(const std::string s) { std::cout << s << std::endl; }
float getDelta(float a, float b, float c)
{
return b*b - 4*a*c;
}
float calculateFirstTerm(float a, float b, float delta)
{
return (-b - sqrt(delta))/(2*a);
}
float calculateSecondTerm(float a, float b, float delta)
{
return (-b + sqrt(delta))/(2*a);
}
int main()
{
print(START);
float a, b, c;
std::cin >> a;
std::cin >> b;
std::cin >> c;
float delta = getDelta(a, b, c);
if(delta < 0)
{
print("delta smaller than 0");
return -1;
}
float x_1 = calculateFirstTerm(a, b, delta);
float x_2 = calculateSecondTerm(a, b, delta);
print("Solutions:");
std::cout << "x_1 = " << x_1 << std::endl;
std::cout << "x_2 = " << x_2 << std::endl;
return 0;
}

View File

@ -0,0 +1,111 @@
#include <iostream>
#include <vector>
void printField(std::vector<unsigned int> &field)
{
std::cout << std::endl;
for(int i = 0; i < 9; i++)
{
if(i % 3 == 0) std::cout << std::endl;
if(field[i] == 0) std::cout << "-";
else if(field[i] == 1) std::cout << "X";
else if(field[i] == 2) std::cout << "O";
}
std::cout << std::endl;
}
unsigned int chooseField(unsigned int playerNumber, std::vector<unsigned int> &field)
{
unsigned int chosenField;
do
{
std::cout << "player " << playerNumber << " choose a field:" << std::endl;
std::cin >> chosenField;
}while(field[chosenField] != 0);
return chosenField;
}
bool vertical(unsigned int playerNumber, std::vector<unsigned int> &field)
{
if((field[0] == playerNumber && field[1] == playerNumber && field[2] == playerNumber)
|| (field[3] == playerNumber && field[4] == playerNumber && field[5] == playerNumber)
|| (field[6] == playerNumber && field[7] == playerNumber && field[8] == playerNumber))
{
return 1;
}else return 0;
}
bool horizontal(unsigned int playerNumber, std::vector<unsigned int> &field)
{
if((field[0] == playerNumber && field[3] == playerNumber && field[6] == playerNumber)
|| (field[1] == playerNumber && field[4] == playerNumber && field[7] == playerNumber)
|| (field[2] == playerNumber && field[5] == playerNumber && field[8] == playerNumber))
{
return 1;
}else return 0;
}
bool across(unsigned int playerNumber, std::vector<unsigned int> &field)
{
if((field[0] == playerNumber && field[4] == playerNumber && field[8] == playerNumber)
|| (field[2] == playerNumber && field[4] == playerNumber && field[6] == playerNumber))
{
return 1;
}else return 0;
}
bool checkPlayerWin(unsigned int playerNumber, std::vector<unsigned int> &field)
{
if(vertical(playerNumber, field)) return 1;
if(horizontal(playerNumber, field)) return 1;
if(across(playerNumber, field)) return 1;
else return 0;
}
unsigned int checkIfWin(std::vector<unsigned int> &field)
{
if(checkPlayerWin(1, field)) return 1;
else if(checkPlayerWin(2, field)) return 2;
else return 0;
}
bool checkIfFilled(std::vector<unsigned int> &field)
{
bool filled = 1;
for(int i = 0; i < 9; i++)
{
if(field[i] == 0)
{
filled = 0;
return filled;
}
}
return filled;
}
bool turn(unsigned int playerNumber, std::vector<unsigned int> &field, bool *filled, unsigned int *whoWon)
{
field[chooseField(playerNumber, field)] = playerNumber;
printField(field);
*whoWon = checkIfWin(field);
*filled = checkIfFilled(field);
if(*whoWon != 0 || *filled != 0) return 1;
else return 0;
}
int main()
{
std::vector<unsigned int> field = {0, 0, 0, 0, 0, 0, 0, 0, 0};
unsigned int whoWon = 0;
bool filled = 0;
while(whoWon == 0 || filled == 0)
{
if(turn(1, field, &filled, &whoWon)) break;
if(turn(2, field, &filled, &whoWon)) break;
}
if(!filled) std::cout << "Player " << whoWon << " Won!" << std::endl;
else std::cout << "DRAW!" << std::endl;
return 0;
}

View File

@ -0,0 +1,89 @@
#include <iostream>
#include <string>
#include <vector>
const std::vector <std::string> TIERS = {"Abhorrent", "Bad", "Mid", "Good", "Top", "God Tier"};
const float TIER_BASE = TIERS.size();
void print(std::string const s)
{
std::cout << s << std::endl;
}
bool errorUserInput(std::string userInput)
{
if(userInput.find("/") == std::string::npos)
{
print("No '/' was found!");
return 1;
}
size_t positionOfSlash = userInput.find("/");
std::string nominatorS = userInput.substr(0, positionOfSlash);
try
{
float nominator = stof(nominatorS);
}catch ( std::invalid_argument )
{
print("No number was found before the slash!");
return 1;
}
std::string denominatorS = userInput.substr(positionOfSlash + 1, userInput.length() - 1);
try
{
float denominator = stof(denominatorS);
if(denominator == 0)
{
print("You cannot divide by 0!");
return 1;
}
}catch ( std::invalid_argument )
{
print("No number was found after the slash!");
return 1;
}
return 0;
}
std::string convertToTier(float nominator, float denominator)
{
float fraction = nominator / denominator;
int tierIndex;
for(int i = TIER_BASE; i > 0; i--)
{
if(fraction >= ( i / TIER_BASE))
{
tierIndex = i - 1;
break;
}
}
if(tierIndex == 0 & fraction > (1.1/10.0)) return TIERS[1];
return TIERS[tierIndex];
}
int main()
{
std::string userScore;
do
{
print("Enter your score in a format: numberOne/numberTwo");
getline(std::cin, userScore);
}while(errorUserInput(userScore));
size_t positionOfSlash = userScore.find("/");
std::string nominatorS = userScore.substr(0, positionOfSlash);
float nominator = stof(nominatorS);
std::string denominatorS = userScore.substr(positionOfSlash + 1, userScore.length() - 1);
float denominator = stof(denominatorS);
print(convertToTier(nominator, denominator));
return 0;
}

View File

@ -0,0 +1,11 @@
#include <stdio.h>
int main()
{
int x = 10;
while (x-- > 0)
{
printf("%d;", x);
}
return 0;
}

View File

@ -0,0 +1,22 @@
// bernoulli_distribution
#include <iostream>
#include <random>
int main()
{
const int nrolls=10000;
std::random_device rd;
std::mt19937 gen(rd());
std::bernoulli_distribution distribution(0.5);
int count=0; // count number of trues
for (int i=0; i<nrolls; ++i) if (distribution(gen)) ++count;
std::cout << "bernoulli_distribution (0.5) x 10000:" << std::endl;
std::cout << "true: " << count << std::endl;
std::cout << "false: " << nrolls-count << std::endl;
return 0;
}

View File

@ -0,0 +1,13 @@
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
for(int i = 0; i < 10; i++) {
std::cout << dis(gen) << std::endl;
}return 0;
}

View File

@ -0,0 +1,2 @@
yousuckatcards:
g++ -Wall -Wextra -pedantic yousuckatcards.cpp

View File

@ -0,0 +1,127 @@
#include <iostream>
#include <random>
#include <string>
const int SEQUENCE_LENGTH = 3;
const bool BOT_WON = 0;
const bool PLAYER_WON = 1;
const int NOBODY_WON = 2;
void print(std::string const s)
{
std::cout << s << std::endl;
}
bool validSequence(std::string const s)
{
if(s.size() != SEQUENCE_LENGTH)
{
print("Sequence too long");
return false;
}
if( (s[0] != 'B' && s[0] != 'R') ||
(s[1] != 'B' && s[1] != 'R') ||
(s[2] != 'B' && s[2] != 'R'))
{
print("Sequence consists of illegal signs!");
return false;
}
return true;
}
std::string playerChoice()
{
std::string playerSequence;
do
{
std::cin >> playerSequence;
}
while(!validSequence(playerSequence));
return playerSequence;
}
std::string botChoice(std::string const playerSequence)
{
std::string botSequence;
if(playerSequence[1] == 'B') botSequence.push_back('R');
else botSequence.push_back('B');
botSequence.push_back(playerSequence[0]);
botSequence.push_back(playerSequence[2]);
return botSequence;
}
int compareGeneratedAndPlayers(std::string playerSequence, std::string botSequence, std::string generatedSequence)
{
int generatedSequenceLength = generatedSequence.length();
std::string sequenceToCompare = generatedSequence.substr(generatedSequenceLength - SEQUENCE_LENGTH, generatedSequenceLength);
if(sequenceToCompare.compare(playerSequence) == 0) return PLAYER_WON;
if(sequenceToCompare.compare(botSequence) == 0) return BOT_WON;
else return NOBODY_WON;
}
bool game(std::string playerSequence, std::string botSequence)
{
std::string generatedSequence;
std::random_device rd;
std::mt19937 gen(rd());
std::bernoulli_distribution distribution(0.5);
for(int i = 0; i < SEQUENCE_LENGTH; i++)
{
if(distribution(gen)) generatedSequence.push_back('R');
else generatedSequence.push_back('B');
}
while(compareGeneratedAndPlayers(playerSequence, botSequence, generatedSequence) == NOBODY_WON)
{
if(distribution(gen)) generatedSequence.push_back('R');
else generatedSequence.push_back('B');
}
print(generatedSequence);
if(compareGeneratedAndPlayers(playerSequence, botSequence, generatedSequence) == PLAYER_WON) return PLAYER_WON;
else return BOT_WON;
}
void score(int playerWins, int botWins)
{
std::cout << "Player won: " << playerWins << " times!" << std::endl;
std::cout << "Bot won: " << botWins << " times!" << std::endl;
}
int main()
{
int playerWins = 0;
int botWins = 0;
do
{
print("Do you want to play the game? 1 - yes, 0 - no");
bool continue_ = 1;
std::string playerInput;
std::cin >> playerInput;
if(playerInput[0] == '1') continue_ = 1;
else continue_ = 0;
if(!continue_) break;
std::string playerSequence;
print("Write three colors sequence created from 52 cards from the deck (26 Black, 26 Red), write B for Black and R for Red");
playerSequence = playerChoice();
std::string botSequence = botChoice(playerSequence);
print("Bot has chosen this sequence:");
print(botSequence);
if(game(playerSequence, botSequence))
{
print("You won!");
playerWins++;
score(playerWins, botWins);
}
else
{
print("Bot won!");
botWins++;
score(playerWins, botWins);
}
}while(1);
return 1;
}

View File

@ -0,0 +1,8 @@
#include <iostream>
int main()
{
float X = 1/2;
std::cout << X << std::endl;
return 0;
}

View File

@ -15,5 +15,6 @@ npm run dev
Then open the printed local URL (default http://localhost:5173).
Notes:
- The Battery Status API may be unavailable or disabled in some browsers for privacy reasons. In that case, the app will show a helpful message.
- On laptops it typically works in Chromium-based browsers; mobile support varies.
- On laptops it typically works in Chromium-based browsers; mobile support varies.

View File

@ -4,9 +4,9 @@
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"typecheck": "tsc --noEmit",
"build": "vite build",
"dev": "vite",
"typecheck": "tsc --noEmit",
"build": "vite build",
"preview": "vite preview --strictPort --port 5173"
},
"dependencies": {
@ -14,7 +14,7 @@
"react-dom": "^18.3.1"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.1",
"@vitejs/plugin-react": "^4.3.1",
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
"typescript": "^5.5.4",

View File

@ -1,12 +1,13 @@
# Champions League Live Scores (React + TS)
This app displays live and today's UEFA Champions League results. It uses:
- React + TypeScript (Vite) for the frontend
- A tiny Express proxy server that calls football-data.org to fetch match data
## Setup
1) Create a `.env` file in `TS/champions_leauge_scores/`:
1. Create a `.env` file in `TS/champions_leauge_scores/`:
```
FOOTBALL_DATA_API_KEY=your_api_token_here
@ -15,7 +16,7 @@ PORT=8787
Sign up at https://www.football-data.org/ to get a free API token. Free tier has rate limits.
2) Install dependencies and run both servers:
2. Install dependencies and run both servers:
```
npm install
@ -26,9 +27,11 @@ npm run dev
- API Proxy: http://localhost:8787
## Notes
- Live endpoint: `GET /api/live`
- Today endpoint: `GET /api/matches` (uses today's date by default)
- Edit polling intervals in `src/App.tsx` if needed.
## License
MIT
MIT

View File

@ -4,29 +4,29 @@
"private": true,
"type": "module",
"scripts": {
"dev": "concurrently \"vite\" \"npm:server:dev\"",
"dev": "concurrently \"vite\" \"npm:server:dev\"",
"build": "vite build",
"preview": "vite preview",
"server:dev": "tsx watch server/src/server.ts"
"server:dev": "tsx watch server/src/server.ts"
},
"dependencies": {
"axios": "^1.7.2",
"dotenv": "^16.4.5",
"cors": "^2.8.5",
"cors": "^2.8.5",
"express": "^4.19.2",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.1",
"@vitejs/plugin-react": "^4.3.1",
"@types/express": "^4.17.21",
"@types/cors": "^2.8.17",
"@types/cors": "^2.8.17",
"@types/node": "^20.12.12",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"concurrently": "^8.2.2",
"ts-node-dev": "^2.0.0",
"tsx": "^4.19.2",
"ts-node-dev": "^2.0.0",
"tsx": "^4.19.2",
"typescript": "^5.4.5",
"vite": "^5.3.3"
}

View File

@ -0,0 +1,92 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"two-inputs": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/two-inputs",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "two-inputs:build:production"
},
"development": {
"buildTarget": "two-inputs:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "two-inputs:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": ["zone.js", "zone.js/testing"],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
}
}
}
}
}
}

View File

@ -0,0 +1,40 @@
{
"name": "two-inputs",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/cdk": "^17.3.5",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/material": "^17.3.5",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/router": "^17.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.0.3",
"@angular/cli": "^17.0.3",
"@angular/compiler-cli": "^17.0.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.2.2"
}
}

View File

@ -0,0 +1,30 @@
<mat-form-field class="example-form-field">
<mat-label>min</mat-label>
<input matInput type="number" [(ngModel)]="min" (input)="updateInput()">
</mat-form-field>
<mat-form-field class="example-form-field">
<mat-label>max</mat-label>
<input matInput type="number" [(ngModel)]="max" (input)="updateInput()">
</mat-form-field>
<mat-form-field class="example-form-field">
<mat-label>step</mat-label>
<input matInput type="number" [(ngModel)]="step" (input)="updateInput()">
</mat-form-field>
<mat-form-field class="example-form-field">
<mat-label>targetValue</mat-label>
<input matInput type="number" [(ngModel)]="targetValue" (input)="updateInput()">
</mat-form-field> <br>
<mat-form-field class="example-form-field">
<mat-label>inputOne</mat-label>
<input disabled="true" matInput type="number" [min]="min" [step]="step" [max]="max" [(ngModel)]="inputOne">
</mat-form-field>
<button mat-button (click)="upOne()"> UP </button>
<button mat-button (click)="downOne()"> DOWN </button>
<br>
<mat-form-field class="example-form-field">
<mat-label>inputTwo</mat-label>
<input disabled="true" matInput type="number" [min]="min" [step]="step" [max]="max" [(ngModel)]="inputTwo">
</mat-form-field>
<button mat-button (click)="upTwo()"> UP </button>
<button mat-button (click)="downTwo()"> DOWN </button>
<br>

View File

@ -0,0 +1,138 @@
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { MatInputModule } from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, MatInputModule, FormsModule, MatButtonModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
inputOne: number | null = null; // Default initialization to 50
inputTwo: number | null = null; // Default initialization to 50
min: number | null = 100;
max: number | null = 250;
step: number | null = 25;
targetValue: number | null = 325;
indexOne: number = 0;
indexTwo: number = 0;
possibleValues: Array<[number, number]> | null = [];
constructor() {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
}
ngOnInit() {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
}
public updateInput() {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
}
private changeIndex(currentValue: number, direction: boolean) {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
const length = this.possibleValues?.length;
if(typeof length !== "undefined") {
if(direction) {
if(currentValue + 1 > length - 1) {
return 0;
}
return currentValue + 1;
} else {
if(currentValue - 1 < 0) {
return length - 1;
}
return currentValue - 1;
}
} else {
console.error(`appComponent, changeIndex, length is undefined!`, length);
}
return currentValue;
}
updateTwoValue() {
if(this.possibleValues !== null) {
this.inputOne = this.possibleValues[this.indexOne][0];
if(typeof this.inputOne !== "undefined" && this.inputOne !== null) {
const result = AppComponent.findCorrespondingValue(this.possibleValues, this.inputOne);
if(result !== null) {
[this.inputTwo, this.indexTwo] = result;
return;
}
console.error(`result is null!`);
}
console.error(`this.inputOne is null or undefined!: `, this.inputOne, this.possibleValues, this.indexOne);
}
}
upOne() {
this.indexOne = this.changeIndex(this.indexOne, true);
this.updateTwoValue();
}
downOne() {
this.indexOne = this.changeIndex(this.indexOne, false);
this.updateTwoValue();
}
upTwo() {
this.indexTwo = this.changeIndex(this.indexTwo, true);
if(this.possibleValues !== null) {
this.inputTwo = this.possibleValues[this.indexTwo][1];
const result = AppComponent.findCorrespondingValue(this.possibleValues, this.inputTwo);
if(result !== null) {
[this.inputOne, this.indexOne] = result;
}
}
}
downTwo() {
this.indexTwo = this.changeIndex(this.indexTwo, false);
if(this.possibleValues !== null) {
this.inputTwo = this.possibleValues[this.indexTwo][1];
const result = AppComponent.findCorrespondingValue(this.possibleValues, this.inputTwo);
if(result !== null) {
[this.inputOne, this.indexOne] = result;
}
}
}
private static findCorrespondingValue(pairs: Array<[number, number]>, number: number): [number, number] | null {
for (let index = 0; index < pairs.length; index += 1) {
if (pairs[index][0] === number) {
return [pairs[index][1], index]; // Return n2 if the given number matches n1
} else if (pairs[index][1] === number) {
return [pairs[index][0], index]; // Return n1 if the given number matches n2
}
}
console.error("No corresponding value found for the provided number in the pairs.", pairs, number);
return null; // Return null if no matching number is found
}
private static findValidPairs(x: number | null, y: number | null, z: number | null, ml: number | null): Array<[number, number]> | null {
if (x === null || y === null || z === null || ml === null) {
console.error("findValidPairs, some value is null");
return null;
}
const results: Array<[number, number]> = [];
// Iterate through possible values of n1, which must be multiples of x, at least y, and not more than z
for (let n1 = y; n1 <= ml - y && n1 <= z; n1 += x) {
let n2 = ml - n1;
// Ensure n2 is also a multiple of x, n2 >= y, and n2 <= z
if (n2 % x === 0 && n2 >= y && n2 <= z) {
results.push([n1, n2]);
}
}
return results;
}
}

View File

@ -0,0 +1,10 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"]
}

View File

@ -0,0 +1,29 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": ["ES2022", "dom"]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -0,0 +1,9 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": ["jasmine"]
},
"include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}