发现周边元件和元件阵列中的 [英] find elements surrounding and element in an array

查看:108
本文介绍了发现周边元件和元件阵列中的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,我希望得到周围的数组中的特定元素的元素。例如,如果我有以下几点:

  [1,2,3,4,5,6]
 [8,9,7,5,2,6]
 [1,6,8,7,5,8]
 [2,7,9,5,4,3]
 [9,6,7,5,2,1]
 [4,7,5,2,1,3]

我如何找到各地的任何上述要素的8个元素。和我怎么照顾元素的边缘。

我想通了就是,写一个9号线code这一点,这是很明显的一种方式,有没有更好的解决办法?
谢谢


解决方案

 为(i = 0; I< array.length,我++){
            为(J = 0; J<阵[I]。长度; J ++){
                为(X = Math.max(0,I - 1); X&下; = Math.min第(i + 1,array.length); X ++){
                    对于(Y = Math.max(0,J - 1); Y< = Math.min(J + 1,
                            数组[I]。长度); Ÿ++){
                        如果(X GT; = 0&放大器;&放大器y与其所连接; = 0&放大器;&放大器; X&下; array.length
                                &功放;&安培; Y'LT;数组[我]。长度){
                            如果(X!= ||我Y!= j)条{
                            System.out.print(数组[X] [Y] +);
                            }
                        }
                    }
                }
                的System.out.println(\\ n);
            }
        }

感谢所有谁回答的人,但我理解了它与,我发现这个职位刚才,尤其是解决方案。再次感谢:)

I have a multidimensional array, I want to get the elements surrounding a particular element in that array. For example if I have the following:

[[1,2,3,4,5,6]
 [8,9,7,5,2,6]
 [1,6,8,7,5,8]
 [2,7,9,5,4,3]
 [9,6,7,5,2,1]
 [4,7,5,2,1,3]]

How do I find all the 8 elements around any of the above elements. and how do I take care of elements at the edges.

One way I figured out is, to write a 9 line code for this , which is obvious, is there a better solution? thanks

解决方案

for (i = 0; i < array.length; i++) {
            for (j = 0; j < array[i].length; j++) {
                for (x = Math.max(0, i - 1); x <= Math.min(i + 1, array.length); x++) {
                    for (y = Math.max(0, j - 1); y <= Math.min(j + 1,
                            array[i].length); y++) {
                        if (x >= 0 && y >= 0 && x < array.length
                                && y < array[i].length) {
                            if(x!=i || y!=j){
                            System.out.print(array[x][y] + " ");
                            }
                        }
                    }
                }
                System.out.println("\n");
            }
        }

Thanks to all the people who have answered, but i figured it out with the help of this post which i found just now, and above is the solution. thanks again :)

这篇关于发现周边元件和元件阵列中的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆