[Solved] text file into array C++ [closed]


Here’s a simple way to make the pattern you want from the data you have. I’m going to use an array rather than reading from a file, but it shouldn’t be hard to do that if you want to.

Basically, the trick is to look at the index of each item at each position in the output. If, instead of outputting the actual value you want, you look at the index of the value in the array, it looks like this:

5 5 5 5 5 5 5 5 5 5 5 
5 4 4 4 4 4 4 4 4 4 5 
5 4 3 3 3 3 3 3 3 4 5 
5 4 3 2 2 2 2 2 3 4 5 
5 4 3 2 1 1 1 2 3 4 5 
5 4 3 2 1 0 1 2 3 4 5 
5 4 3 2 1 1 1 2 3 4 5 
5 4 3 2 2 2 2 2 3 4 5 
5 4 3 3 3 3 3 3 3 4 5 
5 4 4 4 4 4 4 4 4 4 5 
5 5 5 5 5 5 5 5 5 5 5 

So now, think about what the coordinates of each position are. If we write it out as the coordinates, it looks like this:

<0,0> <1,0> <2,0> <3,0> <4,0> ... etc.
<0,1> <1,1> <2,1> <3,1> <4,1> ... etc.
<0,2> <1,2> <2,2> <3,2> <4,2> ... etc.
<0,3> <1,3> <2,3> <3,3> <4,3> ... etc.
... etc.

So how do those coordinates match up with the indexes? We obviously want the relationship to have something to do with their distances from the center of the square. So let’s subtract out the center coordinate from all the other coordinates:

<-5,-5> <-4,-5> <-3,-5> <-2,-5> ... etc.
<-5,-4> <-4,-4> <-3,-4> <-2,-4> ... etc.
<-5,-3> <-4,-3> <-3,-3> <-2,-3> ... etc.
<-5,-2> <-4,-2> <-3,-2> <-2,-2> ... etc.
...etc. 

So what’s the relationship? Notice how all along the top and left edge, there’s a -5? And we want our outermost result to be 5. And in all of the 2nd row and 2nd column, there’s a -4. We want the rest of those values to be a 4. So a pattern’s emerging here. It looks like you need to take the maximum of the absolute value of the coordinate to figure out the index. Then use the index to get the value to put there.

So putting it all together, it would look something like this (I substituted reading from a file for just using an array, but you can build the array from the file) :

    int distances[] = { 9, 5, 4, 3, 2, 1 };
    const int centerX   = 5;
    const int centerY   = 5;

    for (int x = 0; x < 11; x++)
    {
        for (int y = 0; y < 11; y++)
        {
            int largest = std::max (abs(x - centerX), abs(y - centerY));
            std::cout << distances [ largest ] << " ";
        }

        std::cout << "\n";
    }

4

solved text file into array C++ [closed]