【CS50x】Runoff 题解(下)

简介: 【CS50x】Runoff 题解(下)

前言



CS50x 是哈佛大学推出的一门知名公开课,本课程是一门计算机科学的导论课程,适合于对计算机科学感兴趣的任何人学习,不需要任何基础。通过学习本课程有助于对计算机科学的体系建立一个基本的概念,其学习内容如下:


image.png


Runoff



上篇文章我们总结了 Runoff 投票机制,大概需要以下步骤:


  • 读取候选人信息
  • 得到未淘汰的候选人的票数,总结为偏好数组
  • 判断是否有胜者产生
  • 找到最小值
  • 判断是否为平局
  • 淘汰票数最少的候选人


#include <cs50.h>
#include <stdio.h>
#include <string.h>
// 选民和候选人最大值
#define MAX_VOTERS 100
#define MAX_CANDIDATES 9
// 偏好数组
int preferences[MAX_VOTERS][MAX_CANDIDATES];
typedef struct
{
    string name;
    int votes;
    bool eliminated;
} candidate;
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);
复制代码


其中着重要注意的就是偏好数组,preference[i][j] 代表第 i 个选民的第 j 个喜欢。

我们可以根据过程写出 main 函数,首先获取用户输入:


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");
    }
    ...
}
复制代码


然后写出主要部分:


// 循环直到赢家产生
while (true)
{
  // 计算剩余候选人的票数
  tabulate();
  // 检查是否有人胜利
  bool won = print_winner();
  if (won)
  {
    break;
  }
  // 找到票数最少的候选人,同时判断是否平局
  int min = find_min();
  bool tie = is_tie(min);
  // 如果平局,剩下的所有人都赢了
  if (tie)
  {
    for (int i = 0; i < candidate_count; i++)
    {
      if (!candidates[i].eliminated)
      {
        printf("%s\n", candidates[i].name);
      }
    }
    break;
  }
  // 淘汰票数最少的候选人
  eliminate(min);
  // 重复该过程
  for (int i = 0; i < candidate_count; i++)
  {
    candidates[i].votes = 0;
  }
}
return 0;
复制代码


分别实现其中的函数部分,首先是 vote 函数,我们只需要检查候选人是否存在即可:


// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i].name, name) == 0)
        {
            preferences[voter][rank] = i;
            return true;
        }
    }
    return false;
}
复制代码


然后是最重要的制表环节,我们需要根据每一个选民的偏好数组找到还未被淘汰的候选人,为其加上一票:


// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
    // TODO
    for (int i = 0; i < voter_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (!candidates[preferences[i][j]].eliminated)
            {
                candidates[preferences[i][j]].votes++;
                break;
            }
        }
    }
    return;
}
复制代码


检查是否有赢家产生,得到超过50%的票数:


// Print the winner of the election, if there is one
bool print_winner(void)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        if (candidates[i].votes > voter_count / 2)
        {
            printf("%s\n", candidates[i].name);
            return true;
        }
    }
    return false;
}
复制代码


找到得票最少的候选人:


// Return the minimum number of votes any remaining candidate has
int find_min(void)
{
    // TODO
    int min = voter_count;
    for (int i = 0; i < candidate_count; i++)
    {
        if (candidates[i].votes < min && !candidates[i].eliminated)
        {
            min = candidates[i].votes;
        }
    }
    return min;
}
复制代码


判断是否平局:


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


淘汰得票最少的候选人:


// 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)
        {
            candidates[i].eliminated = true;
        }
    }
    return;
}
复制代码


测试样例



./runoff Alice Bob Charlie
Number of voters: 5
Rank 1: Alice
Rank 2: Charlie
Rank 3: Bob
Rank 1: Alice
Rank 2: Charlie
Rank 3: Bob
Rank 1: Bob
Rank 2: Charlie
Rank 3: Alice
Rank 1: Bob
Rank 2: Charlie
Rank 3: Alice
Rank 1: Charlie
Rank 2: Alice
Rank 3: Bob
Alice


目录
相关文章
|
算法
【CS50x】 Tideman 题解(上)
【CS50x】 Tideman 题解(上)
1074 0
【CS50x】 Tideman 题解(上)
|
开发工具 图形学 Android开发
从零开始的unity3d入门教程(一)----环境配置
该文章是《从零开始的Unity3D入门教程》系列的第一篇,详细介绍了Unity3D的环境配置过程,包括注册Unity账户、下载安装Unity Hub和Unity编辑器、配置许可证、创建Unity项目、下载安装Visual Studio 2022以及将Unity与Visual Studio相关联等步骤。
从零开始的unity3d入门教程(一)----环境配置
|
监控 数据可视化 项目管理
关键链项目管理是什么?它如何优化传统项目管理?
关键链项目管理(CCPM)由艾利·高德拉特提出,通过优化资源分配和减少多任务并行的浪费,显著提高项目执行效率与成功率。本文介绍CCPM的核心理念、与传统项目管理的区别及优势,并推荐几款支持CCPM的项目管理软件,如ProChain、板栗看板等,帮助企业更好地实施这一高效管理方法。
720 0
|
Java 容器
JavaFX之Stage
JavaFX之Stage
189 0
【CS50x】 Tideman 题解(下)
【CS50x】 Tideman 题解(下)
1230 0
【CS50x】 Tideman 题解(下)
|
存储 C语言
【C语言】 --- getopt()函数的使用简析
【C语言】 --- getopt()函数的使用简析
279 0
|
XML 开发工具 数据安全/隐私保护
Vivado官网获取License
Vivado官网获取License
5122 0
Vivado官网获取License
|
IDE Java 开发工具
【CS50x】Runoff 题解(上)
【CS50x】Runoff 题解(上)
515 0
【CS50x】Runoff 题解(上)