你好我试图“混合”两个字符串数组有一点问题,我已经搜索了它但我只找到了如何合并它们或连接它们,但那不是我需要的。
我有两个这样的int数组:
int no_items = 5;
int parent1[no_items], parent2[no_items];
如果数组包含例如:
parent1[0] = 1;
parent1[1] = 2;
parent1[2] = 3;
parent1[3] = 4;
parent1[4] = 5;
和
parent2[0] = 5;
parent2[1] = 1;
parent2[2] = 2;
parent2[3] = 3;
parent2[4] = 4;
给出一个“交叉”点,例如2: parent1应该有他的2个第一个元素和parent2的其余部分,而parent2应该有他的前2个元素和其余的parent1。所以结果应该是:
parent1: 1,2 | 5,3,4
parent2: 5,1 | 2,3,4
其中“|”是断点指数,不应重复其余元素。
我如何才能将这种混合两个int数组?谢谢你!
目前我有这个:
for(i = 0; i < cross_point; i++)
{
sprintf(buffer, "%d,", parent1[i]);
strcat(line1, buffer);
}
for(i = 0; i < cross_point; i++)
{
sprintf(buffer, "%d,", parent2[i]);
strcat(line2, buffer);
}
但我不知道如何比交叉点更进一步。
答案 0 :(得分:0)
这样的事情应该这样做:
int no_items = 5;
int output1[no_items];
int output2[no_items];
for (int i = 0; i < no_items; i++){
if(i < crosspoint){
output1[i] = parent1[i];
output2[i] = parent2[i];
}else{
output1[i] = parent2[i];
output2[i] = parent1[i];
}
}
如果你担心临时值,你需要交换值,逻辑应该与上面的相似。
int no_items = 5;
int temp = 0;
for (int i = 0; i < no_items; i++){
if(i < crosspoint){
/* don't need to do anything here */
}else{
temp = parent1[i];
parent1[i] = parent2[i];
parent2[i] = temp;
}
}
答案 1 :(得分:0)
int *find(int *begin, int *end, int value)
{
int *p = begin;
for ( ; p != end; ++p)
if (*p == value) break;
return p;
}
int i, j;
int output1[no_items] = {0};
int output2[no_items] = {0};
int crosspoint = 3;
memcpy(output1, parent1, crosspoint * sizeof(int));
for (i = crosspoint, j = 0; i < no_items; ++i)
{
while (find(output1, output1+i, parent2[j]) != output1+i) ++j;
output1[i] = parent2[j];
}
memcpy(output2, parent2, crosspoint * sizeof(int));
for (i = crosspoint, j = 0; i < no_items; ++i)
{
while (find(output2, output2+i, parent1[j]) != output2+i) ++j;
output2[i] = parent1[j];
}
memcpy(parent1, output1, sizeof(parent1));
memcpy(parent2, output2, sizeof(parent2));