c - 根据位置每 3 个元素从数组中删除元素

标签 c arrays if-statement indices array-difference

我创建了一个名为 elements_n 的数组,其中包含元素 0N-1,其中 N 为 2 . 下面的数字是名为 elements_n 的数组的元素:

0 1 

我有另一个名为 Arr 的数组,它包含以下元素:

0 1 3 1 2 4 

如果数组 Arr 的前 3 个元素中的任何一个等于 elements_n 的第一个元素,即 0,我想从名为 Arr 的数组中删除该元素。然后,我对数组 Arr 的接下来 3 个元素重复相同的过程。因此,为了更好地解释自己,我将使用以下示例:

将数组 Arr 的前 3 个元素(0、1、3)与 elements_n 的第一个元素(0)进行比较。由于 Arr[0] == elements_n[0]。我从数组 Arr 中删除 Arr[0]

将数组 Arr 的接下来 3 个元素(1、2、4)与 elements_n 的第二个元素(1)进行比较。由于 Arr[3] == elements_n[1]。我从数组 Arr 中删除 Arr[3]。因此数组 Arr 中应保留的元素是:

1 3 2 4

当我用 C 编程自己实现它并使用下面的代码时,最终结果如下:

 1       3       3       2       2       4

而不是:

  1       3       2       4

这是我实现的代码:

#include <stdio.h>
#include <stdlib.h>
#define N 2 

int main() {    
    unsigned *elements_n = malloc(N * sizeof(unsigned));

    for (int i = 0; i < N; i++) {
        elements_n[i] = i; //Created an array which has the elements 0 to N-1
    }
    printf("\n");

    unsigned Arr[6] = { 0, 1, 3, 1, 2, 4 };
    unsigned position_indices[2] = { 3, 3 };  //Moving every 3 elements in the Arr array. 

    int count = 0; 
    int index = 0;
    unsigned *ptr_Arr = &Arr[0];

    do {
        for (int i = 0; i < position_indices[count]; i++) {
            if (ptr_Arr[i] == elements_n[count]) {
                index = i + 1; //Index of the Arr element that has the same value as the element in the array elements_n 

                for (int j = index - 1; j < position_indices[count] - 1; j++) {
                    ptr_Arr[j] = ptr_Arr[j + 1];
                }
            }
        }
        printf("\n");
        ptr_Arr += position_indices[count] - 1; 
        count++;
    } while (count < 2);

    for (int i = 0; i < 6; i++) {
        printf("%d\t", Arr[i]);
    }
    printf("\n");

    free(elements_n);

    return 0;
}

最佳答案

您可以尝试类似的方法(未经测试)。

#include <stdio.h>
#include <stdlib.h>
#define N 2 

int main()
{ 
  unsigned *elements_n = malloc(N * sizeof(unsigned));
  for (int i = 0; i < N; i++)
  {
    elements_n[i] = i; //Created an array which has the elements 0 to N-1
  }

  unsigned Arr[6] = { 0, 1, 3, 1, 2, 4 };

  int dest_index = 0;
  int src_index = 0;
  int count = sizeof(Arr)/sizeof(Arr[0]); 

  for ( ; src_index < count; src_index++)
  {
    int group = src_index / 3;
    if (Arr[src_index] != elements_n[group])
    {
      Arr[dest_index++] = Arr[src_index];
    }
  }

  for (int i = 0; i < dest_index; i++)
  {
    printf("%d\t", Arr[i]);
  }
  printf("\n");

  free(elements_n);

  return 0;
}

关于c - 根据位置每 3 个元素从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50969861/

相关文章:

c - 将整数类型转换为指向c中整数的指针

c - 如何减少最小 Linux 进程的内存占用

javascript - AngularJS - 在前端显示数组值

arrays - cocoa 多维NSArray

VBA 2012 - 当用户输入文本而不是数字时需要返回错误

C StdLib malloc 来自 (N)ASM

c - 如果两者在 C 中具有相同的名称而不使用第三个变量,如何将局部变量复制到全局变量?

arrays - linux bash 从文件的每一行中剪切第一个单词,将其分配给一个数组并删除重复项

Javascript - 是否可以有 3 个“if”变量或者这是一个错误?

r - 条件的长度 > 1 并且只使用第一个元素