Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define TEST_TIMES 10000000
- typedef struct node
- {
- char* key;
- int value;
- struct node* next;
- } LinkList;
- char* pick(LinkList* head);
- // 产生一个精度为0.001的 0到1之间的浮点数,不会等于1
- float randf()
- {
- return (float)(rand() % 1001) * 0.001f;
- }
- int main()
- {
- int i;
- char* name;
- char* found;
- int weight;
- LinkList* head = (LinkList*)malloc(sizeof(LinkList));
- LinkList* statHead = (LinkList*)malloc(sizeof(LinkList));
- LinkList* node = head;
- LinkList* statNode = statHead;
- while(1)
- {
- name = (char*)malloc(sizeof(char) * 100);
- scanf("%s", name);
- if (strcmp(name, "0") == 0)
- {
- break;
- }
- node->next = (LinkList*)malloc(sizeof(LinkList));
- statNode->next = (LinkList*)malloc(sizeof(LinkList));
- node = node->next;
- statNode = statNode->next;
- node->key = name;
- statNode->key = name;
- scanf("%d", &weight);
- node->value = weight;
- statNode->value = 0;
- }
- for (i = 0; i < TEST_TIMES; i++)
- {
- found = pick(head);
- if (found != NULL)
- {
- statNode = statHead->next;
- while (statNode!=NULL)
- {
- if (strcmp(statNode->key,found) == 0)
- {
- statNode->value++;
- break;
- }
- statNode = statNode->next;
- }
- }
- }
- statNode = statHead->next;
- while (statNode != NULL)
- {
- printf("%s -> %.0f%%\n", statNode->key, (double) statNode->value / TEST_TIMES * 100);
- statNode = statNode->next;
- }
- return 0;
- }
- //只能更改以下部分
- char* pick(LinkList* head)
- {
- int sum = 0;
- int total = 0;
- LinkList* node = head->next;
- float rnd = randf();
- while (node != NULL)
- {
- total+=node->value;
- node = node->next;
- }
- node = head->next;
- while (node != NULL)
- {
- sum += node->value;
- if (sum / (double) total >= rnd)
- {
- return node->key;
- }
- node = node->next;
- }
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement