This commit is contained in:
Joaquin Gottlebe
2025-07-30 15:57:48 +02:00
parent e49fcfac46
commit a639c34cee
273 changed files with 20151 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
// BMP-related data types based on Microsoft's own
#include <stdint.h>
// These data types are essentially aliases for C/C++ primitive data types.
// Adapted from http://msdn.microsoft.com/en-us/library/cc230309.aspx.
// See https://en.wikipedia.org/wiki/C_data_types#stdint.h for more on stdint.h.
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
// The BITMAPFILEHEADER structure contains information about the type, size,
// and layout of a file that contains a DIB [device-independent bitmap].
// Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx.
typedef struct
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;
// The BITMAPINFOHEADER structure contains information about the
// dimensions and color format of a DIB [device-independent bitmap].
// Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx.
typedef struct
{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;
// The RGBTRIPLE structure describes a color consisting of relative intensities of
// red, green, and blue. Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx.
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
+82
View File
@@ -0,0 +1,82 @@
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
const int BITS_IN_BYTE = 8;
int main(void)
{
string text = get_string("Text: ");
// Loop over every character
int i = 0;
int l = 0;
double rest = 0;
double zahl;
int len = 0;
int bi;
int n = 0;
int m = 0;
for (i = 0, len = strlen(text); i < len; i++)
{
zahl = text[i];
bi = 0;
for (l = 0; l < BITS_IN_BYTE; l++)
{
zahl = (zahl - (rest * pow(10, -1))) / 2.0 ;
rest = (zahl - floor(zahl)) * 10;
if (rest > 0)
{
bi = bi + pow(10, l);
}
else
{
continue;
}
}
if (bi >= 1000000 && bi <= 1111111)
{
char test[bi];
sprintf(test, "0%d", bi);
//printf("%s",test);
for (n = 0, m = strlen(test); n < m; n++)
{
if (test[n] == 48)
{
// Dark emoji
printf("\U000026AB");
}
else if (test[n] == 49)
{
// Light emoji
printf("\U0001F7E1");
}
}
}
else if (bi >= 100000 && bi <= 111111)
{
char test[bi];
sprintf(test, "00%d", bi);
//printf("%s",test);
for (n = 0, m = strlen(test); n < m; n++)
{
if (test[n] == 48)
{
// Dark emoji
printf("\U000026AB");
}
else if (test[n] == 49)
{
// Light emoji
printf("\U0001F7E1");
}
}
}
printf("\n");
}
}
+76
View File
@@ -0,0 +1,76 @@
#include <cs50.h>
#include <stdio.h>
int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);
int main(void)
{
// Ask how many cents the customer is owed
int cents = get_cents();
// Calculate the number of quarters to give the customer
int quarters = calculate_quarters(cents);
cents = cents - quarters * 25;
// Calculate the number of dimes to give the customer
int dimes = calculate_dimes(cents);
cents = cents - dimes * 10;
// Calculate the number of nickels to give the customer
int nickels = calculate_nickels(cents);
cents = cents - nickels * 5;
// Calculate the number of pennies to give the customer
int pennies = calculate_pennies(cents);
cents = cents - pennies * 1;
// Sum coins
int coins = quarters + dimes + nickels + pennies;
// Print total number of coins to give the customer
printf("%i\n", coins);
}
int get_cents(void)
{
int cents;
do
{
cents = get_int("Number of cents: \n");
}
while (cents < 0);
return cents;
}
int calculate_quarters(int cents)
{
int quarters;
quarters = cents / 25;
return quarters;
}
int calculate_dimes(int cents)
{
int dimes;
dimes = cents / 10;
return dimes;
}
int calculate_nickels(int cents)
{
int nickels;
nickels = cents / 5;
return nickels;
}
int calculate_pennies(int cents)
{
int pennies;
pennies = cents / 1;
return pennies;
}
+38
View File
@@ -0,0 +1,38 @@
# TODO
quarters = 0.25
dimes = 0.10
nickels = 0.05
pennies = 0.01
coins = 0
print('Change owed: ')
while True:
try:
change = float(input())
if change >= 0:
break
else:
print("Change must be greater then 0: ")
except ValueError:
print("Change must be a numeric value: ")
while change > 0:
if change >= quarters:
change -= quarters
coins += 1
elif change >= dimes:
change -= dimes
coins += 1
elif change >= nickels:
change -= nickels
coins += 1
elif change >= pennies:
change -= pennies
coins += 1
change = round(change, 2)
print(coins)
+111
View File
@@ -0,0 +1,111 @@
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 3)
{
printf("Usage: colorize infile outfile\n");
return 1;
}
// remember filenames
char *infile = argv[1];
char *outfile = argv[2];
// open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 4;
}
// open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
printf("Could not create %s.\n", outfile);
return 5;
}
// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
bi.biBitCount != 24 || bi.biCompression != 0)
{
fclose(outptr);
fclose(inptr);
printf("Unsupported file format.\n");
return 6;
}
int height = abs(bi.biHeight);
int width = bi.biWidth;
// allocate memory for image
RGBTRIPLE (*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));
if (image == NULL)
{
printf("Not enough memory to store image.\n");
fclose(outptr);
fclose(inptr);
return 7;
}
// determine padding for scanlines
int padding = (4 - (width * sizeof(RGBTRIPLE)) % 4) % 4;
// iterate over infile's scanlines
for (int i = 0; i < height; i++)
{
// read row into pixel array
fread(image[i], sizeof(RGBTRIPLE), width, inptr);
// skip over padding
fseek(inptr, padding, SEEK_CUR);
}
colorize(height, width, image);
// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);
// write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);
// write new pixels to outfile
for (int i = 0; i < height; i++)
{
// write row to outfile
fwrite(image[i], sizeof(RGBTRIPLE), width, outptr);
// write padding at end of row
for (int k = 0; k < padding; k++)
{
fputc(0x00, outptr);
}
}
// free memory for image
free(image);
// close infile
fclose(inptr);
// close outfile
fclose(outptr);
return 0;
}
+56
View File
@@ -0,0 +1,56 @@
//// TODO ////
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int modulo = 0;
int start = 0;
long number = 0;
// Promt for input
number = get_long("Number: ");
printf("%li\n", number);
// Calculate checksum
//for (int i = length; i < length; i-=2)
//{
// printf("number[i]");
//}
// Check for card length and starting digits
// If invalid Print INVALID\n
if (modulo != 0)
{
printf("INVALID\n");
}
// Else
else
{
// Print AMEX\n
if (start == 34 || start == 37)
{
printf("AMEX\n");
}
// Print MASTERCARD\n
else if (start == 51 || start == 52 || start == 53 || start == 54 || start == 55)
{
printf("MASTERCARD\n");
}
// Print VISA\n
else if (start == 4)
{
printf("VISA\n");
}
}
}
+62
View File
@@ -0,0 +1,62 @@
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
} node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
// TODO
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
// TODO: Improve this hash function
return toupper(word[0]) - 'A';
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
// TODO
// Open the dictionary file
// Read each word in the file
// Add each word to the hash table
// Close the dictionary file
return false;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return 0;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
return false;
}
+19
View File
@@ -0,0 +1,19 @@
// Declares a dictionary's functionality
#ifndef DICTIONARY_H
#define DICTIONARY_H
#include <stdbool.h>
// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45
// Prototypes
bool check(const char *word);
unsigned int hash(const char *word);
bool load(const char *dictionary);
unsigned int size(void);
bool unload(void);
#endif // DICTIONARY_H
+58
View File
@@ -0,0 +1,58 @@
import csv
import sys
def main():
# TODO: Check for command-line usage
# TODO: Read database file into a variable
# TODO: Read DNA sequence file into a variable
# TODO: Find longest match of each STR in DNA sequence
# TODO: Check database for matching profiles
return
def longest_match(sequence, subsequence):
"""Returns length of longest run of subsequence in sequence."""
# Initialize variables
longest_run = 0
subsequence_length = len(subsequence)
sequence_length = len(sequence)
# Check each character in sequence for most consecutive runs of subsequence
for i in range(sequence_length):
# Initialize count of consecutive runs
count = 0
# Check for a subsequence match in a "substring" (a subset of characters) within sequence
# If a match, move substring to next potential match in sequence
# Continue moving substring and checking for matches until out of consecutive matches
while True:
# Adjust substring start and end
start = i + count * subsequence_length
end = start + subsequence_length
# If there is a match in the substring
if sequence[start:end] == subsequence:
count += 1
# If there is no match in the substring
else:
break
# Update most consecutive matches found
longest_run = max(longest_run, count)
# After checking for runs at each character in seqeuence, return longest run found
return longest_run
main()
+150
View File
@@ -0,0 +1,150 @@
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
int main(int argc, char *argv[])
{
// Define allowable filters
char *filters = "bgrs";
// Get filter flag and check validity
char filter = getopt(argc, argv, filters);
if (filter == '?')
{
printf("Invalid filter.\n");
return 1;
}
// Ensure only one filter
if (getopt(argc, argv, filters) != -1)
{
printf("Only one filter allowed.\n");
return 2;
}
// Ensure proper usage
if (argc != optind + 2)
{
printf("Usage: ./filter [flag] infile outfile\n");
return 3;
}
// Remember filenames
char *infile = argv[optind];
char *outfile = argv[optind + 1];
// Open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 4;
}
// Open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
printf("Could not create %s.\n", outfile);
return 5;
}
// Read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
// Read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
// Ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
bi.biBitCount != 24 || bi.biCompression != 0)
{
fclose(outptr);
fclose(inptr);
printf("Unsupported file format.\n");
return 6;
}
// Get image's dimensions
int height = abs(bi.biHeight);
int width = bi.biWidth;
// Allocate memory for image
RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));
if (image == NULL)
{
printf("Not enough memory to store image.\n");
fclose(outptr);
fclose(inptr);
return 7;
}
// Determine padding for scanlines
int padding = (4 - (width * sizeof(RGBTRIPLE)) % 4) % 4;
// Iterate over infile's scanlines
for (int i = 0; i < height; i++)
{
// Read row into pixel array
fread(image[i], sizeof(RGBTRIPLE), width, inptr);
// Skip over padding
fseek(inptr, padding, SEEK_CUR);
}
// Filter image
switch (filter)
{
// Blur
case 'b':
blur(height, width, image);
break;
// Grayscale
case 'g':
grayscale(height, width, image);
break;
// Reflection
case 'r':
reflect(height, width, image);
break;
// Sepia
case 's':
sepia(height, width, image);
break;
}
// Write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);
// Write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);
// Write new pixels to outfile
for (int i = 0; i < height; i++)
{
// Write row to outfile
fwrite(image[i], sizeof(RGBTRIPLE), width, outptr);
// Write padding at end of row
for (int k = 0; k < padding; k++)
{
fputc(0x00, outptr);
}
}
// Free memory for image
free(image);
// Close files
fclose(inptr);
fclose(outptr);
return 0;
}
+8
View File
@@ -0,0 +1,8 @@
#include <stdio.h>
#include <cs50.h>
int main(void)
{
string name = get_string("What is your Name? ");
printf("hello, %s\n ", name);
}
+4
View File
@@ -0,0 +1,4 @@
# TODO
print('What is your name?')
name = input()
print(f'hello, {name}')
+350
View File
@@ -0,0 +1,350 @@
#include "helpers.h"
#include <math.h>
#include <stdio.h>
// Convert image to grayscale
// The function grayscale takes three arguments: height and width, which are integers representing the dimensions of an image, and image, which is a two-dimensional array of type RGBTRIPLE representing the pixels of the image. The function converts the image to grayscale by setting the red, green, and blue components of each pixel to the mean of the original values. The result is stored back in the image array. The function uses nested loops to iterate over all pixels in the image. For each pixel, it calculates the mean of its red, green, and blue components using the formula (red + green + blue) / 3, and rounds the result to the nearest integer using the round function. Then it sets the red, green, and blue components of the pixel to the calculated mean. Finally, the function returns void, indicating that it does not return any value.
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int mean = (int) round((image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtBlue) / 3.0);
image[i][j].rgbtRed = mean;
image[i][j].rgbtGreen = mean;
image[i][j].rgbtBlue = mean;
}
}
return;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int sepiaRed = (int) round(.393 * image[i][j].rgbtRed + .769 * image[i][j].rgbtGreen + .189 * image[i][j].rgbtBlue) ;
int sepiaGreen = (int) round(.349 * image[i][j].rgbtRed + .686 * image[i][j].rgbtGreen + .168 * image[i][j].rgbtBlue);
int sepiaBlue = (int) round(.272 * image[i][j].rgbtRed + .534 * image[i][j].rgbtGreen + .131 * image[i][j].rgbtBlue);
if (sepiaRed > 255)
{
sepiaRed = 255;
}
if (sepiaGreen > 255)
{
sepiaGreen = 255;
}
if (sepiaBlue > 255)
{
sepiaBlue = 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtGreen = sepiaGreen;
image[i][j].rgbtBlue = sepiaBlue;
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width / 2; j++)
{
RGBTRIPLE og = image[i][j];
image[i][j] = image[i][width - 1 - j];
image[i][width - 1 - j] = og;
}
}
return;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE og[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
og[i][j] = image[i][j];
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// inbetween
if (i >= 1 && i < height - 1 && j >= 1 && j < width - 1)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i - 1][j - 1].rgbtRed +
og[i - 1][j].rgbtRed +
og[i - 1][j + 1].rgbtRed +
og[i][j - 1].rgbtRed +
og[i][j + 1].rgbtRed +
og[i + 1][j - 1].rgbtRed +
og[i + 1][j].rgbtRed +
og[i + 1][j + 1].rgbtRed) / 9.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i - 1][j - 1].rgbtGreen +
og[i - 1][j].rgbtGreen +
og[i - 1][j + 1].rgbtGreen +
og[i][j - 1].rgbtGreen +
og[i][j + 1].rgbtGreen +
og[i + 1][j - 1].rgbtGreen +
og[i + 1][j].rgbtGreen +
og[i + 1][j + 1].rgbtGreen) / 9.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i - 1][j - 1].rgbtBlue +
og[i - 1][j].rgbtBlue +
og[i - 1][j + 1].rgbtBlue +
og[i][j - 1].rgbtBlue +
og[i][j + 1].rgbtBlue +
og[i + 1][j - 1].rgbtBlue +
og[i + 1][j].rgbtBlue +
og[i + 1][j + 1].rgbtBlue) / 9.0);
}
// Corners
// upper left corner
if (i == 0 && j == 0)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i][j + 1].rgbtRed +
og[i + 1][j].rgbtRed +
og[i + 1][j + 1].rgbtRed) / 4.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i][j + 1].rgbtGreen +
og[i + 1][j].rgbtGreen +
og[i + 1][j + 1].rgbtGreen) / 4.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i][j + 1].rgbtBlue +
og[i + 1][j].rgbtBlue +
og[i + 1][j + 1].rgbtBlue) / 4.0);
}
// upper right corner
if (i == 0 && j == width - 1)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i][j - 1].rgbtRed +
og[i + 1][j - 1].rgbtRed +
og[i + 1][j].rgbtRed) / 4.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i][j - 1].rgbtGreen +
og[i + 1][j - 1].rgbtGreen +
og[i + 1][j].rgbtGreen) / 4.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i][j - 1].rgbtBlue +
og[i + 1][j - 1].rgbtBlue +
og[i + 1][j].rgbtBlue) / 4.0);
}
// lower left corner
if (i == height - 1 && j == 0)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i - 1][j].rgbtRed +
og[i - 1][j + 1].rgbtRed +
og[i][j + 1].rgbtRed) / 4.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i - 1][j].rgbtGreen +
og[i - 1][j + 1].rgbtGreen +
og[i][j + 1].rgbtGreen) / 4.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i - 1][j].rgbtBlue +
og[i - 1][j + 1].rgbtBlue +
og[i][j + 1].rgbtBlue) / 4.0);
}
// lower right corner
if (i == height - 1 && j == width - 1)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i - 1][j - 1].rgbtRed +
og[i - 1][j].rgbtRed +
og[i][j - 1].rgbtRed) / 4.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i - 1][j - 1].rgbtGreen +
og[i - 1][j].rgbtGreen +
og[i][j - 1].rgbtGreen) / 4.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i - 1][j - 1].rgbtBlue +
og[i - 1][j].rgbtBlue +
og[i][j - 1].rgbtBlue) / 4.0);
}
// Sides
// Upper side
if (i == 0 && j > 0 && j < width - 1)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i][j - 1].rgbtRed +
og[i][j + 1].rgbtRed +
og[i + 1][j - 1].rgbtRed +
og[i + 1][j].rgbtRed +
og[i + 1][j + 1].rgbtRed) / 6.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i][j - 1].rgbtGreen +
og[i][j + 1].rgbtGreen +
og[i + 1][j - 1].rgbtGreen +
og[i + 1][j].rgbtGreen +
og[i + 1][j + 1].rgbtGreen) / 6.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i][j - 1].rgbtBlue +
og[i][j + 1].rgbtBlue +
og[i + 1][j - 1].rgbtBlue +
og[i + 1][j].rgbtBlue +
og[i + 1][j + 1].rgbtBlue) / 6.0);
}
// lower side
if (i == height - 1 && j > 0 && j < width - 1)
{
image[i][j].rgbtRed = (int)round((og[i][j].rgbtRed +
og[i - 1][j - 1].rgbtRed +
og[i - 1][j].rgbtRed +
og[i - 1][j + 1].rgbtRed +
og[i][j - 1].rgbtRed +
og[i][j + 1].rgbtRed) / 6.0);
image[i][j].rgbtGreen = (int)round((og[i][j].rgbtGreen +
og[i - 1][j - 1].rgbtGreen +
og[i - 1][j].rgbtGreen +
og[i - 1][j + 1].rgbtGreen +
og[i][j - 1].rgbtGreen +
og[i][j + 1].rgbtGreen) / 6.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i - 1][j - 1].rgbtBlue +
og[i - 1][j].rgbtBlue +
og[i - 1][j + 1].rgbtBlue +
og[i][j - 1].rgbtBlue +
og[i][j + 1].rgbtBlue) / 6.0);
}
// left side
if (i > 0 && i < height - 1 && j == 0)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i - 1][j].rgbtRed +
og[i - 1][j + 1].rgbtRed +
og[i][j + 1].rgbtRed +
og[i + 1][j].rgbtRed +
og[i + 1][j + 1].rgbtRed) / 6.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i - 1][j].rgbtGreen +
og[i - 1][j + 1].rgbtGreen +
og[i][j + 1].rgbtGreen +
og[i + 1][j].rgbtGreen +
og[i + 1][j + 1].rgbtGreen) / 6.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i - 1][j].rgbtBlue +
og[i - 1][j + 1].rgbtBlue +
og[i][j + 1].rgbtBlue +
og[i + 1][j].rgbtBlue +
og[i + 1][j + 1].rgbtBlue) / 6.0);
}
// right side
if (i > 0 && i < height - 1 && j == width - 1)
{
image[i][j].rgbtRed = (int) round((og[i][j].rgbtRed +
og[i - 1][j - 1].rgbtRed +
og[i - 1][j].rgbtRed +
og[i][j - 1].rgbtRed +
og[i + 1][j - 1].rgbtRed +
og[i + 1][j].rgbtRed) / 6.0);
image[i][j].rgbtGreen = (int) round((og[i][j].rgbtGreen +
og[i - 1][j - 1].rgbtGreen +
og[i - 1][j].rgbtGreen + og[i][j - 1].rgbtGreen +
og[i + 1][j - 1].rgbtGreen + og[i + 1][j].rgbtGreen) / 6.0);
image[i][j].rgbtBlue = (int) round((og[i][j].rgbtBlue +
og[i - 1][j - 1].rgbtBlue +
og[i - 1][j].rgbtBlue +
og[i][j - 1].rgbtBlue +
og[i + 1][j - 1].rgbtBlue +
og[i + 1][j].rgbtBlue) / 6.0);
}
}
}
return;
}
//00 = [i - 1][j - 1]
//01 = [i - 1][j]
//02 = [i - 1][j + 1]
//10 = [i][j - 1]
//12 = [i][j + 1]
//20 = [i + 1][j - 1]
//21 = [i + 1][j]
//22 = [i + 1][j + 1]
// Dazwischen
//00 = [i - 1][j - 1]
//01 = [i - 1][j]
//02 = [i - 1][j + 1]
//10 = [i][j - 1]
//12 = [i][j + 1]
//20 = [i + 1][j - 1]
//21 = [i + 1][j]
//22 = [i + 1][j + 1]
//Ecke Links oben
//12 [i][j + 1]
//21 [i + 1][j]
//22 [i + 1][j + 1]
//Ecke Rechts oben
//10 [i][j - 1]
//20 [i + 1][j - 1]
//21 [i + 1][j]
//Ecke Links unten
//01 [i - 1][j]
//02 [i - 1][j + 1]
//12 [i][j + 1]
//Ecke Rechts unten
//00 [i - 1][j - 1]
//01 [i - 1][j]
//10 [i][j - 1]
// Seite oben
//10 [i][j - 1]
//12 [i][j + 1]
//20 [i + 1][j - 1]
//21 [i + 1][j]
//22 [i + 1][j + 1]
// Seite unten
//00 [i - 1][j - 1]
//01 [i - 1][j]
//02 [i - 1][j + 1]
//10 [i][j - 1]
//12 [i][j + 1]
// Seite links
//01 [i - 1][j]
//02 [i - 1][j + 1]
//12 [i][j + 1]
//21 [i + 1][j]
//22 [i + 1][j + 1]
// Seite rechts
//00 [i - 1][j - 1]
//01 [i - 1][j]
//10 [i][j - 1]
//20 [i + 1][j - 1]
//21 [i + 1][j]
+13
View File
@@ -0,0 +1,13 @@
#include "bmp.h"
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width]);
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width]);
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width]);
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width]);
+126
View File
@@ -0,0 +1,126 @@
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct person
{
struct person *parents[2];
char alleles[2];
} person;
const int GENERATIONS = 3;
const int INDENT_LENGTH = 4;
person *create_family(int generations);
void print_family(person *p, int generation);
void free_family(person *p);
char random_allele();
int main(void)
{
srand(time(0));
person *p = create_family(GENERATIONS);
print_family(p, 0);
free_family(p);
}
person *create_family(int generations)
{
person *p = malloc(sizeof(person));
if (generations > 1)
{
person *parent0 = create_family(generations - 1);
person *parent1 = create_family(generations - 1);
p->parents[0] = parent0;
p->parents[1] = parent1;
if (rand() % 2)
{
p->alleles[0] = parent0->alleles[rand() % 2];
p->alleles[1] = parent1->alleles[rand() % 2];
}
else
{
p->alleles[1] = parent0->alleles[rand() % 2];
p->alleles[0] = parent1->alleles[rand() % 2];
}
}
else
{
p->parents[0] = NULL;
p->parents[1] = NULL;
p->alleles[0] = random_allele();
p->alleles[1] = random_allele();
}
return p;
}
void free_family(person *p)
{
if (p == NULL)
{
return;
}
free_family(p->parents[0]);
free_family(p->parents[1]);
free(p);
}
void print_family(person *p, int generation)
{
if (p == NULL)
{
return;
}
for (int i = 0; i < generation * INDENT_LENGTH; i++)
{
printf(" ");
}
if (generation == 0)
{
printf("Child (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
}
else if (generation == 1)
{
printf("Parent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
}
else
{
for (int i = 0; i < generation - 2; i++)
{
printf("Great-");
}
printf("Grandparent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
}
print_family(p->parents[0], generation + 1);
print_family(p->parents[1], generation + 1);
}
char random_allele()
{
int r = rand() % 3;
if (r == 0)
{
return 'A';
}
else if (r == 1)
{
return 'B';
}
else
{
return 'O';
}
}
+25
View File
@@ -0,0 +1,25 @@
// hastable
#include<ctype.h>
typedef struct node {
char *name;
char *number;
struct Node *next;
} Node ;
node *table[26];
unsigned int hash(const char *word){
return toupper(word[0]) - 'A';
}
// tries
typedef struct node{
struct node *children[26];
char *number;
} Node;
node *trie;
+46
View File
@@ -0,0 +1,46 @@
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int size;
int spaces;
int hashes;
// Asking for size
do
{
size = get_int("Size: ");
}
while (size < 1 || size > 8);
// Building
for (int i = 0; i < size; i++)
{
// left spaces
for (spaces = (size - i); spaces >= 2; spaces--)
{
printf(" ");
}
// hashes
for (hashes = 0; hashes <= i; hashes++)
{
printf("#");
}
// middle spaces
printf(" ");
// hashes
for (hashes = 0; hashes <= i; hashes++)
{
printf("#");
}
// next line
printf("\n");
}
}
+14
View File
@@ -0,0 +1,14 @@
# TODO
print("Height: ")
while True:
try:
size = int(input())
if 1 <= size <= 8:
break
else:
print("Height between 1 and 8: ")
except ValueError:
print("Height with numeric value: ")
for i in range(1, size+1):
print(((size - i) * ' ') + (i * '#'))
+105
View File
@@ -0,0 +1,105 @@
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes += 1;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int winner = 0;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > winner)
{
winner = candidates[i].votes;
}
}
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes == winner)
{
printf("%s\n", candidates[i].name);
}
}
return;
}
+38
View File
@@ -0,0 +1,38 @@
#include <cs50.h>
#include <stdio.h>
int main()
{
// TODO: Prompt for start size
int start;
do
{
start = get_int("Start size over 9: ");
}
while (start < 9);
// TODO: Prompt for end size
int end;
do
{
end = get_int("End size: ");
}
while (end < start);
// TODO: Calculate number of years until we reach threshold
int years = 0;
while (start < end)
{
start = start + (start / 3) - (start / 4);
years++;
}
// TODO: Print number of years
printf("Years: %i\n", years);
}
+55
View File
@@ -0,0 +1,55 @@
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main(void)
{
// Get Text
string text = get_string("Text: ");
// Letter, word, sentence count
double lettercount = 0;
double wordcount = 1;
double sentencecount = 0;
for (int i = 0, len = strlen(text); i < len; i++)
{
if ((text[i] >= 65 && text[i] <= 90) || (text[i] >= 97 && text[i] <= 122))
{
lettercount += 1;
}
else if (text[i] == 32)
{
wordcount += 1;
}
else if (text[i] == 33 || text[i] == 63 || text[i] == 46)
{
sentencecount += 1;
}
else
{
continue;
}
}
// Calculate Index
double L = lettercount / wordcount * 100.0;
double S = sentencecount / wordcount * 100.0;
double index = 0.0588 * L - 0.296 * S - 15.8;
// Print conditions
if (index <= 1)
{
printf("Before Grade 1\n");
}
else if (index >= 16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n", (int) round(index));
}
}
+31
View File
@@ -0,0 +1,31 @@
# TODO
print('Text: ')
text = str(input())
lettercount = 0
wordcount = 0
sentencecount = 0
for i in range(len(text)):
if (65 <= ord(text[i]) <= 90) or (97 <= ord(text[i]) <= 122):
lettercount += 1
elif ord(text[i]) == 32:
wordcount += 1
elif ord(text[i]) in [33, 63, 46]:
sentencecount += 1
else:
continue
wordcount += 1
L = lettercount / wordcount * 100
S = sentencecount / wordcount * 100
index = 0.0588 * L - 0.296 * S - 15.8
if index <= 1:
print("Before Grade 1")
elif index >= 16:
print("Grade 16+")
else:
print(f"Grade {round(index)}")
+51
View File
@@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover IMAGE\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
FILE *img = NULL;
BYTE buffer[512];
int img_number = 0;
char img_name[8];
while (fread(&buffer, 512, 1, file) == 1)
{
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
if (!(img_number == 0))
{
fclose(img);
}
sprintf(img_name, "%03i.jpg", img_number);
img = fopen(img_name, "w");
img_number ++;
}
if (!(img_number == 0))
{
fwrite(&buffer, 512, 1, img);
}
}
fclose(file);
fclose(img);
return 0;
}
+227
View File
@@ -0,0 +1,227 @@
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max voters and candidates
#define MAX_VOTERS 100
#define MAX_CANDIDATES 9
// preferences[i][j], j is the preference for voter i
int preferences[MAX_VOTERS][MAX_CANDIDATES];
// Candidates have name, vote count, eliminated status
typedef struct
{
string name;
int votes;
bool eliminated;
}
candidate;
// Array of candidates
candidate candidates[MAX_CANDIDATES];
// Numbers of voters and candidates
int voter_count;
int candidate_count;
// Function prototypes
bool vote(int voter, int rank, string name);
void tabulate(void);
bool print_winner(void);
int find_min(void);
bool is_tie(int min);
void eliminate(int min);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: runoff [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX_CANDIDATES)
{
printf("Maximum number of candidates is %i\n", MAX_CANDIDATES);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
candidates[i].eliminated = false;
}
voter_count = get_int("Number of voters: ");
if (voter_count > MAX_VOTERS)
{
printf("Maximum number of voters is %i\n", MAX_VOTERS);
return 3;
}
// Keep querying for votes
for (int i = 0; i < voter_count; i++)
{
// Query for each rank
for (int j = 0; j < candidate_count; j++)
{
string name = get_string("Rank %i: ", j + 1);
// Record vote, unless it's invalid
if (!vote(i, j, name))
{
printf("Invalid vote.\n");
return 4;
}
}
printf("\n");
}
// Keep holding runoffs until winner exists
while (true)
{
// Calculate votes given remaining candidates
tabulate();
// Check if election has been won
bool won = print_winner();
if (won)
{
break;
}
// Eliminate last-place candidates
int min = find_min();
bool tie = is_tie(min);
// If tie, everyone wins
if (tie)
{
for (int i = 0; i < candidate_count; i++)
{
if (!candidates[i].eliminated)
{
printf("%s\n", candidates[i].name);
}
}
break;
}
// Eliminate anyone with minimum number of votes
eliminate(min);
// Reset vote counts back to zero
for (int i = 0; i < candidate_count; i++)
{
candidates[i].votes = 0;
}
}
return 0;
}
// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
preferences[voter][rank] = i;
return true;
}
}
return false;
}
// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
for (int i = 0; i < voter_count; i++)
{
for (int j = 0; j < candidate_count; j++)
{
if (preferences[i][0] == j && candidates[j].eliminated == false)
{
candidates[j].votes += 1;
}
}
}
return;
}
// Print the winner of the election, if there is one
bool print_winner(void)
{
int winner = 0;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > winner)
{
winner = candidates[i].votes;
}
}
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes == winner && candidates[i].votes > (voter_count / 2))
{
printf("%s\n", candidates[i].name);
return true;
}
}
return false;
}
// Return the minimum number of votes any remaining candidate has
int find_min(void)
{
int min = voter_count;
for (int i = 0; i < candidate_count; i++)
{
if ( candidates[i].votes < min && candidates[i].eliminated == false)
{
min = candidates[i].votes;
}
}
return min;
}
// Return true if the election is tied between all candidates, false otherwise
bool is_tie(int min)
{
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > min && candidates[i].eliminated == false)
{
return false;
}
}
return true;
}
// Eliminate the candidate (or candidates) in last place
void eliminate(int min)
{
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes <= min && candidates[i].eliminated == false)
{
candidates[i].eliminated = true;
}
}
return;
}
+53
View File
@@ -0,0 +1,53 @@
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
int compute_score(string word);
int main(void)
{
// Get input words from both players
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");
// Score both words
int score1 = compute_score(word1);
int score2 = compute_score(word2);
// TODO: Print the winner
if (score1 > score2)
{
printf("Player 1 wins!");
}
else if (score1 < score2)
{
printf("Player 2 wins!");
}
else
{
printf("Tie!");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
int score = 0;
for (int i = 0, len = strlen(word); i < len; i++)
{
if (isupper(word[i]))
{
score += POINTS[word[i] - 'A'];
}
else if (islower(word[i]))
{
score += POINTS[word[i] - 'a'];
}
}
return score;
}
+196
View File
@@ -0,0 +1,196 @@
// Implements a spell-checker
#include <ctype.h>
#include <stdio.h>
#include <sys/resource.h>
#include <sys/time.h>
#include "dictionary.h"
// Undefine any definitions
#undef calculate
#undef getrusage
// Default dictionary
#define DICTIONARY "dictionaries/large"
// Prototype
double calculate(const struct rusage *b, const struct rusage *a);
int main(int argc, char *argv[])
{
// Check for correct number of args
if (argc != 2 && argc != 3)
{
printf("Usage: ./speller [DICTIONARY] text\n");
return 1;
}
// Structures for timing data
struct rusage before, after;
// Benchmarks
double time_load = 0.0, time_check = 0.0, time_size = 0.0, time_unload = 0.0;
// Determine dictionary to use
char *dictionary = (argc == 3) ? argv[1] : DICTIONARY;
// Load dictionary
getrusage(RUSAGE_SELF, &before);
bool loaded = load(dictionary);
getrusage(RUSAGE_SELF, &after);
// Exit if dictionary not loaded
if (!loaded)
{
printf("Could not load %s.\n", dictionary);
return 1;
}
// Calculate time to load dictionary
time_load = calculate(&before, &after);
// Try to open text
char *text = (argc == 3) ? argv[2] : argv[1];
FILE *file = fopen(text, "r");
if (file == NULL)
{
printf("Could not open %s.\n", text);
unload();
return 1;
}
// Prepare to report misspellings
printf("\nMISSPELLED WORDS\n\n");
// Prepare to spell-check
int index = 0, misspellings = 0, words = 0;
char word[LENGTH + 1];
// Spell-check each word in text
char c;
while (fread(&c, sizeof(char), 1, file))
{
// Allow only alphabetical characters and apostrophes
if (isalpha(c) || (c == '\'' && index > 0))
{
// Append character to word
word[index] = c;
index++;
// Ignore alphabetical strings too long to be words
if (index > LENGTH)
{
// Consume remainder of alphabetical string
while (fread(&c, sizeof(char), 1, file) && isalpha(c));
// Prepare for new word
index = 0;
}
}
// Ignore words with numbers (like MS Word can)
else if (isdigit(c))
{
// Consume remainder of alphanumeric string
while (fread(&c, sizeof(char), 1, file) && isalnum(c));
// Prepare for new word
index = 0;
}
// We must have found a whole word
else if (index > 0)
{
// Terminate current word
word[index] = '\0';
// Update counter
words++;
// Check word's spelling
getrusage(RUSAGE_SELF, &before);
bool misspelled = !check(word);
getrusage(RUSAGE_SELF, &after);
// Update benchmark
time_check += calculate(&before, &after);
// Print word if misspelled
if (misspelled)
{
printf("%s\n", word);
misspellings++;
}
// Prepare for next word
index = 0;
}
}
// Check whether there was an error
if (ferror(file))
{
fclose(file);
printf("Error reading %s.\n", text);
unload();
return 1;
}
// Close text
fclose(file);
// Determine dictionary's size
getrusage(RUSAGE_SELF, &before);
unsigned int n = size();
getrusage(RUSAGE_SELF, &after);
// Calculate time to determine dictionary's size
time_size = calculate(&before, &after);
// Unload dictionary
getrusage(RUSAGE_SELF, &before);
bool unloaded = unload();
getrusage(RUSAGE_SELF, &after);
// Abort if dictionary not unloaded
if (!unloaded)
{
printf("Could not unload %s.\n", dictionary);
return 1;
}
// Calculate time to unload dictionary
time_unload = calculate(&before, &after);
// Report benchmarks
printf("\nWORDS MISSPELLED: %d\n", misspellings);
printf("WORDS IN DICTIONARY: %d\n", n);
printf("WORDS IN TEXT: %d\n", words);
printf("TIME IN load: %.2f\n", time_load);
printf("TIME IN check: %.2f\n", time_check);
printf("TIME IN size: %.2f\n", time_size);
printf("TIME IN unload: %.2f\n", time_unload);
printf("TIME IN TOTAL: %.2f\n\n",
time_load + time_check + time_size + time_unload);
// Success
return 0;
}
// Returns number of seconds between b and a
double calculate(const struct rusage *b, const struct rusage *a)
{
if (b == NULL || a == NULL)
{
return 0.0;
}
else
{
return ((((a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec) -
(b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec)) +
((a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec) -
(b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec)))
/ 1000000.0);
}
}
+30
View File
@@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
int BLOCK_SIZE = 512;
typedef uint8_t BYTE;
BYTE buffer[BLOCK_SIZE];
FILE *file = fopen("card.raw", "r");
if (argc != 2)
{
printf("Usage: ./recover card.raw\n");
return 1;
}
while (fread(&buffer, 1, BLOCK_SIZE, file) == BLOCK_SIZE)
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
printf("%i",buffer)
}
}
fclose(file);
return 0;
}
+69
View File
@@ -0,0 +1,69 @@
# Simulate a sports tournament
import csv
import sys
import random
# Number of simluations to run
N = 1000
def main():
# Ensure correct usage
if len(sys.argv) != 2:
sys.exit("Usage: python tournament.py FILENAME")
teams = []
counts = {}
# TODO: Read teams into memory from file
with open(sys.argv[1], 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
teams.append({'team': row['team'], 'rating': int(row['rating'])})
counts[row['team']] = 0
# TODO: Simulate N tournaments and keep track of win counts
for _ in range(N):
winner = simulate_tournament(teams.copy())
counts[winner] += 1
# Print each team's chances of winning, according to simulation
for team in sorted(counts, key=lambda team: counts[team], reverse=True):
print(f"{team}: {counts[team] * 100 / N:.1f}% chance of winning")
def simulate_game(team1, team2):
"""Simulate a game. Return True if team1 wins, False otherwise."""
rating1 = team1["rating"]
rating2 = team2["rating"]
probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600))
return random.random() < probability
def simulate_round(teams):
"""Simulate a round. Return a list of winning teams."""
winners = []
# Simulate games for all pairs of teams
for i in range(0, len(teams), 2):
if simulate_game(teams[i], teams[i + 1]):
winners.append(teams[i])
else:
winners.append(teams[i + 1])
return winners
def simulate_tournament(teams):
"""Simulate a tournament. Return name of winning team."""
# TODO
while len(teams) > 1:
teams = simulate_round(teams)
return teams[0]['team']
if __name__ == "__main__":
main()