最近项目上需要用到一个从模型中取数据,然后根据ID打包分成N组,最后分组通过UDP发送出去给控制器。自己写了一个分组的算法,虽然功能也算实现了,但总感觉应该还有更好的办法,但是自己想不到了,搜索了许久也没能找到更好的。因此发表到博客中,一是自己做个总结,二是如有网友有好的想法,望不吝赐教。
以下是算法实现,为了更好地演示我在项目中的实现,我重新写了一个简单的程序。
1,首先,创建了10所学校信息,每一个学校包含有多少个年纪,有多少个班级,和学校的ID;
2,然后,通过每一个学校的ID是单还是双数,将10所学校分成两组;这里我通过在学校的结构体上层再创建一个Block层级,用于通过ID分组之后,重新分配一个Block ID给新创建的结构体。这一步感觉有点不直观,不知道有没有更好的算法。
3,重新打印分组后的学校分布信息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tschool {
int grade;
int class;
int ID;
}tschool;
typedef struct tBlock {
tschool rankSchool[10];
}tBlock;
typedef struct tcity {
tBlock Block[2];
}tcity;
tschool *mySchool = NULL;
tcity *Beijing = NULL;
int main()
{
int i = 0;
int j = 0;
int block_id = -999;//用于筛选单双ID
int BlockID = -999;//用于分组后调用
mySchool = (tschool *)calloc(10, sizeof(mySchool) * 3);
Beijing = (tcity *)calloc(10, sizeof(Beijing) * 3);
//给结构体变量赋初值
for (i = 1; i < 11; i++) {
mySchool[i].grade = i * 10;
mySchool[i].class = 10 - i;
mySchool[i].ID = i;
}
printf("Before ranking!\n");
//打印初始化结构体
for (i = 1; i < 11; i++) {
printf("grade of mySchool[%d] is: %d\n", i, mySchool[i].grade);
printf("class of mySchool[%d] is: %d\n", i, mySchool[i].class);
printf("ID of mySchool[%d] is: %d\n", i, mySchool[i].ID);
printf("*************\n");
}
printf("After ranking!\n");
//根据每一个学校ID是单还是双分成两组,分别打包成两个Block
for (j = 1; j < 11; j++) {
block_id = mySchool[j].ID % 2;
Beijing->Block[block_id].rankSchool[j] = mySchool[j];
}
//打印分组之后的各组学校信息
BlockID = 0;
printf("printing Block - 0\n");
for(i = 2; i < 11; i+=2) {
printf("grade of Block[0].rankSchool[%d] is: %d\n", i, Beijing->Block[BlockID].rankSchool[i].grade);
printf("class of Block[0].rankSchool[%d] is: %d\n", i, Beijing->Block[BlockID].rankSchool[i].class);
printf("ID of Block[0].rankSchool[%d] is: %d\n", i, Beijing->Block[BlockID].rankSchool[i].ID);
printf("*************\n");
}
BlockID = 1;
printf("printing Block - 1\n");
for(i = 1; i < 11; i+=2) {
printf("grade of Block[1].rankSchool[%d] is: %d\n", i, Beijing->Block[BlockID].rankSchool[i].grade);
printf("class of Block[1].rankSchool[%d] is: %d\n", i, Beijing->Block[BlockID].rankSchool[i].class);
printf("ID of Block[1].rankSchool[%d] is: %d\n", i, Beijing->Block[BlockID].rankSchool[i].ID);
printf("*************\n");
}
free(mySchool);
free(Beijing);
return 0;
}