Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

c# - Convert 1D array index to 2D array index

I have 2 arrays. I want to convert the index of the first array to the second. Is there a better way to do it than what I have below?

Array array1[9];
Array array2[3][3];

// Index is the index of the 1D array
public Point convert1Dto2D(int index)
{
        Point p = new Point();

        switch (index) {
            case 0:
                p.x = 0;
                p.y = 0;
                break;
            case 1:
                p.x = 0;
                p.y = 1;
                break;
            case 2:
                p.x = 0;
                p.y = 2;
                break;
            case 3:
                p.x = 1;
                p.y = 0;
                break;
            case 4:
                p.x = 1;
                p.y = 1;
                break;
            case 5:
                p.x = 1;
                p.y = 2;
                break;
            case 6:
                p.x = 2;
                p.y = 0;
                break;
            case 7:
                p.x = 2;
                p.y = 1;
                break;
            case 8:
                p.x = 2;
                p.y = 2;
                break;
        }

return p;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
p.x = index / 3;
p.y = index % 3;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...