Closed12
CS50 2020
ハーバード大学のコンピュータサイエンス入門講座「CS50」の課題をします。
week1 Lab1 Hello
#include <cs50.h>
#include <stdio.h>
int main(void)
{
string name = get_string("What is your name?\n");
printf ("hello, %s\n",name) ;
}
week1 Lab1 Population
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// TODO: Prompt for start size
int start_size;
do
{
start_size = get_int("Start size: ");
}
while (start_size < 9);
// TODO: Prompt for end size
int end_size;
do
{
end_size = get_int("End size: ");
}
while (end_size < start_size);
// TODO: Calculate number of years until we reach threshold
int years = 0;
while (start_size < end_size)
{
start_size = start_size + (start_size / 3) - (start_size / 4);
years++;
}
// TODO: Print number of years
printf("Years: %i\n", years);
}
week1 mario
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("Height: ");
}
while (height > 8 | height < 1);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < height - i - 1; j++)
{
printf(" ");
}
for (int j = 0; j < i + 1; j++)
{
printf("#");
}
printf(" ");
for (int j = 0; j < i + 1; j++)
{
printf("#");
}
printf("\n");
}
}
week1 Credit
#include <cs50.h>
#include <stdio.h>
int main(void)
{
//番号取得
long number;
number = get_long("Number: ");
//桁数取得
int digit = 0;
long _number = number;
while (_number != 0)
{
_number = _number / 10;
++digit;
}
// 桁数での確認
if (digit != 13 && digit != 15 && digit != 16)
{
printf("INVALID\n");
return 0;
}
//checksumの計算
int sum1 = 0;
int sum2 = 0;
long num = number;
int checksum = 0;
int mod1;
int mod2;
int d1;
int d2;
do
{
//1桁目を取得&削除し、sum1に足す
mod1 = num % 10;
num = num / 10;
sum1 = sum1 + mod1;
//2桁目の取得と削除
mod2 = num % 10;
num = num / 10;
//2桁目の計算
mod2 = mod2 * 2;
d1 = mod2 % 10;
d2 = mod2 / 10;
sum2 = sum2 + d1 + d2;
}
while (num > 0);
checksum = sum1 + sum2;
// checksumでの確認
if (checksum % 10 != 0)
{
printf("INVALID\n");
return 0;
}
// 最初の2桁の取得
long start = number;
do
{
start = start / 10;
}
while (start > 100);
// 最初の2桁での確認
if ((start / 10 == 5) && (0 < start % 10 && start % 10 < 6))
{
printf("MASTERCARD\n");
}
else if ((start / 10 == 3) && (start % 10 == 4 || start % 10 == 7))
{
printf("AMEX\n");
}
else if (start / 10 == 4)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
week2 lab2 scrabble
#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!\n");
}
else if (score1 < score2)
{
printf("Player 2 wins!\n");
}
else if (score1 == score2)
{
printf("Tie!\n");
}
}
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 = score + POINTS[word[i] - 'A'];
}
else if (islower(word[i]))
{
score = score + POINTS[word[i] - 'a'];
}
}
return score;
}
week2 readability
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int main(void)
{
string text = get_string("Text: ");
int letters = count_letters(text);
int words = count_words(text);
int sentences = count_sentences(text);
float L = (float) letters / (float) words * 100;
float S = (float) sentences / (float) words * 100;
int index = round(0.0588 * L - 0.296 * S - 15.8);
// printf("%i letter(s)\n",letters);
// printf("%i word(s)\n",words);
// printf("%i sentence(s)\n",sentences);
// printf("%i index\n",index);
if (index < 1)
{
printf("Before Grade 1\n");
}
else if (index > 16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n", index);
}
}
int count_letters(string text)
{
int letters = 0;
for (int i = 0, len = strlen(text); i < len; i++)
{
if (isupper(text[i]))
{
letters += 1;
}
else if (islower(text[i]))
{
letters += 1;
}
}
return letters;
}
int count_words(string text)
{
// 最後のwordの1個を初期値としてもつ
int words = 1;
for (int i = 0, len = strlen(text); i < len; i++)
{
if (text[i] == ' ')
{
words += 1;
}
}
return words;
}
int count_sentences(string text)
{
int sentences = 0;
for (int i = 0, len = strlen(text); i < len; i++)
{
if (text[i] == '.')
{
sentences += 1;
}
else if (text[i] == '!')
{
sentences += 1;
}
else if (text[i] == '?')
{
sentences += 1;
}
}
return sentences;
}
week2 Substitution
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
// validate arg
if (argc != 2)
{
printf("useage: ./substitution key\n");
return 1;
}
// get key
string key = argv[1];
// validate key
if (strlen(key) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
for (int i = 0; i < 26; i++)
{
if (!isalpha(key[i]))
{
printf("Key must only contain alphabetic characters.\n");
return 1;
}
for (int j = 0; j < 26; j++)
{
if (i != j && key[i] == key[j])
{
printf("Key must not contain repeated characters.\n");
return 1;
}
}
}
// get plaintext
string plaintext = get_string("plaintext: ");
// Encipher & output
printf("ciphertext: ");
for (int i = 0, len = strlen(plaintext); i < len; i++)
{
if (islower(plaintext[i]))
{
printf("%c", tolower(key[plaintext[i] - 'a']));
}
else if (isupper(plaintext[i]))
{
printf("%c", toupper(key[plaintext[i] - 'A']));
}
else
{
printf("%c", plaintext[i]);
}
}
printf("\n");
}
week3 lab3 sort
sort1 uses: Bubble sort
How do you know?:
sorted5000 : 0m0.009s
sorted10000 : 0m0.020s
sorted50000 : 0m2.995s
reversed5000 : 0m0.092s
reversed10000 : 0m0.368s
reversed50000 : 0m13.248s
random5000 : 0m0.080s
random10000 : 0m0.432s
random50000 : 0m19.828s
sort1 is faster than sort3 when I sort sorted50000.txt.
sort2 uses: Merge sort
How do you know?:
sorted5000 : 0m0.012s
sorted10000 : 0m0.090s
sorted50000 : 0m4.192s
reversed5000 : 0m0.036s
reversed10000 : 0m0.018s
reversed50000 : 0m3.203s
random5000 : 0m0.013s
random10000 : 0m0.018s
random50000 : 0m4.838s
sort2 is the fastest when I sort random50000.txt.
sort3 uses: Selection sort
How do you know?:
sorted5000 : 0m0.038s
sorted10000 : 0m0.219s
sorted50000 : 0m8.990s
reversed5000 : 0m0.075s
reversed10000 : 0m0.179s
reversed50000 : 0m8.421s
random5000 : 0m0.032s
random10000 : 0m0.160s
random50000 : 0m6.952s
sort3 is not faster than sort1 when I sort sorted50000.txt.
week3 plurality
#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
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)
{
// TODO
int max_votes = 0;
for (int i = 0; i < candidate_count; i++)
{
if (max_votes < candidates[i].votes)
{
max_votes = candidates[i].votes;
}
}
for (int i = 0; i < MAX; i++)
{
if (max_votes == candidates[i].votes)
{
printf("%s\n", candidates[i].name);
}
}
return;
}
week3 tideman
途中からわからず。時間なかったので、👇を参照した。
#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
bool locked[MAX][MAX];
// Each pair has a winner, loser
typedef struct
{
int winner;
int loser;
}
pair;
// Array of candidates
string candidates[MAX];
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 cycle(int end, int cycle_start);
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
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];
// 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
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(candidates[i], name) == 0)
{
ranks[rank] = i;
return true;
}
}
return false;
}
// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
// TODO
for (int i = 0; i < candidate_count; i++)
{
for (int j = i + 1; j < candidate_count; j++)
{
preferences[ranks[i]][ranks[j]]++;
}
}
return;
}
// Record pairs of candidates where one is preferred over the other
void add_pairs(void)
{
// TODO
for (int i = 0; i < candidate_count; i++)
{
for (int j = i + 1; j < candidate_count; j++)
{
if (preferences[i][j] > preferences[j][i])
{
pairs[pair_count].winner = i;
pairs[pair_count].loser = j;
pair_count++;
}
else if (preferences[i][j] < preferences[j][i])
{
pairs[pair_count].winner = j;
pairs[pair_count].loser = i;
pair_count++;
}
}
}
return;
}
// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
for (int i = pair_count - 1; i >= 0 ; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if ((preferences[pairs[j].winner][pairs[j].loser]) < (preferences[pairs[j + 1].winner][pairs[j + 1].loser]))
{
pair temp = pairs[j];
pairs[j] = pairs[j + 1];
pairs[j + 1] = temp;
}
}
}
return;
}
bool cycle(int end, int cycle_start)
{
if (end == cycle_start)
{
return true;
}
for (int i = 0; i < candidate_count; i++)
{
if (locked[end][i])
{
if (cycle(i, cycle_start))
{
return true;
}
}
}
return false;
}
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
for (int i = 0; i < pair_count; i++)
{
if (!cycle(pairs[i].loser, pairs[i].winner))
{
locked[pairs[i].winner][pairs[i].loser] = true;
}
}
return;
}
// Print the winner of the election
void print_winner(void)
{
// TODO
for (int i = 0; i < candidate_count; i++)
{
int false_count = 0;
for (int j = 0; j < candidate_count; j++)
{
if (locked[j][i] == false)
{
false_count++;
if (false_count == candidate_count)
{
printf("%s\n", candidates[i]);
}
}
}
}
return;
}
week4 lab4 volume
// 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
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
int16_t buffer;
while (fread(&buffer, sizeof(int16_t), 1, input))
{
buffer = buffer * factor;
fwrite(&buffer, sizeof(int16_t), 1, output);
}
// Close files
fclose(input);
fclose(output);
}
このスクラップは2023/07/26にクローズされました