Skip to content

Instantly share code, notes, and snippets.

@Charlesmendez
Last active April 8, 2021 02:16
Show Gist options
  • Save Charlesmendez/489721b42013664d5b1fb8e18715271d to your computer and use it in GitHub Desktop.
Save Charlesmendez/489721b42013664d5b1fb8e18715271d to your computer and use it in GitHub Desktop.
CS50 Problem Sets *SOLVED
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// prompts the user for a credit card number
long num;
num = get_long("Enter card number: ");
// do a checksum to check validity
int index = 0;
int digit;
int position;
int multiplication;
int addition = 0;
int remainder;
int last_num;
int firstDigit;
//int second_num;
int second = 0;
int temp2last;
int second2last;
long originalnum = num;
while (num > 0)
{
digit = num % 10;
num /= 10;
//printf("(%i) %i ", index, digit);
index ++;
position = index % 2;
//printf("%i", position);
if (position == 0)
{
multiplication = digit * 2;
//printf(" %i ", multiplication);
if (multiplication > 9)
{
// step 1: This is a 2 digit number. Separate the 2 digits
int first_digit = multiplication / 10;
//printf("the first digit is %i", first_digit);
// step 2: Look at the first digit and add it to the second digit
multiplication = first_digit + (multiplication % 10);
// step 3: Give a final number that we can pass to addition
}
addition += multiplication;
}
else
{
addition += digit;
//second_num = digit % 10;
//printf("%i", second_num);
}
}
// printf("\n");
//printf("addition; %i\n", addition);
//printf("digit; %i\n", digit);
//printf("second; %i\n", second);
// 369421438430814
long thiscard = originalnum;
// find the first 2 nums of the credict card num.
while (thiscard >= 100)
{
// get rid of the last digit
thiscard = thiscard / 10;
}
// what digits are left?
// printf("thiscard; %li", thiscard);
//printf("index; %i", index);
//printf("\n");
if (((addition % 10 == 0) && (digit == 4)) && (index == 16 || index == 13))
{
printf("VISA");
}
else if (((addition % 10 == 0 && index == 15) && thiscard == 34) || thiscard == 37)
{
printf("AMEX");
}
else if ((((((addition % 10 == 0 && index == 16) && thiscard == 51) || thiscard == 52) || thiscard == 53) || thiscard == 54) || thiscard == 55)
{
printf("MASTERCARD");
}
else
{
printf("INVALID");
}
printf("\n");
}
# prompts the user for a credit card number
num = input("Enter card number: ")
# reverses the order
credit_card = num[::-1]
# converts the list to integer
int_list = []
for i in credit_card:
int_list.append(int(i))
# Multiply every other number by 2
second_digit = []
for i in range(len(int_list)):
if i % 2 == 1:
second_digit.append(int_list[i]*2)
else:
second_digit.append(int_list[i])
# Sum all the numbers
digit_sum = []
for i in second_digit:
if i < 10:
digit_sum.append(i)
else:
addition = (i % 10) + (i // 10)
digit_sum.append(addition)
total_sum = sum(digit_sum)
final_sum = []
for i in range(len(int_list)):
if i % 2 == 0:
final_sum.append(int_list[i])
sum_of_nums_plus_totalsum = sum(final_sum) + total_sum
# Conditions to check for type of card
if sum_of_nums_plus_totalsum % 10 == 0 and len(num) == 13 or len(num) == 16 and num[0] == '4':
print("VISA\n")
elif len(num) == 16:
if sum_of_nums_plus_totalsum % 10 == 0 and num[0] == '5' and num[1] >= '1' or num[1] <= '5':
print("MASTERCARD\n")
elif sum_of_nums_plus_totalsum % 10 == 0 and len(num) == 15 and num[0] == '3' and num[1] == '4' or num[1] == '7':
print("AMEX\n")
else:
print("INVALID\n")
import csv
import sys
import random
# expect 2 line arguments. If not print an error
# first command-line argument the name of a CSV file containing the STR counts for a list of
# individuals and should require as its second command-line argument the name of a text file containing the DNA sequence to identify.
def main():
# Ensure correct usage
if len(sys.argv) != 3:
sys.exit("Usage: dna.py FILE.csv FILE.txt")
individuals = []
dna = []
# Your program should open the CSV file and read its contents into memory.
# You may assume that the first row of the CSV file will be the column names. The first column will be the word name and the
# remaining columns will be the STR sequences themselves.
with open(sys.argv[1]) as file:
reader = csv.DictReader(file)
for row in reader:
individuals.append(row)
# Get only the STR
all_patterns = []
for individual in individuals:
patterns = list(set(individual.keys()) - {'name'})
all_patterns.extend(patterns)
# Your program should open the DNA sequence and read its contents into memory.
file2 = open(sys.argv[2], 'r')
while 1:
# read by character
char = file2.read(1)
dna.append(char)
if not char:
break
# For each of the STRs (from the first line of the CSV file), your program should compute the longest run
# of consecutive repeats of the STR in the DNA sequence to identify.
for str_string in patterns:
dna_result = str_compute(str_string, dna)
# If the STR counts match exactly with any of the individuals in the CSV file, your program should print out the name of the matching individual.
# If the STR counts do not match exactly with any of the individuals in the CSV file, your program should print "No match"
result = []
for str_string in patterns:
dna_result = str_compute(str_string, dna)
result.append(dna_result)
new_result = dict(zip(patterns, result))
# iterate each individual
for individual in individuals:
# first of all, let's assume that this guy fits the results
does_it_fit = True
for k in new_result:
if int(individual[k]) != new_result[k]:
does_it_fit = False
if does_it_fit == True:
print(individual['name'])
else:
print('No match')
def str_compute(str_string, dna):
index_list = {}
seq = []
for char in str_string:
seq.append(char)
seq_len = len(seq)
for i in range(len(dna)):
if dna[i] == seq[0]:
if dna[i:i+seq_len] == seq:
index_list[i] = 1
else:
index_list[i] = 0
else:
index_list[i] = 0
lenSeq = len(seq)
for i in range(lenSeq, len(index_list)):
if index_list[i] == 1 and index_list[i-lenSeq] > 0:
index_list[i] = index_list[i-lenSeq] + 1
return max(index_list.values())
if __name__ == "__main__":
main()
The THIEF is: Ernest
The thief ESCAPED TO: London
The ACCOMPLICE is: Berthold
-- Keep a log of any SQL queries you execute as you solve the mystery.
-- The theft took place July 28
-- Theft took place on Chamberlin street
-- Answers to find: Who the thief is? Where the thief escaped to? Who helped the thief escape out of town.
-- Query to list all the tables in the database
.tables
-- Query to understand the crime_scene_reports table. Start by looking for a crime scene report that matches the date and the location of the crime
.schema crime_scene_reports
-- Query the description of the crime scene on the date and street
SELECT description FROM crime_scene_reports WHERE month = 7 and day = 28 AND street = 'Chamberlin Street';
-- No we know this: Theft of the CS50 duck took place at 10:15am at the Chamberlin Street courthouse. Interviews were conducted today
-- with three witnesses who were present at the time — each of their interview transcripts mentions the courthouse.
-- Query the schema of the interviews table to check if I can get more info
.schema interviews
-- Check all the data in the table. I want to make sure I understand what's written in full and make sure I don't miss anything.
SELECT * FROM interviews;
-- Tips from the interviews:
-- Sometime within ten minutes of the theft (theft occured at 10:15am), I saw the thief get into a car in the courthouse parking lot and drive away.
-- If you have security footage from the courthouse parking lot, you might want to look for cars that left the parking lot in that time frame.
-- I don't know the thief's name, but it was someone I recognized. Earlier this morning, before I arrived at the courthouse,
-- I was walking by the ATM on Fifer Street and saw the thief there withdrawing some money.
-- As the thief was leaving the courthouse, they called someone who talked to them for less than a minute. In the call, I heard the thief
-- say that they were planning to take the earliest flight out of Fiftyville tomorrow. The thief then asked the person on the other end of
-- the phone to purchase the flight ticket.
-- Let's check the schema of the atm_transactions
.schema atm_transactions
-- Let's explore bank accounts from atm transactions at the time
SELECT account_number, id FROM atm_transactions WHERE month = 7 AND day = 28 AND atm_location = 'Fifer Street';
-- Bank accounts we are down to:
-- 28500762 | 246
-- 28296815 | 264
-- 76054385 | 266
-- 49610011 | 267
-- 16153065 | 269
-- 86363979 | 275
-- 25506511 | 288
-- 81061156 | 313
-- 26013199 | 336
-- Let's explore bank accounts schema
.schema bank_accounts
-- Let's explore possible names
SELECT name FROM people WHERE id IN (SELECT account_number FROM bank_accounts WHERE account_number IN (SELECT account_number FROM atm_transactions WHERE month = 7 AND day = 28 AND atm_location = 'Fifer Street'));
-- Let's check the schema of the security logs
.schema courthouse_security_logs
-- Let's do a query to get the license plate of cars that left between 10 and 11 am
SELECT id, license_plate, activity FROM courthouse_security_logs WHERE year = 2020 AND month = 7 AND day = 28 AND hour >= 10 AND hour <= 11 AND activity = 'exit';
-- Now we have this license plates associated to ids:
-- 260 | 5P2BI95 | exit
-- 261 | 94KL13X | exit
-- 262 | 6P58WS2 | exit
-- 263 | 4328GD8 | exit
-- 264 | G412CB7 | exit
-- 265 | L93JTIZ | exit
-- 266 | 322W7JE | exit
-- 267 | 0NTHK55 | exit
-- 268 | 1106N58 | exit
-- Explore posible names:
SELECT name FROM people WHERE license_plate IN (SELECT license_plate FROM courthouse_security_logs WHERE year = 2020 AND month = 7 AND day = 28 AND hour >= 10 AND hour <= 11 AND activity = 'exit');
-- Possible thiefs
-- Patrick
-- Amber
-- Elizabeth
-- Roger
-- Madison
-- Danielle
-- Russell
-- Evelyn
-- Ernest
-- let's check who of this people withdrew money
SELECT name FROM people WHERE id IN (SELECT person_id FROM bank_accounts WHERE account_number IN (SELECT account_number FROM atm_transactions WHERE month = 7 AND day = 28 AND atm_location = 'Fifer Street'));
Results:
-- Bobby
-- Elizabeth
-- Victoria
-- Madison
-- Roy
-- Danielle
-- Russell
-- Ernest
-- Robert
-- Possible thiefs that exited the courthouse and withdrew money:
-- Elizabeth
-- Madison
-- Danielle
-- Ernest
-- Let's get the id's of those people
SELECT id, name FROM people WHERE name LIKE 'Elizabeth' OR name LIKE 'Madison' OR name LIKE 'Danielle' OR name LIKE 'Ernest';
-- 396669 | Elizabeth
-- 449774 | Madison
-- 467400 | Danielle
-- 686048 | Ernest
-- Now let's see who flew out of Fiftyville and to where
SELECT name FROM people WHERE passport_number IN (SELECT passport_number FROM passengers WHERE flight_id IN (SELECT id FROM flights WHERE year = 2020 AND month = 7 AND day = 29 AND hour >= 8 OR hour <= 11 AND origin_airport_id = 8));
-- Seems we are down just to
-- Madison
-- Danielle
-- Ernest
--phone_call schema
-- Phone calls between 10 and 11 and who?
SELECT name, phone_number FROM people WHERE phone_number in (SELECT caller FROM phone_calls WHERE year = 2020 AND month = 7 AND day = 28);
-- Madison
-- Ernest
-- Now that I am down to 2 names let's see if I can narrow down based on a call of less than a minute and the car exiting closer to 10:15.
-- Phone call
SELECT name, phone_number FROM people WHERE phone_number in (SELECT caller FROM phone_calls WHERE year = 2020 AND month = 7 AND day = 28 AND duration < 60);
-- Madison and Ernest still on the list
-- Exiting the courthouse
SELECT name FROM people WHERE license_plate IN (SELECT license_plate FROM courthouse_security_logs WHERE year = 2020 AND month = 7 AND day = 28 AND hour >= 10 AND minute <= 30 AND activity = 'exit');
-- Ernest is the thief.
-- Let's check who called Ernest
SELECT caller, receiver FROM phone_calls WHERE year = 2020 AND month = 7 AND day = 28 AND duration < 60 AND caller = '(367) 555-5533' ;
-- Query to find the accomplice
SELECT name FROM people WHERE phone_number = '(375) 555-8161';
-- It is Berthhold
-- Let's find where they scaped to:
SELECT name, passport_number FROM people WHERE name LIKE 'Ernest';
-- Ernest passport: 5773159633
-- Berthhold has no passport
-- Filter destinations of Ernest at first thing.
SELECT destination_airport_id, hour FROM flights WHERE year = 2020 AND month = 7 AND day = 29 AND hour >= 8 OR hour <= 11 AND origin_airport_id = 8 AND id IN (SELECT passport_number FROM passengers WHERE passport_number = 5773159633);
-- Only 2 destinations early morning. Destination airport id 4 and 1. I would say is destination id 4.
SELECT city FROM airports WHERE id = 4;
--The destination is London.
#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 == '?')
{
fprintf(stderr, "Invalid filter.\n");
return 1;
}
// Ensure only one filter
if (getopt(argc, argv, filters) != -1)
{
fprintf(stderr, "Only one filter allowed.\n");
return 2;
}
// Ensure proper usage
if (argc != optind + 2)
{
fprintf(stderr, "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)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 4;
}
// Open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "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);
fprintf(stderr, "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)
{
fprintf(stderr, "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 infile
fclose(inptr);
// Close outfile
fclose(outptr);
return 0;
}
#include "helpers.h"
#include <stdlib.h>
#include <math.h>
void threebythree(int height, int width, RGBTRIPLE image[height][width]);
// The values of a pixel’s rgbtRed, rgbtGreen, and rgbtBlue components are all integers,
// so be sure to round any floating-point numbers to the nearest integer when assigning them to a pixel value!
// Convert image to grayscale
// should take an image and turn it into a black-and-white version of the same image.
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// Take each pixel and take each byte of that pixel which represents a color.
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
int red = image[i][j].rgbtRed;
// Formula to calculate Grey Scale.
int new_color = round(((float)red + (float)blue + (float)green) / 3);
//Assign formula to each color.
image[i][j].rgbtBlue = new_color;
image[i][j].rgbtGreen = new_color;
image[i][j].rgbtRed = new_color;
}
}
return;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
// Iterate though the image.
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
int red = image[i][j].rgbtRed;
// Calculate Sepia for each color.
int sepia_blue = round(.272 * red + .534 * green + .131 * blue);
if (sepia_blue > 255)
{
sepia_blue = 255;
}
int sepia_green = round(.349 * red + .686 * green + .168 * blue);
if (sepia_green > 255)
{
sepia_green = 255;
}
int sepia_red = round(.393 * red + .769 * green + .189 * blue);
if (sepia_red > 255)
{
sepia_red = 255;
}
image[i][j].rgbtBlue = sepia_blue;
image[i][j].rgbtGreen = sepia_green;
image[i][j].rgbtRed = sepia_red;
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
uint8_t temp;
// Iterate through the image but only half of the image.
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width / 2; j++)
{
int temp_blue = image[i][j].rgbtBlue;
int temp_green = image[i][j].rgbtGreen;
int temp_red = image[i][j].rgbtRed;
//Place the put the temp files in the left side and original pixels in the right side.
image[i][j].rgbtBlue = image[i][width - (j + 1)].rgbtBlue;
image[i][j].rgbtGreen = image[i][width - (j + 1)].rgbtGreen;
image[i][j].rgbtRed = image[i][width - (j + 1)].rgbtRed;
image[i][width - (j + 1)].rgbtBlue = temp_blue;
image[i][width - (j + 1)].rgbtGreen = temp_green;
image[i][width - (j + 1)].rgbtRed = temp_red;
}
}
return;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
//RGBTRIPLE **new_image = NULL;
RGBTRIPLE new_image[height][width];
// Iterate through the whole image
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
float blue_total = 0;
float green_total = 0;
float red_total = 0;
float counter = 0;
// Iterate throug the 3x3 bix. find the neighbors and returns the values of the neighbors
for (int row = - 1; row <= 1; row++)
{
for (int col = - 1; col <= 1; col++)
{
int neighbor_row = i + row;
int neighbor_col = j + col;
if (neighbor_row >= 0 && neighbor_col >= 0 && neighbor_row < height && neighbor_col < width)
{
blue_total += (float)image[neighbor_row][neighbor_col].rgbtBlue;
green_total += (float)image[neighbor_row][neighbor_col].rgbtGreen;
red_total += (float)image[neighbor_row][neighbor_col].rgbtRed;
counter++;
}
}
}
new_image[i][j].rgbtBlue = round(blue_total / counter);
new_image[i][j].rgbtGreen = round(green_total / counter);
new_image[i][j].rgbtRed = round(red_total / counter);
}
}
// Go through the original image and replace the pixels
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j].rgbtBlue = (int)new_image[i][j].rgbtBlue;
image[i][j].rgbtGreen = (int)new_image[i][j].rgbtGreen;
image[i][j].rgbtRed = (int)new_image[i][j].rgbtRed;
}
}
return;
}
// Simulate genetic inheritance of blood type
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Each person has two parents and two alleles
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)
{
// Seed random number generator
srand(time(0));
// Create a new family with three generations
person *p = create_family(GENERATIONS);
// Print family tree of blood types
print_family(p, 0);
// Free memory
free_family(p);
}
// Create a new individual with `generations`
person *create_family(int generations)
{
// TODO: Allocate memory for new person
person *p = malloc(sizeof(person));
if (p == NULL)
{
return NULL;
}
// Generation with parent data
if (generations > 1)
{
// TODO: Recursively create blood type histories for parents
p->parents[0] = create_family(generations - 1);
p->parents[1] = create_family(generations - 1);
// TODO: Randomly assign child alleles based on parents
p->alleles[0] = p->parents[0]->alleles[rand() % 2];
p->alleles[1] = p->parents[1]->alleles[rand() % 2];
}
// Generation without parent data
else
{
// TODO: Set parent pointers to NULL
p->parents[0] = NULL;
p->parents[1] = NULL;
// TODO: Randomly assign alleles
p->alleles[0] = random_allele();
p->alleles[1] = random_allele();
}
// TODO: Return newly created person
return p;
}
// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
// TODO: Handle base case
if (p == NULL)
{
return;
}
// TODO: Free parents
else
{
free_family(p->parents[0]);
free_family(p->parents[1]);
}
// TODO: Free child
free(p);
}
// Print each family member and their alleles.
void print_family(person *p, int generation)
{
// Handle base case
if (p == NULL)
{
return;
}
// Print indentation
for (int i = 0; i < generation * INDENT_LENGTH; i++)
{
printf(" ");
}
// Print person
printf("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);
}
// Randomly chooses a blood type allele.
char random_allele()
{
int r = rand() % 3;
if (r == 0)
{
return 'A';
}
else if (r == 1)
{
return 'B';
}
else
{
return 'O';
}
}
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///birthdays.db")
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
# TODO: Add the user's entry into the database
name = request.form.get("name")
month = request.form.get("month")
day = request.form.get("day")
db.execute("INSERT INTO birthdays (name, month, day) VALUES(?, ?, ?)", name, month, day)
return redirect("/")
else:
# TODO: Display the entries in the database on index.html
birthdays = db.execute("SELECT * FROM birthdays")
return render_template("index.html", birthdays=birthdays)
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="/static/styles.css" rel="stylesheet">
<title>Birthdays</title>
</head>
<body>
<div class="jumbotron">
<h1>Birthdays</h1>
</div>
<div class="container">
<div class="section">
<h2>Add a Birthday</h2>
<!-- TODO: Create a form for users to submit a name, a month, and a day -->
</div>
<div class="section">
<h2>All Birthdays</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Birthday</th>
</tr>
</thead>
<tbody>
<!-- TODO: Loop through the database entries to display them in this table -->
<form action="/" method="post">
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
<input autocomplete="off" autofocus name="month" placeholder="Month" type="text">
<input autocomplete="off" autofocus name="day" placeholder="Day" type="text">
<input type="submit">
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Birthday</th>
<th></th>
</tr>
</thead>
<tbody>
{% for birthday in birthdays %}
<tr>
<td>{{ birthday.name }}</td>
<td>{{ birthday.month }}/{{ birthday.day }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</tbody>
</table>
</div>
</div>
</body>
</html>
# prompt user for pyramid height
def main():
# Call positive int function to check for num
num = get_positive_int()
num = int(num)
# Nested loop to build the pyramid
for i in range(num):
for j in range(num):
# Logic to either put a space or a hash
if ((num - i) > j + 1):
print(" ", end="")
else:
print("#", end="")
print("")
# Function to check for a positive int between 1 and 8
def get_positive_int():
while True:
try:
n = int(input("Num between 1 and 8: "))
except ValueError:
n = int(input("Num between 1 and 8: "))
continue
else:
if n >= 1 and n <= 8:
break
return n
main()
#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)
{
// TODO
// vote takes a single argument, a string called name, representing the name of the candidate who was voted for.
// If name matches one of the names of the candidates in the election, then update that candidate’s vote total
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(name, candidates[i].name) == 0)
{
candidates[i].votes += 1;
return true;
}
}
// to account for the new vote. The vote function in this case should return true to indicate a successful ballot.
// If name does not match the name of any of the candidates in the election, no vote totals should change, and
// the vote function should return false to indicate an invalid ballot.
// You may assume that no two candidates will have the same name.
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// TODO
// The function should print out the name of the candidate who received the most votes in the election, and then print a newline.
// It is possible that the election could end in a tie if multiple candidates each have the maximum number of votes.
// In that case, you should output the names of each of the winning candidates, each on a separate line.
int max = 0;
string max_cand;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > max)
{
max = candidates[i].votes;
max_cand = candidates[i].name;
}
else if (candidates[i].votes == max)
{
printf("%s\n", candidates[i].name);
}
}
printf("%s\n", max_cand);
printf("\n");
return;
}
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int compute_text(string text);
int main(void)
{
// ask for using input
string text = get_string("What's your text: ");
// Score text
int score = compute_text(text);
//printf("Score: %f", score);
//printf("\n");
// Your program should print as output "Grade X"
if (score >= 16)
{
printf("Grade 16+");
}
else if (score < 1)
{
printf("Before Grade 1");
}
else
{
printf("Grade %i", score);
}
printf("\n");
}
//Your program should count the number of letters, words, and sentences in the text.
//You may assume that a letter is any lowercase character from a to z or any uppercase
//character from A to Z, any sequence of characters separated by spaces should count as a word,
//and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.
int compute_text(string text)
{
float letters = 0;
float word = 1;
float sentence = 0;
int i = 0;
// loop till end of string
while (text[i] != '\0')
{
/* check whether the current character is white space or new line or tab character*/
if (text[i] == ' ' || text[i] == '\n' || text[i] == '\t')
{
word++;
}
else if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
{
letters++;
}
else if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentence++;
}
i++;
}
float average_letters = 100 * letters / word;
float average_sentences = sentence * 100 / word;
float score = 0.0588 * average_letters - 0.296 * average_sentences - 15.8;
return roundf(score);
//return letters;
}
def main():
# ask for user input
paragraph = input("What's your text: ")
score = compute_text(paragraph)
# Your program should print as output "Grade X"
if score >= 16:
print("Grade 16+")
elif score < 1:
print("Before Grade 1")
else:
print(f"Grade, {score}")
# Your program should count the number of letters, words, and sentences in the text.
# You may assume that a letter is any lowercase character from a to z or any uppercase
# character from A to Z, any sequence of characters separated by spaces should count as a word,
# and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.
def compute_text(paragraph):
word = 1
letters = 0
sentence = 0
counter = 0
for i in range(len(paragraph)):
# check whether the current character is white space or new line or tab character
if ord(paragraph[i]) == 32 or ord(paragraph[i]) == 10:
word += 1
elif ord(paragraph[i]) >= 65 and ord(paragraph[i]) <= 90 or ord(paragraph[i]) >= 97 and ord(paragraph[i]) <= 122:
letters += 1
elif ord(paragraph[i]) == 46 or ord(paragraph[i]) == 33 or ord(paragraph[i]) == 63:
sentence += 1
counter += 1
average_letters = float(100 * letters / word)
average_sentences = float(sentence * 100 / word)
score = float(0.0588 * average_letters - 0.296 * average_sentences - 15.8)
return round(score)
main()
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// Your program should accept exactly one command-line argument, the name of a forensic image from which to recover JPEGs.
// If your program is not executed with exactly one command-line argument, it should remind the user of correct usage, and main should return 1
if (argc < 2 || argc > 2)
{
printf("Usage: recover [image]\n");
return 1;
}
// Remember filename
char *infile = argv[1];
// Open the file. If the forensic image cannot be opened for reading, your program should inform the user as much, and main should return 1
FILE *file = fopen(infile, "r");
if (!file)
{
printf("Could not open %s.\n", infile);
return 1;
}
BYTE buffer[512];
char filename[8];
int counter = 0;
FILE *img = NULL;
while (fread(&buffer, 512, 1, file))
{
// Starting to read the file that containts the infile in 512 byte blocks
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
if (counter != 0)
{
// Counter more than 0. Meaning it is a new image. Close the previous one and create. Then increase counter.
fclose(img);
sprintf(filename, "%03i.jpg", counter);
img = fopen(filename, "w");
fwrite(&buffer, 512, 1, img);
counter++;
}
else
{
// If counter is 0 then is a new image. Create it
sprintf(filename, "%03i.jpg", counter);
img = fopen(filename, "w");
fwrite(&buffer, 512, 1, img);
counter++;
}
}
// Continue writing is no header found
else if (counter != 0)
{
fwrite(&buffer, 512, 1, img);
}
}
fclose(file);
fclose(img);
return 0;
}
#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!");
}
printf("\n");
//printf("result player 1: %i", score1);
//printf("\n");
//printf("result player 2: %i", score2);
//printf("\n");
}
int compute_score(string word)
{
// TODO: Compute and return score for string
int count = 0;
for (int i = 0, n = strlen(word); i < n; i++)
{
if ((word[i] >= 33 && word[i] <= 47) || (word[i] >= 58 && word[i] <= 64))
{
count += 0;
}
else
{
count += POINTS[tolower(word[i]) - 97];
}
}
return count;
}
// Implements a dictionary's functionality
#include <stdbool.h>
#include "dictionary.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <strings.h>
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 17576;
// Hash table
node *table[N];
unsigned int num_words = 0;
bool it_loaded = false;
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
// TODO
// Hash the word to obtain a hash value
int hashed = hash(word);
// Access linked list at that index in the hash table
node *cursor = table[hashed];
// traverse linked list looking for the word strcasecmp
while (cursor != NULL)
{
const char *s1 = word;
const char *s2 = cursor->word;
if (strcasecmp(s1, s2) == 0)
{
return true;
}
else
{
cursor = cursor->next;
}
}
return false;
}
// Hashes word to a number
// Hash function taken from https://stackoverflow.com/questions/7666509/hash-function-for-string with recommendation to use tolower to improve performance.
unsigned int hash(const char *word)
{
// TODO
unsigned long hash = 5381;
int c;
while ((c = tolower(*word++)))
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash % N;
}
bool load(const char *dictionary)
{
// TODO
// Loads dictionary into memory, returning true if successful, else false
// Open the file
FILE *file = fopen(dictionary, "r");
if (!file)
{
printf("Could not open %s.\n", dictionary);
return false;
}
char word_temp[LENGTH + 1];
// read from dictionary one at a time
while (fscanf(file, "%s", word_temp) != EOF)
{
// allocate memory into the node
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
}
// takes a word as input and saves it in a node
strcpy(n->word, word_temp);
// Hash word to obtain hash value
int index = hash(word_temp);
n->next = NULL;
// Insert node into the hash table at that location
n->next = table[index];
table[index] = n;
num_words++;
}
fclose(file);
return true;
it_loaded = true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
return num_words;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
// Iterates over the table
for (int i = 0; i < N; i++)
{
node *ptr = table[i];
// frees the memory of each node with a temp
while (ptr != NULL)
{
node *tmp = ptr;
ptr = ptr->next;
free(tmp);
}
}
return true;
}
// VALIDATE KEY.
// Check the key lenght
if (argc < 2 || argc > 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
int lenght_s;
lenght_s = strlen(argv[1]);
if (lenght_s < 26)
{
printf("Key must be at least 26 characters\n");
return 1;
}
// Check for non-alphabetical char
for (int i = 0; i < strlen(argv[1]); i++)
{
if (!isalpha(argv[1][i]))
{
printf("ERROR: Contrains non-alphabetical characters \n");
return 1;
}
// Check for repeated chars (case insensitive)
int count = 1;
for (int j = i + 1; j < strlen(argv[1]); j++)
{
if (tolower(argv[1][i]) == tolower(argv[1][j]) && tolower(argv[1][i]) != ' ')
{
count++;
argv[1][j] = '0';
}
}
//A character is considered as duplicate if count is greater than 1
if (count > 1 && argv[1][i] != '0')
{
//printf("%c\n", argv[1][i]);
printf("ERROR: Contrains repeated characters \n");
return 1;
}
}
//printf("The full word was: %s\n\n", argv[1]);
//}
// GET PLAINTEXT
// Use get_string
string plaintext = get_string("plaintext: ");
// PRINT CIPHERTEXT
printf("ciphertext: ");
// ENCIPHER
// For each alphabetical char, determine what letter it maps to.
char encipher;
string copy_argv = argv[1];
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (islower(plaintext[i]))
{
// Preserve case.
encipher = tolower(copy_argv[(int)plaintext[i] - 97]);
printf("%c", encipher);
}
else if (isupper(plaintext[i]))
{
encipher = toupper(copy_argv[(int)plaintext[i] - 65]);
printf("%c", encipher);
}
// Leave non-alphabetical chars as is.
else
{
printf("%c", plaintext[i]);
}
}
printf("\n");
}
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// preferences[i][j] is number of voters who prefer i over j
int preferences[MAX][MAX];
// locked[i][j] means i is locked in over j. true represents the existence of an edge pointing from candidate i to candidate j
bool locked[MAX][MAX];
// Each pair has a winner, loser
typedef struct
{
int winner;
int loser;
}
pair;
// Array of candidates
string candidates[MAX];
// represent all of the pairs of candidates (for which one is preferred over the other) in the election.
pair pairs[MAX * (MAX - 1) / 2];
int pair_count;
int candidate_count;
// Function prototypes
bool vote(int rank, string name, int ranks[]);
void record_preferences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void lock_pairs(void);
void print_winner(void);
bool check_pair(int x, int y);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: tideman [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] = argv[i + 1];
}
// Clear graph of locked in pairs. which means our initial graph will have no edges in it.
for (int i = 0; i < candidate_count; i++)
{
for (int j = 0; j < candidate_count; j++)
{
locked[i][j] = false;
}
}
pair_count = 0;
int voter_count = get_int("Number of voters: ");
// Query for votes
for (int i = 0; i < voter_count; i++)
{
// ranks[i] is voter's ith preference
int ranks[candidate_count];
// helper Carlos. Sorry for not erasing it but will help me in the future.
//for(int j = 0; j < candidate_count; j++)
//{
//printf("ranks: %i", ranks[j]);
//}
// Query for each rank
for (int j = 0; j < candidate_count; j++)
{
string name = get_string("Rank %i: ", j + 1);
if (!vote(j, name, ranks))
{
printf("Invalid vote.\n");
return 3;
}
}
record_preferences(ranks);
printf("\n");
}
add_pairs();
sort_pairs();
lock_pairs();
print_winner();
return 0;
}
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
// TODO
// If name is a match for the name of a valid candidate, then you should update
// the ranks array to indicate that the voter has the candidate as their rank preference
// (where 0 is the first preference, 1 is the second preference, etc.)
// Recall that ranks[i] here represents the user’s ith preference.
// The function should return true if the rank was successfully recorded,
// and false otherwise (if, for instance, name is not the name of one of the candidates).
// You may assume that no two candidates will have the same name.
// Look through the array for a candidate that has the same name as the one passed.
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(name, candidates[i]) == 0)
{
ranks[rank] = i;
return true;
}
}
// If no candidate found don't update any ranks and return false.
return false;
}
// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
// TODO
// The function is called once for each voter
// and takes as argument the ranks array, (recall that ranks[i] is the voter’s ith preference, where ranks[0] is the first preference).
// The function should update the global preferences array to add the current voter’s preferences. Recall that preferences[i][j] should
// represent the number of voters who prefer candidate i over candidate j.
// You may assume that every voter will rank each of the candidates.
for (int i = 0; i < candidate_count; i++)
{
//printf("ranksifirst %i ", ranks[i]);
for (int j = i + 1; j < candidate_count; j++)
{
//printf("ranksi %i ", ranks[i]);
//printf("ranksj %i ", ranks[j]);
preferences[ranks[i]][ranks[j]] = preferences[ranks[i]][ranks[j]] + 1;
}
}
return;
}
// Record pairs of candidates where one is preferred over the other
// Have to say that I got some help in the logic from Pierre one of the teaching fellows.
void add_pairs(void)
{
// TODO
// The function should add all pairs of candidates where one candidate is preferred to the pairs array.
// A pair of candidates who are tied (one is not preferred over the other) should not be added to the array.
// The function should update the global variable pair_count to be the number of pairs of candidates.
// (The pairs should thus all be stored between pairs[0] and pairs[pair_count - 1], inclusive).
for (int i = 0; i < candidate_count; i++)
{
//printf("preferencesi: %i ", (int)preferences[i]);
for (int j = i + 1; j < candidate_count; j++)
{
//printf("preferencesji : %i", preferences[i]);
//printf("preferencesji : %i", preferences[j]);
//printf("preferencesij : %i", preferences[i][j]);
//printf("preferencesji : %i", preferences[j][i]);
if (preferences[i][j] > preferences[j][i])
{
pairs[pair_count].winner = i;
pairs[pair_count].loser = j;
//printf("winner: %i ", i);
//printf("Loser: %i ", j);
pair_count += 1;
}
else if (preferences[i][j] < preferences[j][i])
{
pairs[pair_count].loser = i;
pairs[pair_count].winner = j;
//printf("loser: %i ", i);
//printf("Winner: %i ", j);
pair_count += 1;
}
}
}
return;
}
// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
// TODO
// The function should sort the pairs array in decreasing order of strength of victory,
// where strength of victory is defined to be the number of voters who prefer the preferred candidate.
// If multiple pairs have the same strength of victory, you may assume that the order does not matter.
int i, j;
for (i = 0; i < pair_count - 1; i++)
{
int min_index = i;
for (j = i + 1; j < pair_count; j++)
{
if ((preferences[pairs[j].winner][pairs[j].loser]) < (preferences[pairs[min_index].winner][pairs[min_index].loser]))
{
min_index = j;
}
//printf("swap1: %i", pairs[i]);
//printf("swap2: %i", pairs[j]);
{
pair temp = pairs[j];
pairs[j] = pairs[min_index];
pairs[min_index] = temp;
//printf("winner: %i", pairs[j].winner);
//printf("loser: %i", pairs[j].loser);
//printf("swap2.2: %i", pairs[j].loser);
}
}
}
return;
}
// Lock pairs into the candidate graph in order, without creating cycles
// NOTE TO INSTRUCTOR: I consulted this url which helped a lot into understanding the logic needed https://gist.github.com/nicknapoli82/6c5a1706489e70342e9a0a635ae738c9
void lock_pairs(void)
{
// TODO
// The function should create the locked graph, adding all edges in decreasing order of victory strength so long as the edge would not create a cycle.
// The base case is a winner-loser pair that had previously been locked in as a loser-winner pair.
for (int i = 0; i < pair_count; i++)
{
if (!check_pair(pairs[i].winner, pairs[i].loser))
{
locked[pairs[i].winner][pairs[i].loser] = true;
}
}
return;
}
// Print the winner of the election
void print_winner(void)
{
// TODO
// The function should print out the name of the candidate who is the source of the graph. You may assume there will not be more than one source.
for (int i = 0; i < candidate_count; i++)
{
for (int j = i + 1; j < candidate_count; j++)
{
if (locked[i][j] == true)
{
printf("%s\n", candidates[i]);
break;
}
}
}
return;
}
bool check_pair(int x, int y)
{
//Look at a pair
//If the loser is not a winner in any existing locked pair, then lock the pair
if (locked[y][x])
{
return true;
}
// see if anyone else locks onto the current winner
else
{
for (int i = 0; i < candidate_count; i++)
{
if (locked[i][x] == true)
{
return check_pair(i, y);
}
}
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
<script>
// TODO: Add code to check answers to questions
</script>
</head>
<body>
<div class="jumbotron">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<!-- TODO: Add multiple choice question here -->
<h3>What's the best city in Colombia, South America?</h3>
<h3 id="div"></h3>
<button id="cartagena">Cartagena</button>
<button id="cali">Cali</button>
<button id="medellin">Medellín</button>
<script>
let button = document.querySelector('#cartagena');
document.querySelector('#cartagena').onclick = function() {
button.style.backgroundColor = 'green';
div.innerHTML = 'Correct!';
};
</script>
<script>
let button2 = document.querySelector('#cali');
document.querySelector('#cali').onclick = function() {
button2.style.backgroundColor = 'red';
div.innerHTML = 'Incorrect!';
};
</script>
<script>
let button3 = document.querySelector('#medellin');
document.querySelector('#medellin').onclick = function() {
button3.style.backgroundColor = 'red';
div.innerHTML = 'Incorrect!';
};
</script>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<!-- TODO: Add free response question here -->
<h3>Which country colonized Cartagena?</h3>
<h3 id="div2"></h3id></h3>
<form id="form2">
<input autocomplete="off" autofocus id="name" placeholder="Name" type="text">
<input type="submit">
</form>
<script>
document.querySelector('form').addEventListener('submit', function(event)
{
if (document.querySelector('#name').value == "Spain")
{
document.querySelector('#form2 #name').style.borderColor = 'green';
div2.innerHTML = 'Correct!';
event.preventDefault();
}
else
{
document.querySelector('#form2 #name').style.borderColor = 'red';
div2.innerHTML = 'Incorrect!';
event.preventDefault();
}
});
</script>
</div>
</div>
</body>
</html>
body {
background-color: #fff;
color: #212529;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
margin: 0;
text-align: left;
}
.container {
margin-left: auto;
margin-right: auto;
padding-left: 15px;
padding-right: 15px;
}
.jumbotron {
background-color: #477bff;
color: #fff;
margin-bottom: 2rem;
padding: 2rem 1rem;
text-align: center;
}
.section {
padding: 0.5rem 2rem 1rem 2rem;
}
.section:hover {
background-color: #f5f5f5;
transition: color 2s ease-in-out, background-color 0.15s ease-in-out;
}
h1 {
font-family: 'Montserrat', sans-serif;
font-size: 48px;
}
button, input[type="submit"] {
background-color: #d9edff;
border: 1px solid transparent;
border-radius: 0.25rem;
font-size: 0.95rem;
font-weight: 400;
line-height: 1.5;
padding: 0.375rem 0.75rem;
text-align: center;
transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
vertical-align: middle;
}
input[type="text"] {
line-height: 1.8;
width: 25%;
}
input[type="text"]:hover {
background-color: #f5f5f5;
transition: color 2s ease-in-out, background-color 0.15s ease-in-out;
}
// Modifies the volume of an audio file
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
// Number of bytes in .wav header
const int HEADER_SIZE = 44;
int main(int argc, char *argv[])
{
// Check command-line arguments
if (argc != 4)
{
printf("Usage: ./volume input.wav output.wav factor\n");
return 1;
}
// Open files and determine scaling factor
FILE *input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Could not open file.\n");
return 1;
}
FILE *output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Could not open file.\n");
return 1;
}
float factor = atof(argv[3]);
// TODO: Copy header from input file to output file
// Recall that this header is always exactly 44 bytes long.
// Array of bytes to store the data from the WAV file header
uint8_t header[HEADER_SIZE];
fread(&header, HEADER_SIZE, 1, input);
fwrite(&header, HEADER_SIZE, 1, output);
// TODO: Read samples from input file and write updated data to output file
// one 16-bit (2-byte) sample at a time. Your program should multiply each sample by the factor and write the new sample to the output file.
int16_t buffer;
while (fread(&buffer, sizeof(int16_t), 1, input))
{
buffer = (int16_t)(buffer * factor);
fwrite(&buffer, sizeof(int16_t), 1, output);
}
// Close files
fclose(input);
fclose(output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment