Creating a specific pattern with two-dimensional array in scala - arrays

So my problem is that I would want to change two-dimensional int array's values to 1 so that the array would look like this
0 0 1 0 0
0 1 1 1 0
1 1 1 1 1
0 1 1 1 0
0 0 1 0 0
I have a parameter "size" in my function that equals to the array size. So I would want to create this pattern regardless of the array size
Example with size equal to 9:
0 0 0 0 1 0 0 0 0
0 0 0 1 1 1 0 0 0
0 0 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1 0
0 0 1 1 1 1 1 0 0
0 0 0 1 1 1 0 0 0
0 0 0 0 1 0 0 0 0
Oh and size is always an odd integer obviously so that it is possible to create this tilted square "shape". Please Help!!

It should be like this:
def createDiamond(size: Int) = {
require(size % 2 != 0, "size must be odd")
def innerIterator(limit: Int) = {
(0 until size).map{ column =>
if(column > ((size / 2) + limit) || column < ((size / 2) - limit)) "0"
else "1"
}.mkString(" ") + "\n"
}
val str = (0 until size).map{ row => if(row <= size / 2) innerIterator(row) else innerIterator(size - row - 1)}.mkString("")
println(str)
}

def createFilter(size: Int, value: Int) :Array[Array[Int]] = {
val middle = size / 2
if (size % 2 == 1) {
Array.fill(size, size)(value)
} else {
Array.tabulate(size + 1, size + 1)((x, y) =>
if (abs(middle - x) + abs(middle - y)
<= middle) value else 0)
}
}

Related

Create a matrix blockwise attaching blocks like a stairway MATLAB

I want to build an Array containing of different blocks in the following way.
Given the block I want to repeat the block n-times so that it looks like this:
A =
1 0 0 -1 0 0 0 0 0 1 0 0
0 1 0 0 -1 0 0 0 0 0 1 0
0 0 1 0 0 -1 0 0 0 0 0 1
and I want the Array look like this, n times repeating the scheme:
newArray =
1 0 0 -1 0 0 0 0 0 1 0 0
0 1 0 0 -1 0 0 0 0 0 1 0
0 0 1 0 0 -1 0 0 0 0 0 1
1 0 0 -1 0 0 0 0 0 1 0 0
0 1 0 0 -1 0 0 0 0 0 1 0
0 0 1 0 0 -1 0 0 0 0 0 1
and so on...
With the free space being zeros, since the final array should be a sparse array either way.
How can I repeat and attach the block without using loops?
I'm assuming that the leftward offset of each block with respect to a pure block-diagonal matrix is the number of rows of A, as in your example.
You can build a matrix t that 2D-convolved with A gives the result, as follows:
A = [1 2 3 4; 5 6 7 8]; % data matrix
n = 3; % number of repetitions
[r, c] = size(A);
d = c-r;
t = zeros(r*(n-1)+1, d*(n-1)+1);
t(1:(r*(n-1)+1)*d+r:end) = 1;
result = conv2(t,A);
This gives
A =
1 2 3 4
5 6 7 8
result =
1 2 3 4 0 0 0 0
5 6 7 8 0 0 0 0
0 0 1 2 3 4 0 0
0 0 5 6 7 8 0 0
0 0 0 0 1 2 3 4
0 0 0 0 5 6 7 8
Here is a solution using kron:
n = 5; % number of repetitions
v = 3; % overlapping
s = size(A);
B = A(:,1:s(2)-v)
C = zeros(s(1),s(2)-v);
C(:,end-v+1:end) = A(:,end-v+1:end);
result = kron(eye(n) , B);
result(end,end+v)=0;
result(:,v+1:end) = result(:,v+1:end) + kron(eye(n) , C);
When the matrix size is large you can use sparse matrix:
n = 5;
v = 3;
s = size(A);
B = sparse(A(:,1:s(2)-v));
C = sparse(s(1),s(2)-v);
C(:,end-v+1:end) = A(:,end-v+1:end);
result = kron(eye(n) , B);
result(end,end+v) = 0;
result(:,v+1:end) = result(:,v+1:end) + kron(eye(n) , C);

finding minimum number of rectangular pieces in a rectangular chocolate bar, with a rule

I'm having trouble with my school homework. I have a chocolate bar that consists of either black, white or black & white (mixed) squares. I'm supposed to divide it in two groups, one that has only white or black&white pieces and the other that has only black or black&white pieces. Dividing the chocolate bar means cracking it either horizontally or vertically along the line that separates individual squares.
Given a layout of a chocolate bar, I am to find an optimal division which separates dark and white cubes and results in the smallest possible number of pieces, the chocolate bar being not bigger than 50x50 squares.
The chocolate bar is defined on the standard input like this:
first line consists of two integers M (number of rows in chocolate bar) and N (no. of columns), then there M columns each consisting of N characters symbolizing individual squares (0-black, 1-white, 2-mixed)
Some examples of an optimal division, their inputs respectively (correct outputs are 3 and 7):
3 3
1 1 2
1 2 0
2 0 0
4 4
0 1 1 1
1 0 1 0
1 0 1 0
2 0 0 0
My problem is that I managed to work out a solution, but the algorithm I'm using isn't fast enough, if the chocolate bar is big like this for example:
40 40
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 1 2 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 2 1 2 1 2 0 0 1 2 2 0 0 0 0 0 0 0 0 1 1 2 1 2 0 0 0 0 0 0 0 0 0 0
0 0 0 1 2 2 0 1 1 1 1 1 0 0 1 2 2 0 0 0 0 0 1 0 0 2 2 1 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 2 2 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 1 1 2 2 0 0 0 1 2 2 1 2 1 0 0 0 0 0 1 2 1 2 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 2 2 1 2 0 0 0 0 0 2 1 2 2 0 0 0 0 0 2 1 2 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 2 2 2 1 1 0 0 0 0 0 2 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 0 0 0 0 0
0 2 1 2 1 0 2 2 2 2 1 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 1 2 0 2 2 1 0 0 0 0 0 0
0 2 2 1 2 0 1 2 2 1 1 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 1 1 0 0 0 0 0 0
0 2 2 1 2 0 0 0 0 2 1 2 1 2 1 1 2 0 2 0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 0 0 0 0 0 2 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
then it takes 10 seconds for my program to solve it (correct solution for that one is 126 and I should be able to solve it in under 2 seconds!)
My algorithm works roughly with some minor optimization like this: iterate through all possible lines where it's possible to cut and then recursively do the same for the 2 newly emerged rectangles, if they cannot be divided anymore, then return 1.
The function after it iterates trough all the possible cuts always returns the minimum, once the minimum is found then store it and if I'd happen to need to solve this rectangle again then just return the value.
I thought that maybe If I happen to have already solved a particular rectangle and now I need to solve one that is one row or column bigger or smaller, then I could somehow use the solution I already have for that one and use it for the new one. But I really don't know how would i implement such a feature.
Right now my algorithm treats it like a completely new unsolved rectangle.
My code so far:
#include <stdio.h>
#include <stdlib.h>
unsigned int M, N;
unsigned int ****pieces; ////already solved rectangles, the value of pieces[y0][x0][y1][x1] is the optimal number of pieces in which the particular rectangle(that has upperleft corner in [x0,y0] and bottomright corner in[x1,y1]) can be divided
int ****checked;
unsigned int inf;
unsigned int minbreaks(int mat[M][N], unsigned int starti, unsigned int startj, unsigned int maxi, unsigned int maxj) {
if (pieces[starti][startj][maxi][maxj] != 0) {
return pieces[starti][startj][maxi][maxj];
} else {
unsigned int vbreaks[maxj - 1];
unsigned int hbreaks[maxi - 1];
for (unsigned int i = 0; i < maxj - 1; i++) {
vbreaks[i] = inf;
}
for (unsigned int i = 0; i < maxi - 1; i++) {
hbreaks[i] = inf;
}
unsigned int currentmin = inf;
for (unsigned int i = starti; i < maxi; i++) {
for (unsigned int j = startj; j < maxj - 1; j++) {
if (mat[i][j] != 2) {
for (unsigned int k = startj + 1; k < maxj; k++) {
if (vbreaks[k - 1] == inf) {
for (unsigned int z = starti; z < maxi; z++) {
if (!checked[i][j][z][k]) {
if (mat[z][k] != 2 && mat[i][j] != mat[z][k]) {
vbreaks[k - 1] = minbreaks(mat, starti, startj, maxi, k) + minbreaks(mat, starti, k, maxi, maxj);
if (vbreaks[k - 1] < currentmin) {
currentmin = vbreaks[k - 1];
}
break;
}
checked[i][j][z][k] = 1;
}
}
}
}
}
}
}
for (unsigned int i = starti; i < maxi - 1; i++) {
for (unsigned int j = startj; j < maxj; j++) {
if (mat[i][j] != 2) {
for (unsigned int k = starti + 1; k < maxi; k++) {
if (hbreaks[k - 1] == inf) {
for (unsigned int z = startj; z < maxj; z++) {
if (!checked[i][j][k][z]) {
if (mat[k][z] != 2 && mat[i][j] != mat[k][z]) {
hbreaks[k - 1] = minbreaks(mat, starti, startj, k, maxj) + minbreaks(mat, k, startj, maxi, maxj);
if (hbreaks[k - 1] < currentmin) {
currentmin = hbreaks[k - 1];
}
break;
}
checked[i][j][k][z] = 1;
}
}
}
}
}
}
}
if (currentmin == inf) {
currentmin = 1;
}
pieces[starti][startj][maxi][maxj] = currentmin;
return currentmin;
}
}
int main(void) {
FILE *file = stdin;
fscanf(file, "%u %u", &M, &N);
int mat[M][N];
pieces = malloc(sizeof (unsigned int***)*M);
checked = malloc(sizeof (int***)*M);
for (unsigned int i = 0; i < M; i++) {//initialize the pieces,checked and mat arrays.
pieces[i] = malloc(sizeof (unsigned int**)*N);
checked[i] = malloc(sizeof (int**)*N);
for (unsigned int j = 0; j < N; j++) {
int x;
fscanf(file, "%d", &x);
mat[i][j] = x;
pieces[i][j] = malloc(sizeof (unsigned int*)*(M + 1));
checked[i][j] = malloc(sizeof (int*)*M);
for (unsigned int y = i; y < M + 1; y++) {
pieces[i][j][y] = malloc(sizeof (unsigned int)*(N + 1));
for (unsigned int x = j; x < N + 1; x++) {
pieces[i][j][y][x] = 0;
}
}
for (unsigned int y = 0; y < M; y++) {
checked[i][j][y] = malloc(sizeof (int)*N);
for (unsigned int x = 0; x < N; x++) {
checked[i][j][y][x] = 0;
}
}
}
}
inf = M * N + 1; //number one bigger than maximal theoretically possible number of divisions
unsigned int result = minbreaks(mat, 0, 0, M, N);
printf("%u\n", result);
return (EXIT_SUCCESS);
}
So anybody has any idea for improvements?
For any arbitrary rectangle, we can know if it contains either no white or no black pieces in O(1) time, with O(M * N) preprocessing of matrix prefix-sums for white and black separately (count 1 for each piece).
We can store potential horizontal and vertical split points separately in two k-d trees for O(log(|splitPoints|) + k) retrieval for an arbitrary rectangle, again preprocessing the entire input.
After that, a general recursive algorithm could look like:
f(tl, br):
if storedSolution(tl, br):
return storedSolution(tl, br)
else if isValid(tl, br):
return setStoredSolution(tl, br, 0)
best = Infinity
for p in vSplitPoints(tl, br):
best = min(
best,
1 +
f(tl, (p.x-1, br.y)) +
f((p.x, tl.y), br)
)
for p in hSplitPoints(tl, br):
best = min(
best,
1 +
f(tl, (br.x, p.y-1)) +
f((tl.x, p.y), br)
)
return setStoredSolution(tl, br, best)
There is a dynamic programming approach to this, but it won't be cheap either. You need to fill in a load of tables giving, for each size and position of rectangle within the main square, the minimum number of divisions necessary to divide up that smaller rectangle fully.
For a rectangle of size 1x1 then answer is 0.
For a rectangle of size AxB look and see if all of its cells are uniform enough that the answer is 0 for that rectangle. If so, fine. If not try all possible horizontal and vertical divisions. Each of these divisions gives you two smaller rectangles. If you work out the answers for all rectangles of size A-1xB and smaller and size AxB-1 and smaller before you try and work out the answers for rectangles of size AxB you all ready know the answers for the two smaller rectangles. So for each possible division, add up the answers for the two smaller rectangles and add one to get the cost for that division. Chose the division that gives you the smallest cost and that gives you the answer for your current AxB rectangle.
Working out the answers for all smaller rectangles before larger rectangles, the very last answer you work out gives you the optimum number of divisions for the full square. The easiest way to work out what the best division is is to keep a little extra information for each rectangle, recording what the best division found was.
For an NxN square there are O(N^4) rectangles - any two points in the square define a rectangle as opposite corners. A rectangle of size O(N)xO(N) has O(N) possible divisions so you have something like an O(N^5) algorithm, or O(N^2.5) if N is the input size since an NxN square has input data of size O(N^2).
(You could also do something very like this by taking your original code and storing the results from calls to minBreaks() so that if minBreaks() is called more than once with the same arguments it simply returns the stored answer instead of recalculating it with yet more recursive calls to minBreaks()).
Thanks to everybody who helped me, my mistake was that in those nested loops I tried to avoid some unnecessary breaks, like this for example
1 1 -> 1 | 1
1 1 1 | 1
1 1 1 | 1
thinking it would speed up the runtime but the correct approach was just simply breaking the chocolate bar always everywhere possible.
Anyway for anyone interested here is my working code:
#include <stdio.h>
#include <stdlib.h>
unsigned int M, N;
unsigned int ****pieces; ////already solved rectangles, the value of pieces[y0][x0][y1][x1] is the optimal number of pieces in which the particular rectangle(that has upperleft corner in [x0,y0] and bottomright corner in[x1,y1]) can be divided
unsigned int inf;
int isOneColor(int mat[M][N], unsigned int starti, unsigned int startj, unsigned int maxi, unsigned int maxj) {
int c = 2;
for (unsigned int i = starti; i < maxi; i++) {
for (unsigned int j = startj; j < maxj; j++) {
if (c == 2) {
if (mat[i][j] != 2) {
c = mat[i][j];
}
} else if (c != mat[i][j] && mat[i][j] != 2) {
return 0;
}
}
}
return 1;
}
unsigned int minbreaks(int mat[M][N], unsigned int starti, unsigned int startj, unsigned int maxi, unsigned int maxj) {
if (pieces[starti][startj][maxi][maxj] != 0) {
return pieces[starti][startj][maxi][maxj];
} else if (isOneColor(mat, starti, startj, maxi, maxj)) {
return pieces[starti][startj][maxi][maxj] = 1;
} else {
unsigned int currentmin = inf;
for (unsigned int j = startj; j < maxj - 1; j++) {
unsigned int c = minbreaks(mat, starti, startj, maxi, j + 1) + minbreaks(mat, starti, j + 1, maxi, maxj);
if (c < currentmin) {
currentmin = c;
}
}
for (unsigned int i = starti; i < maxi - 1; i++) {
unsigned int c = minbreaks(mat, starti, startj, i + 1, maxj) + minbreaks(mat, i + 1, startj, maxi, maxj);
if (c < currentmin) {
currentmin = c;
}
}
pieces[starti][startj][maxi][maxj] = currentmin;
return currentmin;
}
}
int main(void) {
FILE *file = stdin;
//FILE *file = fopen("inputfile", "r");
fscanf(file, "%u %u", &M, &N);
int mat[M][N];
pieces = malloc(sizeof (unsigned int***)*M);
for (unsigned int i = 0; i < M; i++) {
pieces[i] = malloc(sizeof (unsigned int**)*N);
for (unsigned int j = 0; j < N; j++) {
int x;
fscanf(file, "%d", &x);
mat[i][j] = x;
pieces[i][j] = malloc(sizeof (unsigned int*)*(M + 1));
for (unsigned int y = i; y < M + 1; y++) {
pieces[i][j][y] = malloc(sizeof (unsigned int)*(N + 1));
for (unsigned int x = j; x < N + 1; x++) {
pieces[i][j][y][x] = 0;
}
}
}
}
inf = M * N + 1; //number that is bigger by one than maximal theoretically possible number of divisions
unsigned int result = minbreaks(mat, 0, 0, M, N);
printf("%u\n", result);
return (EXIT_SUCCESS);
}

Bit Expansion with finite width (Expanding PBM Images) in C

I am trying to expand a PBM image of say, 5x5 to 10x10 but I have hit somewhat of a road block.
I have read the header, and height / width with the following
int fSize = size(inFile);
char *inputBuffer = malloc(fSize);
int pbmHeight, pbmWidth;
memset(inputBuffer, 0, fSize);
if (!fgets(inputBuffer, sizeof(inputBuffer), inFile)) {
fprintf(stderr, "Unable to read image format.\n");
exit(-1);
}
if (inputBuffer[0] != 'P' || inputBuffer[1] != '4') {
fprintf(stderr, "Invalid image format.\n");
exit(-1);
}
if (fscanf(inFile, "%d %d", &pbmWidth, &pbmHeight) != 2) {
fprintf(stderr, "Invalid image size.\n");
exit(-1);
}
int i;
int bitRemainder = ((pbmWidth % 8) != 0 ? 8 - (pbmWidth % 8) : 0);
Then read the data
while (fgetc(inFile) != '\n');
fread(inputBuffer, pbmHeight * pbmWidth, 1, inFile);
I have a second char *secondPBM which contains another PBM image of the same height / width
What I am looking to do, is iterate through each bit of the 1st image, the 2nd image, compare, and then output specific bits to an output
For example, here is image 1 (Note the image width is 5, but it needs to fill 1 byte)
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Here is image 2
1 1 1 1 1 0 0 0
1 1 1 1 1 0 0 0
1 1 1 1 1 0 0 0
1 1 1 1 1 0 0 0
1 1 1 1 1 0 0 0
Based on image 1, and image 2 bits I need to output 4 bits so the new image size becomes 2 * pbmWidth
So for example, the output should be (a 10x10 image, with 6 bits set to 0 to fill the remaining byte) (The bit values in the 2nd image will be set with another piece of code and and isn't exactly what is listed here)
1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0
I'm reading the bit value of the 1st and 2nd image like this
Here are my getBitValue and setBitValue functions
int getBitVal(unsigned char *keyStrBin, int keyIndex) {
int keyMod = keyIndex % 8;
int keyIn = keyIndex / 8;
return (((keyStrBin[keyIn]) >> (7 - (keyMod))) & 1);
}
void setBitVal(unsigned char *keyC, int keyIndex) {
int keyMod = keyIndex % 8;
int keyIn = keyIndex / 8;
keyC[keyIn] |= (1 << (7 - (keyMod)));
}
int newWidth = 2 * pbmWidth;
int newHeight = 2 * pbmHeight;
int totalBits = newWidth * newHeight;
int newFileSize = (totalBits % 8 == 0) ? (totalBits / 8) : (totalBits / 8 + 1);
int bitRemainder = ((pbmWidth % 8) != 0 ? 8 - (pbmWidth % 8) : 0);
int newbitRemainder = ((newWidth % 8) != 0 ? 8 - (newWidth % 8) : 0);
for (i = 0; k = 0; i < newHeight * (newWidth + newbitRemainder); i++, k++) {
if (i != 0 && i % (pbmWidth - 1) == 0) {
i += (bitRemainder - 1);
}
if (k != 0 && k % (newWidth - 1) == 0) {
k += (newbitRemainder - 1);
}
if (getBitVal((unsigned char *)inputBuffer, i) == 0 && getBitVal(keyBuffer, k) == 0) {
// Code to set 1 bit to black in the 1st row, then set another bit to black in the 2nd row. For example, The bit at index 0 becomes a 1, then the bit at index 17 becomes a 1 (Making a 2x2 square)
// 1 0
// 0 1
// Then move on to the 2nd bit (or bit index 1) of the input image, compare.
}
else if (getBitVal((unsigned char *)inputBuffer, i) == 0 && getBitVal(keyBuffer, k) == 1) {
}
else if (getBitVal((unsigned char *)inputBuffer, i) == 1 && getBitVal(keyBuffer, k) == 0) {
}
else if (getBitVal((unsigned char *)inputBuffer, i) == 1 && getBitVal(keyBuffer, k) == 1) {
}
I can't seem to figure out how to set the bits in the comparative if statements.
I tried this, but it doesn't seem to work right.
setBitVal(pbmOut1Buffer, k * 2);
setBitVal(pbmOut1Buffer, (k * 2) + (newWidth + newbitRemainder) + 1);
Any help with this would be greatly appreciated. Thank you all in advance.

Fill odd sequences between ones in binary vector with value

I'm looking for a vectorized solution for this problem :
Let A a vector (great size : > 10000) of 0 and 1.
Ex :
A = [0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 1 etc]
I want to replace the 0 between the 1's (of odd ranks) by 2
i.e. to produce :
B = [0 0 0 1 2 2 2 2 2 1 0 0 0 1 2 2 1 0 0 1 2 1 etc]
Thanks for your help
It can be done quite easily with cumsum and mod:
A = [0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 1]
Short answer
A( mod(cumsum(A),2) & ~A ) = 2
A =
0 0 0 1 2 2 2 2 2 1 0 0 0 1 2 2 1 0 0 1 2 1
You requested to fill the islands of odd rank, but by changing mod(... to ~mod(... you can easily fill also the islands of even rank.
Explanation/Old answer:
mask1 = logical(A);
mask2 = logical(mod(cumsum(A),2))
out = zeros(size(A));
out(mask2) = 2
out(mask1) = 1
try using cumsum
cs = cumsum( A );
B = 2*( mod(cs,2)== 1 );
B(A==1) = 1;

Array of points algorithm

I'm having trouble designing an algorithm that will pretty much make a line move like in a snake game using an array that holds all the points on the line. I would do something like...
for (int x = 0; i < array.length; i++) {
array[i] = array[i+1]
}
array[array.length] = (the new point)
but this will happen many times a second and it is very slow. I thought of doing something similar but instead of moving each number every time, they stay in the same position in the array but an int is saved to keep track of which one will be removed next and which will contain the new nummber.
If you have any idea what I just said, please help me. Thanks
Use a circular buffer. This can be implemented using an array and two indices (one for head, one for tail). If the snake always has the same length, you can get away with using a single index.
With such a structure, the entire operation that you require can be done in constant time (i.e. independent of the size of the array).
You're correct to think that moving all of the blocks each time is slow.
There is a more efficient way to do it.
Only the first at last positions change with each move.
So, if you have your snake array[i] and a "head" marker head then you can simply march head through your array and overwrite the next location with where the head moved that turn.
The place you just overwrote? That was where the tail was, and you don't need it anymore.
It gets a little trickier if the snake grows, but not too much more so.
(The data structure, as NPE points out, is a circular buffer.)
int front, back, length; // 0<=front,back<length
increaseLength()
{
back--;
if(back<0)
back=length-1;
}
goForward()
{
front++;
back++;
if (front==length)
front=0;
if (back==length)
back=0;
}
checkFull() // check every time you increase length
{
if (back==front)
return true;
return false;
}
NPE is correct that a circular buffer is the best solution. This is a simple example of a circular buffer using C++. Notice the modulus operators instead of if tests.
#include <iostream>
int main(int argc, char **argv)
{
int front = 4;
int back = 0;
int length = 10;
int snake[10] = { 1,1,1,1,1,0,0,0,0,0 };
for (int i = 0; i < length * 3; i++)
{
for (int j = 0; j < length; j++)
std::cout << snake[j] << " ";
std::cout << std::endl;
snake[back] = 0;
front = (front + 1) % length;
back = (back + 1) % length;
snake[front] = 1;
}
}
Output:
1 1 1 1 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 1 0 0 0 0 0 1 1
1 1 1 1 0 0 0 0 0 1
1 1 1 1 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 1 0 0 0 0 0 1 1
1 1 1 1 0 0 0 0 0 1
1 1 1 1 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 1 0 0 0 0 0 1 1
1 1 1 1 0 0 0 0 0 1
Notice how the output nicely demonstrates the snake "moving" through the buffer.

Resources