What is wrong with this code - maze in C? - c

Well, I am trying to create a maze in C. When I try running the code (picture below) the output is 101010101010 and it doesn't stop until I use Ctrl-C or Ctrl-Z.
n - for example: n = 3 ->
1 1 1
1 1 1
1 1 1
Maze has size 2n+1 x 2n+1 because I decided to create an array which contains both numbers and walls. It is how it is supposed to look like:
x x x x x x x
x 1 1 1 x
x x
x 1 1 1 x
x x
x 1 1 1 x
x x x x x x x
The blank spaces are supposed to be walls.
Does anyone have an idea what's wrong?
The code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n = 4;
int maze[(2 * n) + 1][(2 * n) + 1];
// creating maze
for (int i = 0; i < (2 * n) + 1; i++) {
for (int j = 0; j < (2 * n) + 1; j++) {
maze[(2 * i) - 1][(2 * j) - 1] = 1;
if (2 * 1 == 0 || 2 * j == 0)
maze[2 * i][2 * j] = 0;
else
maze[2 * i][2 * j] = 1;
printf("%d", maze[i][j]);
}
}
}
The output is:

There are multiple problems in the code:
The code has undefined behavior because you write beyond the end of the matrix in maze[(2 * i) - 1][(2 * j) - 1] = 1;, maze[2 * i][2 * j] = 0; and maze[2 * i][2 * j] = 1;
Since i and j vary from 0 to 2 * n, you should just refer to maze[i][j].
Furthermore, the test if (2 * 1 == 0 || 2 * j == 0) probably has a typo and should be changed to
if (i == 0 || j == 0)
You should output a newline after each row.

Related

Fastest way to compute maximal n s.t. n over k <= x

I'm looking for a fast way to compute the maximal n s.t. n over k <= x for given k and x.
In my context n \leq n' for some known constant n', lets say 1000. k is either 1,2, or 3 and x is choosen at random from 0 ... n' over k
My current approach is to compute the binomial coefficient iterativly, starting from a_0 = k over k = 1. The next coefficient a_1 = k+1 over k can be computed as a_1 = a_0 * (k+1) / 1 and so on.
The current C code looks like this
uint32_t max_bc(const uint32_t a, const uint32_t n, const uint32_t k) {
uint32_t tmp = 1;
int ctr = 0;
uint32_t c = k, d = 1;
while(tmp <= a && ctr < n) {
c += 1;
tmp = tmp*c/d;
ctr += 1;
d += 1;
}
return ctr + k - 1;
}
int main() {
const uint32_t n = 10, w = 2;
for (uint32_t a = 0; a < 10 /*bc(n, w)*/; a++) {
const uint32_t b = max_bc(a, n, w);
printf("%d %d\n", a, b);
}
}
which outputs
0 1
1 2
2 2
3 3
4 3
5 3
6 4
7 4
8 4
9 4
So I'm looking for a Bittrick or something to get around the while-loop to speed up my application. Thats because the while loop gets executedat worst n-k times. Precomputation is not an option, because this code is part of a bigger algorithm which uses a lot of memory.
Thanks to #Aleksei
This is my solution:
template<typename T, const uint32_t k>
inline T opt_max_bc(const T a, const uint32_t n) {
if constexpr(k == 1) {
return n - k - a;
}
if constexpr (k == 2) {
const uint32_t t = __builtin_floor((double)(__builtin_sqrt(8 * a + 1) + 1)/2.);
return n - t - 1;
}
if constexpr (k == 3) {
if (a == 1)
return n-k-1;
float x = a;
float t1 = sqrtf(729.f * x * x);
float t2 = cbrtf(3.f * t1 + 81.f * x);
float t3 = t2 / 2.09f;
float ctr2 = t3;
int ctr = int(ctr2);
return n - ctr - k;
}
if constexpr (k == 4) {
const float x = a;
const float t1 = __builtin_floorf(__builtin_sqrtf(24.f * x + 1.f));
const float t2 = __builtin_floorf(__builtin_sqrtf(4.f * t1 + 5.f));
uint32_t ctr = (t2 + 3.f)/ 2.f - 3;
return n - ctr - k;
}
// will never happen
return -1;
}
If k is really limited to just 1, 2 or 3, you can use different methods depending on k:
k == 1: C(n, 1) = n <= x, so the answer is n.
k == 2: C(n, 2) = n * (n - 1) / 4 <= x. You can solve the equation n * (n - 1) / 4 = x, the positive solution is n = 1/2 (sqrt(16x + 1) + 1), the answer to the initial question should be floor( 1/2 (sqrt(16x + 1) + 1) ).
k == 3: C(n, 3) = n(n-1)(n-2)/6 <= x. There is no nice solution, but the formula for the number of combinations is straightforward, so you can use a binary search to find the answer.

How can I make the code print 1234 2341 3412 4123 while using the map container

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> //malloc library
void ft_putchar(char c)
{
write(1, &c, 1);
}
int main(void)
{
int r;
int c;
int num;
int *map;
int i;
r = 4;
c = 4;
i = 0;
map = malloc((r * c) * (sizeof(int)));
num = 1;
while (map[i] < r * c)
{
ft_putchar(num + '0');
ft_putchar(' ');
num++;
if (num == 5)
{
ft_putchar('\n');
num = 1;
}
i++;
}
free(map);
return (0);
}
I got the code to output
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
in a 4x4 format but I need help to make it
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
in a 4x4 format.
I'm sorry if this looks silly but I'm really new to coding, any help is appreciated!
Basically, you need to rotate elements in an array left one position at a time, and then do that n-1 times for n being the length of the array.
--------------v
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
<-- <-- <--
This individual rotation broken out into a very straightforward function.
void rotate_left1(int *arr, size_t n) {
int first = arr[0];
for (size_t i = 1; i < n; ++i) {
arr[i-1] = arr[i];
}
arr[n-1] = first;
}
In your code, please note that C does allow for variable length arrays, and your map lives in main so there is no need to dynamically allocate it unless you scale it to a point where it will not be able to live on the stack.
I have modified your code to avoid the undefined behaviour in the loop condition you are not asking about in order that it will in fact run in my test:
This will rotate the sequence 1 2 3 4 on each output line.
int r = 4;
int c = 4;
int* map = malloc((r * c) * (sizeof(*map)));
int start = 0 ;
int num = start ;
for( int i = 0; i < r * c; i++ )
{
ft_putchar( num + '1');
ft_putchar(' ');
num = (num + 1) % 4 ;
if( num == start)
{
ft_putchar('\n');
start = (start + 1) % 4 ;
num = start ;
}
}
free(map);
I have removed the separate instantiation/initialisation nonsense you had - don't do that.
The solution increments the start value on each iteration and uses modulo-4 arithmetic to wrap from 3 to zero. The output is + '1' rather then + '0' because arithmetically it is easier to use 0 to 3 rather then 1 to 4 (it allows the use of the % modulo operator).
The original code wasn't making use of the map array so I modified it to first populate map then just print what's in the array.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> //malloc library
void ft_putchar(char c)
{
write(1, &c, 1);
}
int main(void)
{
int rows = 4;
int cols = 4;
char *map;
map = malloc((rows * cols) * (sizeof(char)));
for(int r = 0 ; r < rows ; ++r)
for(int c = 0 ; c < cols ; ++c)
map[(r * cols) + c] = '0' + ((r + c) % cols) + 1;
for(int i = 0 ; i < (rows * cols) ; ++i)
{
ft_putchar(map[i]);
if(i % cols == (cols - 1))
ft_putchar('\n');
}
free(map);
return 0;
}
Of course, there really isn't a need for map, and getting rid of it makes the code that much simpler:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> //malloc library
void ft_putchar(char c)
{
write(1, &c, 1);
}
int main(void)
{
int rows = 4;
int cols = 4;
for(int r = 0 ; r < rows ; ++r)
for(int c = 0 ; c < cols ; ++c)
{
ft_putchar('0' + ((r + c) % cols) + 1);
if(((r * cols) + c) % cols == (cols - 1))
ft_putchar('\n');
}
return 0;
}

I need to determine the successive odd numbers whose sum is equal to n^3, for n = 1, ..., 20 (as an example 1^3 = 1; 2^3 = 3 + 5; 3^3 = 7 + 9 + 11)

I tried to solve it on my own way, but instead of giving me consecutive odd numbers, it gave me the result of a cubic number. How can I make so it'll give me, after the compilation, consecutive odd numbers whose sum equals to n^3(cubic number) like the examples shown above? Thanks in advance and also do not forget to explain me how you did it. Please use C, when giving a much more viable solution.
#include <stdio.h>
#include <math.h>
int main()
{
int n, sum;
printf("Value of n= ");
scanf("%d",&n);
for(int n=1; n<=20; n++)
{
if(n%2!=0);
}
printf("%d", sum=pow(n,3));
return 0;
}
Instead of thinking it like that, I tried a few numbers and found the solution in math. I guess this is not what you wanted, but it does work and consists of only odd numbers.
1^3=1
2^3=3+5
3^3=7+9+11
4^3=13+15+17+19
5^3=21+23+25+27+29
...
x^3=[x*(x-1)+1]+[x*(x-1)+3]+...+[x*(x-1)+2x-1]
for math proof, define it as a series:
An=x^2-x+1+2(n-1)=x^2-x+1+2n-2=x^2-x+2n-1
Sx=(A1+Ax)*x/2=[(x^2-x+1)+(x^2-x+2x-1)]*x/2=(2x^2)*x/2=x^3
Also, because n(n-1) is always even, the numbers must be odd.
to write it as code:
void printOddNumbers(int n)
{
int a1 = n * (n - 1) + 1;
for(int i = 0; i < n; i++)
{
printf("%d+", a1 + 2 * i);
}
printf("\b=%d^3=%d\n", n, n * n * n);
}
So the output will look like: 13+15+17+19=4^3=64.
So, you have an input, n, which is the number of consecutive odd numbers, which should yield a given sum as a result. So, this is how it looks alike:
sum = k + (k + 2) + ... + (k + 2n - 2) =
= n * k + 2 * (1 + 2 + ... + n - 1) =
= n * k + 2 (n * (n - 1) / 2) =
= n * k + n * (n - 1) =
= n * (n + k - 1)
n is known, k is an unkown odd number. So, for sum = 27 and n = 3 this would mean
3 * (3 + k - 1) = 27
3 + k - 1 = 9
k + 2 = 9
k = 7
7 + 9 + 11 = 27
For sum = 125, k = 5:
5 * (5 + k - 1) = 125
5 + k - 1 = 25
k = 21
21 + 23 + 25 + 27 + 29 = 125
So, the implementation would look like this:
int getK(int n, int sum) {
int k = (sum / n) - n + 1;
int currentSum = k;
int result = k;
for (int i = 1; i < n; i++) currentSum += 2 * i + k;
return ((currentSum == sum) && (k % 2)) ? k : 0;
}
Explanation: We return the smallest of the set when the problem is solvable. If it is not an odd, then we return 0 as a sign of error. Also, if the sum does not add up, then the problem is unsolvable and we return 0.

Math. Sorting. Do "n * (n + 1) / 2" always less than "n * n"? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
Please see code below. The code sorts an array in exactly n * (n + 1) / 2 iterations. I took the formula from Wikipedia 1 + 2 + 3 + 4 +.... No need to prove it, lets assume it just works.
#include <stdio.h>
int A[] = {3,1,4,8,6,17};
int nruns = 0;
#define N sizeof(A) / sizeof(int)
int imin(int idx){
int im = idx;
for(int i = idx; i < N; ++i, ++nruns)
if(A[i] < A[im])im = i;
return im;
}
int swap(li, ri){
int t = A[li];
A[li] = A[ri];
A[ri] = t;
return 0;
}
int main()
{
int im;
for(int i = 0; i < N; ++i){
im = imin(i);
swap(i, im);
}
for(int i = 0; i < N; ++i)
printf("%d ", A[i]);
printf("\nN = %d\nN*N = %d\nnruns = %d\n", N, N*N, nruns);
/*
(n*n + n) / 2 < n*n
Is above always true ?
*/
return 0;
}
This code at OnlineGDB
My question is, is it always true that "n * (n + 1) / 2" is less than "n * n" ?
Suppose n > 0. Then, if n * (n + 1) / 2 < n * n is true, (n + 1) / 2 < n is also true, thus, n + 1 < 2 * n, so n > 1. If (n > 0) AND (n > 1), then n > 1.
Suppose n < 0. Then, if n * (n + 1) / 2 < n * n is true, (n + 1) / 2 > n is also true, thus, n + 1 > 2 * n, so n < 1. If (n < 0) AND (n < 1) then n < 0.
Which means that this is true if (n > 1) OR (n < 0).
Suppose n is real and n < 0 or n > 1.
n•(n+1)/2 < n2 if and only if there is a positive h such that n•(n+1)/2 + h = n2.
So h would be n2 − n•(n+1)/2. Is this positive? It equals n2/2 − n/2. If n < 0, both n2/2 and n/2 are positive, so h is positive. If n > 1, n2/2 − n/2 = n•(n−1)/2, and both n and (n−1)/2 are positive, so h is positive. So, for n < 0 or n > 1, n•(n+1)/2 < n2.
On the other hand, if 0 ≤ n ≤ 1, we have h = n•(n−1)/2, and we can see that n is positive or zero while (n−1)/2 is negative or zero, so h is not positive, so n•(n+1)/2 ≥ n2.

C - Only one pointer coordinate adds up, the rest is equal to 0

I have a pointer to an array of ints and I declare initial coordinates values in cells from j+1 to j+3. Iteration of js are just indeces of objects. In cells from j+4 to j+6 I assign the velocity vectors values x,y,z thanks to which, the object should be moved in next steps.
int * objects = (int *)malloc(amount_of_objects * 7 * sizeof(int));
if (x_vector != 0 || y_vector != 0 || z_vector != 0) {
for (int j = 0; j < amount_of_objects; ++j) {
*(objects + (j * 4)) = j;
*(objects + (j * 4 + 1)) = x_start;
*(objects + (j * 4 + 2)) = y_start;
*(objects + (j * 4 + 3)) = z_start;
*(objects + (j * 4 + 4)) = x_vector;
*(objects + (j * 4 + 5)) = y_vector;
*(objects + (j * 4 + 6)) = z_vector;
}`
However after I tried to increase the x,y,z coords with arithemtic of pointers only the x value increases - y and z remain equal to 0. What is more interesting the y and z velocity vectors equal 0 somehow as well.
for (int k = 0; k < current_amount_of_objects; ++k) {
*(objects + k * 7 + 1) += *(objects + k * 7 + 4);
*(objects + k * 7 + 2) += *(objects + k * 7 + 5);
*(objects + k * 7 + 3) += *(objects + k * 7 + 6);
}`
Why does that happen? Am I screwing sth up with the pointers? Any suggestions please?
You have 7 ints per "object", but for some reason you are multiplying by 4.
Your code should be:
for (int j = 0; j < amount_of_objects; ++j) {
*(objects + (j * 7)) = j;
*(objects + (j * 7 + 1)) = x_start;
...
This code would be much clearer and less error-prone if you made a struct containing the 7 ints, and then worked in terms of those structs.
You are scaling by 4 in the first code block and 7 in the second code block. Assuming you want the layout of the accesses to be the same, you should use the same size. Index with y*Y_SIZE + x. I assume you want to multiply by 7 and not 4 because you are writing seven values at a time.
Also, you should probably not hard code the size, to avoid this issue in the future.

Resources