2주차 Pset2 과제는 총 3부분으로 이루어져 있습니다!

 

2-1) Scrabble

2-2) Readability
2-3) Caesar

 

 


 


<Pset 2-1. Scrabble>

: Implement a program in C that determines the winner of a short Scrabble-like game. Your program should prompt for input twice: once for “Player 1” to input their word and once for “Player 2” to input their word. Then, depending on which player scores the most points, your program should either print “Player 1 wins!”, “Player 2 wins!”, or “Tie!”

 

Score for each alphabet is :

 

 

Pseudocode being like:

//Prompt the user for two words

//Compute the score for each word

//Print the winner

 

 

★ strlen()

: string length를 줄인 함수, 문장의 길이를 알 수 있음. 뒤에서도 계속 쓰이는 함수라 기억해 둘 것!!

 

★각 단어의 char에 score 부여하고, 점수 합산하기

: for loop 사용.

('word[i] - 'A')나 ('word[i]  - 'a')는 word[] 의 각 char에 points[] 의 순서에 맞는 점수를 배분하는 것임.

 

ex) word = HELLO 일 때, word[0] = H임. 'H' - 'A' = 8이고, points[8]은 해당 배열의 8번째 점수를 H에 할당시키고,

score += points[] 의 형태로 각 char의 score을 합산하여 합계 score을 최종적으로 return.

 

 


 

 

<Pset 2-2. Readability>

:  Implement a program that calculates the approximate grade level needed to comprehend some text. Your program should print as output “Grade X” where “X” is the grade level computed, rounded to the nearest integer. If the grade level is 16 or higher (equivalent to or greater than a senior undergraduate reading level), your program should output “Grade 16+” instead of giving the exact index number. If the grade level is less than 1, your program should output “Before Grade 1”.

 

One readability test is the Coleman-Liau index :

index = 0.0588 * L - 0.296 * S - 15.8

L : the average number of letters per 100 words in the text

S : the average number of sentences per 100 words in the text

 

Pseudocode being like:

//Prompt the user for some text

//Count the number of letters/ words/ and sentences in the text

//Compute the Coleman-Liau index

//Print the grade level

 

The idea of counting the number of letters, words, and sentences

: letters(# of alphabets) - isalpha ()

  words(# of spaces+ 1) - isspace()

  sentences(# of punctuations) - ispunct()

→ Ensure to make each function below main()

 

★ The value of L and S should be float, not int 

Also, make sure to multiply 100 each when you compute the Coleman-Liau index. (to make it the average # per 100)

 

 

round() - 가까운 정수로 반올림

: a function that rounds a floating-point number to the nearest integer

 

★ When counting the # of words, make sure not to count double spaces or starting with a space.

→ It means that space should be followed by alpha or punct :

if (isspace(text[i]) && (isalpha(text[i + 1]) || ispunct(text[i + 1]))

 

★Notice that int sum_words = 1;

: This is to make sure that the text starts with a word.

 

★ When counting the # of sentences, make sure not to count punctuation other than '.', '?', or '!'

 

 


 

 

<Pset 2-3. Caesar>

: Caesar used to “encrypt” confidential messages by shifting each letter therein by some number of places. For instance, he might write A as B, B as C, C as D, …, and, wrapping around alphabetically, Z as A. And so, to say HELLO to someone, Caesar might write IFMMP instead. Upon receiving such messages from Caesar, recipients would have to “decrypt” them by shifting letters in the opposite direction by the same number of places.

 

Pseudocode being like:

//Make sure program was run with just one command-line argument

//Make sure every character in argv[1] is a digit

//Convert argv[1] from a 'string' to an 'int'

//Prompt the user for a plaintext

//For each character in the plaintext, rotate each one if it's a letter

//Print the ciphertext

★ Use argc to make sure there's only one command-line argument

if (argc != 2)

argc = 2일 때 c-l argument가 하나이기 때문에, 2가 아닌 경우를 조건에 기재하여 error message를 print함.

++  argv[1]이 digit으로 이루어져 있지 않은 경우에도 ||로 묶어 같은 error message print함.

 

atoi()

: a function in stdlib.h that converts a string to an 'int'

 

 

bool only_digits(string s)

: argv[1] 안에 있는 각각의 char이 digit인지 아닌지 판단하는 함수 → true or false

 

malloc()

: a function that allocates size bytes of uninitialized storage

pointer = malloc(size_in_bytes);

 

위 코드에 적은 malloc function을 풀어서 해석해보면 :

string ciphertext = malloc((strlen(plaintext) + 1) * sizeof(char));

→ char의 bytes size인 4 * (plaintext의 길이+1)ciphertext라는 string에 배정하는 것.

 

strlen(plaintext) + 1

: ensure that there's enough memory allocated to store the entire string, including the null terminator. ('\0')

 

ciphertext[length] = '\0'

: ensures that the last character of the ciphertext string is the null terminator, marking the end of the string.
This is necessary for functions like printf to correctly identify where the string ends.

 

char new_c = (c - 'a' + n) % 26 + 'a';

ⓐ c - 'a' : converts c to zero-based index (where 'a' becomes 0, 'b' becomes 1, and so on up to 'z' becomes 25)

ⓑ (c - 'a' + n) : shifts the character by n positions in the alphabet

ⓒ % 26 : ensures that the result wraps around if it goes past 'z'.
ⓓ + 'a' : converts the zero-based index to a character 

 

 

 


이번 과제를 하면서 수정을 100번도 더 했는데...

느낀 점은 코딩은 반복을 싫어한다! 위에서 정의한 변수일 경우 아래에서는 간단하게 사용할 것.

그리고 본래 library에 있는 함수들을 많이 사용하면 편리하다. 예를 들면 atoi(), malloc(), islower()... 같은 것들!

그리고 확실히 지난 주 과제보다 스스로 할 수 있는 부분이 늘어났고, 앞선 과제에서 사용했던 방법들을 응용할 수도 있었다.

물론 아직 수정에 수정에 수정을 거듭하지만, 오류를 계속해서 디버그하고 고민하는 과정 속에서 배울 점들이 있었다.

Week 3 로 돌아올게 팟팅 ♥ㅎ

'CS50' 카테고리의 다른 글

[CS50] Week 3 Section  (2) 2024.10.03
[CS50] Week 3 Review  (1) 2024.10.01
[CS50] Week 2 Section  (0) 2024.09.24
[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15

+ Recent posts