首页 > 其他分享 >【哈佛cs50 2022】lab3 & problemSet3【ing】

【哈佛cs50 2022】lab3 & problemSet3【ing】

时间:2023-07-01 16:35:31浏览次数:31  
标签:count cs50 candidate int lab3 candidates problemSet3 vote name

(1)lab3

如何测试每个代码运行所需要的时间?time ./sort1 sorted5000.txt

  sort1 sort2 sort3
sorted5000.txt 0.037s 0.020s 0.045s
sorted10000.txt

0.058s

0.050s

0.151s

sorted50000.txt 1.244s 2.238s 5.637s
reversed5000.txt 0.088s 0.026s 0.045s
reversed10000.txt 0.279s 0.087s 0.142s
reversed50000.txt 7.326s 3.560s 5.474s
random5000.txt 0.096s 0.023s 0.071s
random10000.txt 0.287s

0.1s

0.143s

random50000.txt 8.405s 1.975s 4.808s
my answer  bubble sort, merge sort  selection sort

(2)problem set3 - 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
    int compare = 0;
    for(int i=0;i<candidate_count;++i){
        compare = strcmp(candidates[i].name,name);
        if(!compare){
            candidates[i].votes+=1;
            //printf("compare result-%i,votes-%i\n",strcmp(candidates[i].name,name),candidates[i].votes);
            return true;
        }
    }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    int sort_max = 0;
    if(candidate_count == 1){
        printf("%s\n",candidates[candidate_count-1].name);
    }
    else{
        sort_max = candidates[0].votes;
        for(int i=0;i<candidate_count-1;++i){
            if(candidates[i+1].votes > candidates[i].votes){
                sort_max = candidates[i+1].votes;
            }
        }
        //printf("%i\n",sort_max);
        for(int j=0;j<candidate_count;++j){
            if(candidates[j].votes == sort_max){
                printf("%s\n",candidates[j].name);
            }
        }
    }
    return;
}

(3)runoff

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

// Max voters and candidates
#define MAX_VOTERS 100
#define MAX_CANDIDATES 9

// preferences[i][j] is jth 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
//voter:voter_count-ing
//rank:candidate_count-ing
bool vote(int voter, int rank, string name)
{
    // TODO
    for(int i=0;i<candidate_count;i++){
        if(!strcmp(name,candidates[i].name)){
            preferences[voter][rank] = i;
            return true;
        }
    }

    return false;
}

// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
    // TODO
    int rank = 0;
    int number = 0;
    int count = 0;
    int mid = 0;
    while(count<voter_count){

        for(int j=0;j<voter_count;j++){
            rank = 0;
            for(int i=0;i<candidate_count;i++){
                mid = preferences[j][i];
                if(!candidates[mid].eliminated){
                    break;
                }
                rank ++;
            }
            number = preferences[j][rank];
            candidates[number].votes ++;
            count++;
        }
    }
    return;
}

// Print the winner of the election, if there is one
bool print_winner(void)
{
    // TODO
    int win_number = 0.5 * voter_count;
    int max = candidates[0].votes;
    int index = 0;
    for(int i=1;i<candidate_count;i++){
        if(candidates[i].votes > max){
            max = candidates[i].votes;
            index = i;
        }
        else if(candidates[i].votes == max){
            return false;
        }
        else{
            continue;
        }
    }
    int leader = candidates[index].votes;
    printf("leader-%i-%s\n",index,candidates[index].name);
    for(int i=0;i<candidate_count;i++){
        if(i==index){
            continue;
        }
        if(max==candidates[i].votes){
            return false;
        }
    }
    if(leader>win_number){
        printf("%s\n",candidates[index].name);
        return true;
    }
    else{
        return false;
    }
    return false;
}

// Return the minimum number of votes any remaining candidate has
int find_min(void)
{
    // TODO
    int min = candidates[0].votes;

    for(int j=1;j<candidate_count;j++){
        if(!candidates[j].eliminated){
            if(candidates[j].votes<min){
                min = candidates[j].votes;
            }
        }
    }
    return min;
}

// Return true if the election is tied between all candidates, false otherwise
bool is_tie(int min)
{
    // TODO
    int count = 0;
    int num = 0;
    for(int i=0;i<candidate_count;i++){
        if(!candidates[i].eliminated){
            num++;
        }
    }
    for(int i=0;i<candidate_count;i++){
        if(candidates[i].votes == min){
            count++;
        }
    }
    if(count == num){
        return true;
    }
    else{
        return false;
    }
}

// Eliminate the candidate (or candidates) in last place
void eliminate(int min)
{
    // TODO
    for(int i=0;i<candidate_count;i++){
        if(candidates[i].votes == min){
            candidates[i].eliminated = true;
           // candidates[i].votes = 0;
        }
    }

    return;
}

(4)Tideman-ing

 

标签:count,cs50,candidate,int,lab3,candidates,problemSet3,vote,name
From: https://www.cnblogs.com/zhimingyiji/p/17519473.html

相关文章

  • 【cs50 2022】lab1 && problem set1
    |lab1|#include<cs50.h>#include<stdio.h>intmain(void){//TODO:Promptforstartsizeintstart_size;do{start_size=get_int("Startsize:");}while(start_size<9);//TODO:Promptforend......
  • 哈工大体系结构lab3 —— 流水线处理器的verilog实现
    流水线处理器的verilog实现个人认为我码风还算可以,如果我的代码有写的错误/值得改进之处,欢迎指出!!base版本设计图如下,WB阶段有一个MUX没画,因为没地方了(懒了)哈哈最后版本跟我最开始写出来的框架有些许变化,如果你看到了让你不知所以然的代码,大概率是修锅的时候造的。。CPU.v`timesc......
  • 软件构造lab3总结
    软件构造的课程和实验已经结束一段时间了,如今回顾起来,收获颇丰,在此我将回忆总结一下在实验中出现的问题,总结一下从中得到的教训,进行一个盘的复,避免以后再出现这些问题。首先,最重要的一点就是不要拖延!不要拖延!不要拖延!在前两次实验中,我的时间把控还做的不错,两次实验......
  • CS144 计算机网络 Lab3:TCP Sender
    前言在Lab2中我们实现了TCPReceiver,负责在收到报文段之后将数据写入重组器中,并回复给发送方确认应答号。在Lab3中,我们将实现TCP连接的另一个端点——发送方,负责读取ByteStream(由发送方上层应用程序创建并写入数据),并将字节流转换为报文段发送给接收方。代码实现TCPSe......
  • CS50363内置MOS可升压16V,高效率升压DC-DC转换器
    CS50363E是一款采用CMOS工艺升压型开关稳压器,其主要包括一个参考电压源,一个振荡电路,一个误差放大器,一个相位补偿电路,通过PWM/PFM切换控制电路。CS50363E内置MOS的设计,只需极简的外围电路,可以最大限度的保证电源模块的可靠性以及避免电源模块设计的复杂化。CS50363E最高可提供16V恒......
  • CS50-Python实验5,6
    Week5UnitTestsTestingmytwittr题目描述:测试ProblemSet2中Settingupmytwttr程序;题解:twttr.pydefmain():print("Output:",shorten(input("Input:")))defshorten(word):ans=""foriinword:ifi.lowe......
  • CS50-Python实验3,4
    Week3ExceptionsFuelGauge题目描述:输入分数字符串,判断并输出相应的百分数;特例不足1%输出E,超出99%输出F思路:1,从字符串中取出x,y;2,按题中要求计算输出;题解:whileTrue:try:##取出x,yx,z,y=input("Fraction:")x,y=int(x),int(y)......
  • lab3
    明确函数作用fill_window()只关心_segments_out和_outstanding_segments这两个数据结构,它要做的就是构造报文并将其添加到这两个数据结构中,添加到_segments_out......
  • lab3实验报告
    lab3实验报告一、实验思考题Thinking3.1为了保证在envs中顺序与在Env块的顺序相同。Thinking3.2低10位表示Env在envs中的位置,高位表示调用分配函数的次数。如果只有......
  • Lab3
    Lab3主要是实现一个容错的KV数据库,并用Lab2的Raft服务,在每台运行Raft的peer上构建一个状态机.3A跟着课程提示一步步走,补全client.go中的sendRPC和server.go中的处理......