c - 根据条件匹配数组元素

标签 c arrays

如果节点[i]和节点[i+1]存在于邻居[i]中,则存储节点的“i”位置并打印节点的“i”值。

这也是通过反转节点数组(仅)来完成的,并且对邻居[i]进行相同类型的检查和打印。

这段代码是我写的,效果很好,有没有其他有效的方法来执行这个。

#include <stdio.h>
int main()
{
    int node[5] = {44,5,4,6,40};
    int neighbor[4]= {40,3,4,6};
    int i=0,j=0,k=0;
    int found_indices[5]; // array used to store indices of found entries..
    int count = 0; //n entries found;
    int fwd_count=0;
    int postn;
    int find;
    // to find in forward direction
     for (i=0; i<4; i++) {
        for (j=0; j<4; j++) {
            if (node[i]==neighbor[j]) {
                postn=node[i];
                for (k=0; k<4; k++) {
                    if (node[i+1]==neighbor[k]) {
                      found_indices[fwd_count ++] = postn; // storing the index of found entry


                    }
                }
            }
        }
    }

   if (fwd_count!=0) {  
       for (i=0; i<fwd_count; i++)
           printf("forward relay for ==%d\n", found_indices[i]);

   } else{
     printf("Relay not found in forward\n");
  }



 // to find in backward direction
    for (i=4; i>0; i--) {
        for (j=0; j<4; j++) {
            if (node[i]==neighbor[j]) {
                postn=node[i];
                for (k=0; k<4; k++) {
                    if (node[i-1]==neighbor[k]) {
                      found_indices[count ++] = postn; // storing the index of found entry


                    }
                }
            }
        }
    }

   if (count!=0) {  
       for (i=0; i<count; i++)
           printf("backward relayy for ==%d\n", found_indices[i]);

   }else{
      printf("Relay not found in backward \n");
   }

}

最佳答案

更有效的方法是将neighbor 转换为位图。对于您的示例,您可以使用 6 个字节来完成(我假设可能的值从 0 到 40):

00000001 00000000 00000000 00000000 00000000 01011000

检查给定数字是否在邻居中只需检查该位是否已设置,这比循环数组更有效。

当然,这是一个简单的例子,没有任何意义。但是,如果你有更多的值(value)观,那么它就会得到返回。

关于c - 根据条件匹配数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14914376/

相关文章:

c - 将 char* 解析为标记时出现段错误

c - 如何使用 C 截断特定的 char[]

c - 为什么将此 double 转换为 int 会得到 0?

javascript - 如何在原型(prototype)函数中访问javascript对象数组

python - 如何使函数的返回值可迭代?

python - 通过 bool 索引数组进行 Numpy 数组赋值

c - 在循环中打印数组元素组

c - 如果换行符 '0A' 是文件的一部分,如何读取完整文件。

c - 用 C 实现 Malloc

javascript - 访问对象内对象的键和值