CS50 第二周 Arrays

scores.c

#include <stdio.h>
#include <cs50.h>

const int N = 3;

float average(int length, int array[]);

int main()
{
    int scores[N];
    for (int i = 0; i < N; i++)
    {
        scores[i] = get_int("Score: ");
    }

    printf("Average: %f\n", average(N, scores));
}

float average(int length, int array[])
{
    int sum = 0;
    for (int i = 0; i < length; i++)
    {
        sum += array[i];
    }

    return sum / (float)length;
}

string.c

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    string words[2];

    words[0] = "HI!";
    words[1] = "BYE!";

    printf("%c%c%c\n", words[0][0], words[0][1], words[0][2]);
    //printf("%i",words[0][3]);
    printf("%i",words[0][4]);
    printf("%i",words[0][5]);
    printf("%i",words[0][6]);
    printf("%i",words[0][7]);
    printf("%i",words[0][8]);

    printf("\n");
    printf("%i%i%i%i\n", words[1][0], words[1][1], words[1][2], words[1][3]);
    return 0;
}

length.c

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    string name = get_string("What's your name? ");

    int n = 0;
    while (name[n] != '\0')
    {
        n++;
    }
    printf("%i\n", n);
    printf("%i", name[n]);
    return 0;
}

uppercase.c

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    string str = get_string("Before: ");
    printf("After: ");
    for (int i = 0, n = strlen(str); i < n; i++)
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
            str[i] -= ('a' - 'A');
            printf("%c", str[i]);
        }
        else
        {
            printf("%c", str[i]);
        }
    }

    printf("\n");
    return 0;
}

uppercase2.c

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    string str = get_string("Before: ");
    printf("After: ");
    for (int i = 0, n = strlen(str); i < n; i++)
    {
        printf("%c", toupper(str[i]));

    }
    printf("\n");
    return 0;
}

greet.c

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>

int main(int argc, string argv[])//int argc,string argv[] 代表命令行参数,string实际上是char *
{
    string  name = get_string("What is your name? ");
    printf("Hello,%s.\n",name);
    
    return 0;
}

status.c

#include <cs50.h>
#include <stdio.h>

int main(int argc,string argv[])
{
    if (argc != 2)
    {
        printf("Missing command-line argument\n");
    }
    else
    {
        printf("Hello,%s!\n",argv[1]);
    }
    
    return 0; //通过    echo $? 查看返回状态 通过返回不同数字了解不同状态比如return 1;
}

hours.c

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int num = get_int("Number of weeks taking CS50: ");

    int total_hours = 0;

    for (int i = 0; i < num; i++)
    {
        total_hours += get_int("Week %i HW Hours: ", i + 1);
    }

    char answer = get_char("Enter T for total hours, A for average hours per week: ");

    if (answer == 'T')
    {
        printf("Total hours: %i\n", total_hours);
    }
    else if (answer == 'A')
    {
        float average_hours = (float)total_hours / num;
        printf("Average hours per week: %.2f\n", average_hours);
    }
    else
    {
        printf("Invalid choice.\n");
    }

    return 0;
}

hours_array.c

#include <cs50.h>
#include <stdio.h>

int total_hours(int arr[], int size);
float average_hours(int arr[], int size);

int main(void)
{
    int num = get_int("Number of weeks taking CS50: ");

    int hours_per_week[num];

    for (int i = 0; i < num; i++)
    {
        hours_per_week[i] = get_int("Week %i HW Hours: ", i + 1);
    }

    char answer = get_char("Enter T for total hours, A for average hours per week: ");

    if (answer == 'T')
    {
        printf("Total hours: %i\n", total_hours(hours_per_week,num));
    }
    else if (answer == 'A')
    {
        printf("Average hours per week: %.2f\n", average_hours(hours_per_week,num));
    }
    else
    {
        printf("Invalid choice.\n");
    }

    return 0;
}

int total_hours(int arr[], int size)
{
    int total = 0;
    for (int i = 0; i < size; i++)
    {
        total += arr[i];
    }

    return total;
}

float average_hours(int arr[], int size)
{
    int total = 0;
    float average = 0;
    for (int i = 0; i < size; i++)
    {
        total += arr[i];
    }
    average = (float)total / size;
    return average;
}

no_vowels.c

#include <stdio.h>
#include <string.h>
#include <cs50.h>

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: %s <string>\n",argv[0]);
        return 1;
    }
    int length = strlen(argv[1]);
    for (int i = 0; i < length; i++)
    {
        switch (argv[1][i])
        {
        case 'a':
            printf("%d",6);
            break;
        case 'e':
            printf("%d",3);
            break;
        case 'i':
            printf("%d",1);
            break;
        case 'o':
            printf("%d",0);
            break;
        default:
            printf("%c",argv[1][i]);
            break;
        }
    }
    printf("\n");
    return 0;
}

passwd.c

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

bool is_valid_password(string str , int size);

int main(void)
{
    string passwd = get_string("Enter your password: ");
    int length = strlen(passwd);

    if (is_valid_password(passwd , length))
    {
        printf("Your password is valid!");
    }
    else
    {
        printf("Your password needs at least one uppercase letter, lowercase letter, number and symbol!");
    }
    return 0;
}

bool is_valid_password(string str , int size)
{   
    bool has_upper = false,has_lower = false, has_digit = false, has_symbol = false;
    for (int i = 0; i < size; i++)
    {
        if (isupper(str[i]))
        {
            has_upper = true;
        }else if(islower(str[i])){
            has_lower = true;
        }else if(isdigit(str[i])){
            has_digit = true;
        }else if(ispunct(str[i])){
            has_symbol = true;
        }
    }

    return has_digit && has_lower && has_symbol && has_upper;
}

scrabble.c

#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 length = strlen(word);
    int score = 0;
    for (int i = 0; i < length; i++)
    {
        if (isalpha(word[i]))
        {
            if (islower(word[i]))
            {
                score += POINTS[word[i] - 'a'];
            }
            else
            {
                score += POINTS[word[i] - 'A'];
            }
        }
    }
    return score;
}

bulbs.c

//不用位操作转换二进制

#include <cs50.h>
#include <stdio.h>
#include <string.h>

const int BITS_IN_BYTE = 8;

void print_bulb(int bit);

// 要求通过用户输入的字符,转化成二进制,然后用灯泡表示出来
int main(void)
{
    // TODO
    string ms = get_string("Message: ");
    int length = strlen(ms);
    // 用来存储计算出的比特数值
    int bits[BITS_IN_BYTE];

    // 遍历每个字符
    for (int i = 0; i < length; i++)
    {
        // 将字符转换为整数值
        int value = (int)ms[i];

        for (int j = 0; j < BITS_IN_BYTE; j++)
        {
            // 倒序存储到整数数组
            bits[j] = value % 2;
            value /= 2;
        }
        for (int k = BITS_IN_BYTE - 1; k >= 0; k--)
        {
            // 将每个比特位的值倒序打印到灯泡函数
            print_bulb(bits[k]);
        }
        printf("\n");
    }
}

void print_bulb(int bit)
{
    if (bit == 0)
    {
        // Dark emoji
        printf("\U000026AB");
    }
    else if (bit == 1)
    {
        // Light emoji
        printf("\U0001F7E1");
    }
}

bulbs2.c

#include <cs50.h>
#include <stdio.h>
#include <string.h>

const int BITS_IN_BYTE = 8;

void print_bulb(int bit);

// 要求通过用户输入的字符,转化成二进制,然后用灯泡表示出来
int main(void)
{
    // TODO
    string ms = get_string("Message: ");
    int length = strlen(ms);

    // 遍历每个字符
    for (int i = 0; i < length; i++)
    {
        // 将字符转换为整数值
        int value = (int)ms[i];

        // 遍历每个比特
        for (int j = BITS_IN_BYTE - 1; j >= 0; j--)
        {
            // 将每个比特位的值打印到灯泡函数
            print_bulb((value >> j) & 1);
        }
        printf("\n");
    }
}

void print_bulb(int bit)
{
    if (bit == 0)
    {
        // Dark emoji
        printf("\U000026AB");
    }
    else if (bit == 1)
    {
        // Light emoji
        printf("\U0001F7E1");
    }
}

caesar.c

//字符串加密  

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void ciphertext(string str, size_t size, int n);
int string_to_int(string str);

int main(int argc, string argv[])
{

    if (argc == 2)
    {
        string key_str = argv[1];
        // strlen 返回类型为 size_t
        for (size_t i = 0; i < strlen(key_str); i++)
        {
            if (!isdigit(key_str[i]))
            {
                printf("Usage: ./caesar key\n");
                return 1;
            }
        }
        string plaintext = get_string("Plaintext: ");
        // 将key_str转换成 key_num

        int key_num = string_to_int(key_str);

        ciphertext(plaintext, strlen(plaintext), key_num);
    }
    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    return 0;
}

void ciphertext(string str, size_t size, int n)
{
    for (size_t i = 0; i < size; i++)
    {
        if (islower(str[i]))
        {
            // 加密字符转换逻辑 A 或者 a 为0 加密后后移
            printf("%c", (str[i] - 'a' + n) % 26 + 'a');
        }
        else if (isupper(str[i]))
        {
            printf("%c", (str[i] - 'A' + n) % 26 + 'A');
        }
        else
        {
            printf("%c", str[i]);
        }
    }
    printf("\n");
}
int string_to_int(string str)
{
    int result = 0;
    int sign = 1; // 默认为正数

    // 处理负号
    if (str[0] == '-')
    {
        sign = -1;
        str++;
    }

    // 遍历字符串中的每个字符
    for (int i = 0; str[i] != '\0'; i++)
    {
        // 检查字符是否为数字
        if (str[i] >= '0' && str[i] <= '9')
        {
            // 将字符转换为数字并更新结果
            result = result * 10 + (str[i] - '0');
        }
    }

    // 将符号应用到结果并返回
    return result * sign;
}

substitution.c

//通过给出的26个字母排序加密文本

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

bool is_abc(string str);
void ciphertext(string key, string ms);

int main(int argc, string argv[])
{
    if (argc == 2)
    {
        string key_str = argv[1];
        // 判断是否是26个不重复字母,不分大小写
        if (!is_abc(key_str))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
        else // 如果key格式正确,让用户输入文本进行加密处理
        {
            string plaintext = get_string("Plaintext: ");
            // 加密处理逻辑
            ciphertext(key_str, plaintext);
            return 0;
        }
    }
    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}

// 检查是否包含26个字母
bool is_abc(string str)
{
    if (strlen(str) != 26)
    {
        return false;
    }
    // 创建一个长度为26的整数数组,用于记录每个字母的出现次数。初始化所有的计数为0。
    int count[26] = {0};
    // 使用循环遍历输入的字符串 str 中的每个字符
    for (size_t i = 0; i < strlen(str); i++)
    {
        // 使用 isalpha 函数检查当前字符是否是字母。如果不是字母,函数返回 false,表示输入字符串中包含了非字母字符
        if (!isalpha(str[i]))
        {
            return false;
        }
        // 将当前字符转换为小写形式(如果是大写字母),然后减去 'a' 的 ASCII 值,得到字母在数组中的索引
        int index = tolower(str[i]) - 'a';
        // 如果数组中对应字母的计数已经大于0,说明该字母已经在字符串中出现过,函数返回 false,表示有重复的字母
        if (count[index] > 0)
        {
            return false; // 有重复字母
        }
        // 如果当前字母是第一次出现,将对应的计数加1
        count[index]++;
    }

    return true;
}

void ciphertext(string key, string ms)
{
    int index = 0;
    for (size_t i = 0; i < strlen(ms); i++)
    {
        // 判断遍历的字符是否是字母
        if (isalpha(ms[i]))
        {
            // 如果是小写字母,输出key中对应位置的小写字母
            if (islower(ms[i]))
            {
                index = ms[i] - 'a';
                printf("%c", tolower(key[index]));
            }
            else// 添加 else 来确保是同一个条件下的输出
            {
                index = ms[i] - 'A';
                printf("%c", toupper(key[index]));
            }
        }
        else
        {
            // 不是字母的直接打印字符
            printf("%c", ms[i]);
        }
    }
    printf("\n");
}

wordle.c

wget https://cdn.cs50.net/2022/fall/psets/2/wordle.zip

#include <cs50.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

// 每个文本文件包含 1000 个单词
#define LISTSIZE 1000

// 颜色和分数值(EXACT == 正确的字母,正确的位置;CLOSE == 正确的字母,错误的位置;WRONG == 错误的字母)
#define EXACT 2
#define CLOSE 1
#define WRONG 0

// ANSI 颜色代码,用于在方框中显示字母
#define GREEN "\e[38;2;255;255;255;1m\e[48;2;106;170;100;1m"
#define YELLOW "\e[38;2;255;255;255;1m\e[48;2;201;180;88;1m"
#define RED "\e[38;2;255;255;255;1m\e[48;2;220;20;60;1m"
#define RESET "\e[0;39m"

// 用户定义的函数原型
string get_guess(int wordsize);
int check_word(string guess, int wordsize, int status[], string choice);
void print_word(string guess, int wordsize, int status[]);

int main(int argc, string argv[])
{
    // 确保使用正确

    // TODO #1
    if (argc != 2)
    {
        printf("Usage: ./wordle wordsize\n");
        return 1;
    }
    else if (!isdigit(argv[1][0]))
    {
        printf("Usage: ./wordle wordsize\n");
        return 1;
    }
    int wordsize = 0;
    // 确保 argv[1] 是 5、6、7 或 8,并将该值存储在 wordsize 中

    // TODO #2

    if (argv[1][0] > '4' && argv[1][0] < '9')
    {
        wordsize = argv[1][0] - '0';
    }
    else
    {
        printf("Error: wordsize must be either 5, 6, 7, or 8\n");
        return 1;
    }

    // 打开正确的文件,每个文件恰好包含 LISTSIZE 个单词
    char wl_filename[6];
    sprintf(wl_filename, "%i.txt", wordsize);
    FILE *wordlist = fopen(wl_filename, "r");
    if (wordlist == NULL)
    {
        printf("Error opening file %s.\n", wl_filename);
        return 1;
    }

    // 将单词文件加载到大小为 LISTSIZE 的数组中
    char options[LISTSIZE][wordsize + 1];

    for (int i = 0; i < LISTSIZE; i++)
    {
        fscanf(wordlist, "%s", options[i]);
    }

    // 伪随机选择一个单词用于这个游戏
    srand(time(NULL));
    string choice = options[rand() % LISTSIZE];

    // 允许猜测次数比单词长度多一次
    int guesses = wordsize + 1;
    bool won = false;

    // 打印问候语,使用 ANSI 颜色代码演示
    printf(GREEN "This is WORDLE50" RESET "\n");
    printf("You have %i tries to guess the %i-letter word I'm thinking of\n", guesses, wordsize);

    // 主游戏循环,每次猜测一次
    for (int i = 0; i < guesses; i++)
    {
        // 获取用户的猜测
        string guess = get_guess(wordsize);

        // 数组以保存猜测状态,最初设置为零
        int status[wordsize];

        // 将状态数组的所有元素最初设置为 0,即 WRONG
        // TODO #4
        for (int i = 0; i < wordsize; i++)
        {
            status[i] = WRONG;
        }

        // 计算猜测的分数
        int score = check_word(guess, wordsize, status, choice);

        printf("Guess %i: ", i + 1);

        // 打印猜测
        print_word(guess, wordsize, status);

        // 如果他们完全正确猜到,设置终止循环
        if (score == EXACT * wordsize)
        {
            won = true;
            break;
        }
    }

    // 打印游戏结果
    // TODO #7
    if (won)
    {
        printf("You won!\n");
    }

    // 结束游戏
    return 0;
}

string get_guess(int wordsize)
{
    string guess = get_string("Input a %i-letter word: ", wordsize);

    // 确保用户提供的猜测实际上是正确长度的
    // TODO #3
    if (strlen(guess) == wordsize)
    {
        int value = 0;
        for (size_t i = 0; i < strlen(guess); i++)
        {
            if (isalpha(guess[i]))
            {
                value++;
            }
        }
        if (value == wordsize)
        {
            return guess;
        }
    }
    get_guess(wordsize);//return "";
}

int check_word(string guess, int wordsize, int status[], string choice)
{
    int score = 0;

    // 将猜测与选择进行比较,并根据需要得分,将分数存储在状态中
    // TODO #5

    // 提示
    // 遍历猜测的每个字母
    // 遍历选择的每个字母
    // 比较当前猜测字母与当前选择字母
    // 如果它们在单词中的相同位置,得分 EXACT 点(绿色)并终止循环,以便不进一步比较该字母
    // 如果它在单词中,但不是正确的位置,得分 CLOSE 点(黄色)
    // 通过添加上述每个字母的个体分数来跟踪总分
    for (int i = 0; i < wordsize; i++)
    {
        if (guess[i] == choice[i])
        {
            status[i] = EXACT;
        }
        else
        {
            for (int j = 0; j < wordsize; j++)
            {
                if (status[j] != EXACT)
                {
                    if (guess[i] == choice[j])
                    {
                        status[i] = CLOSE;
                    }
                }
            }
        }
    }
    for (int k = 0; k < wordsize; k++)
    {
        score += status[k];
    }
    return score;
}

void print_word(string guess, int wordsize, int status[])
{
    // 以正确的颜色编码逐字符打印单词,然后将终端字体重置为正常
    // TODO #6
    
    for (int i = 0; i < wordsize; i++)
    {
        if (status[i] == EXACT)
        {
            // 输出猜中的字母为绿色
            printf(GREEN "%c " RESET, guess[i]);
        }
        else if (status[i] == CLOSE)
        {
            // 输出位置错误的字母为黄色
            printf(YELLOW "%c " RESET, guess[i]);
        }
        else if (status[i] == WRONG)// && guess[0] != '\0'
        {
            // 输出错误字母为红色
            printf(RED "%c " RESET, guess[i]);
        }
    }
    printf("\n");
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anxonz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值