srand() in nested loop same results - c

So my task is to produce randomly generate weights and profits for batches of items(for 0/1 knapsack problem). I represented the batches in arrays in batch[]. My problem is that:
rand() is not generating unique random values in the second for loop. Is it because of the nested for loops?
The second for loop assigns values to p[j] and w[j] but as it follows j, at each iteration assigning of values start at j, how can I start it from 0 each time?
The output:
| 231 |25
| 231 |25
| 231 |25
| 231 |25
| 0 | 0
|19 | 4
|19 | 4
|19 | 4
|19 | 4
|19 | 4
main(){
srand(time(NULL));
int i, j, t;
int batch[] = { 4, 5 };
int sizeOfBatch = sizeof(batch) / sizeof(batch[0]);
for (i = 0; i < sizeOfBatch ; i++){
int *p = (int*)calloc(batch[i], sizeof(int));
int *w = (int*)calloc(batch[i], sizeof(int));
for (j = 0; j < batch[i]; j++){
p[j] = rand() % 500;
printf("\n| %d ", p[i]);
w[j] = rand() % 100;
printf("| %d ", w[i]);
}

You are assigning to p[j] (and w[j]) and printing p[i] (and w[i]); your problem is unrelated to srand() or rand().
p[j] = rand() % 500; // assign to p[j]
printf("\n| %d ", p[i]); // print p[i]
w[j] = rand() % 100;
printf("| %d ", w[i]);
In the 2nd loop, everytime the loop starts, j begins at 0
for (j = 0; j < batch[i]; j++) {
// first time through the loop, j is 0
}

Related

need some printing number pyramid

I need to program a number pattern pyramid like that:
Here is my code:
#include<stdio.h>
int main()
{
int i, j, rows = 5;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d ", j);
}
printf("\n");
}
for (i = 0; i <= 5; i++)
{
for (j = 0; j <= i; j++)
{
printf("%d ", j);
}
printf("\n");
}
}
Where am I doing wrong? I need to flip somehow the first triangle pattern and mix it with the second. Please help.
Your pyramid is 6 levels high. The max number is 5. This is not a coincidence. There is a direct relationship.
If n is 5, you need to do something 6 times, from 0 to n. There's a loop.
for (int i = 0; i <= n; i++) {
...
}
On each row you need to do print from i to 0, and then from 1 to i. That's two loops.
for (int j = i; j > 0; j--) {
...
}
for (int j = 1; j <= i; j++) {
...
}
Of course, you also need to indent a number of spaces inversely related to i, which is another loop.
for (int j = 0; j <= /* Fill in here for inverse relationship */; j++) {
...
}
I need to flip somehow the first triangle pattern and mix it with the second.
TL;DR The trick is very simple: your row index i should start from |n - j| (or abs(n - j)) where j is the column index and n is the number.
Here is how you can do it:
for (int j = 0; j < ncols; ++j) {
for (int i = abs(n - j); i < nrows; ++i) {
matrix[i][j] = '0' + abs(n - j);
}
}
Explanation:
Imagine you have a matrix. In order to build a pyramid with a number n, you will need:
n + 1 rows (since you will have 0 included in the top). Let's call it nrows.
2n + 1 columns (2n because the numbers will appear twice in a row, 1 because you will have one 0 per row). Let's call it ncols.
0 1 2 3 4 5 6 7 8 9 10
- - - - - - - - - - -
0 | 0
1 | 1 0 1
2 | 2 1 0 1 2
3 | 3 2 1 0 1 2 3
4 | 4 3 2 1 0 1 2 3 4
5 | 5 4 3 2 1 0 1 2 3 4 5
First, you want to fill the first half, i.e. from column 0 to n: for (int j = 0; j <= n; ++j).
J | End | Start | Pattern of Start
---------------------------------------
0 | N | N | N - 0
---------------------------------------
1 | N | N - 1 | N - 1
---------------------------------------
2 | N | N - 2 | N - 2
---------------------------------------
... | ... | ..... | N - J
---------------------------------------
N | N | 0 | N - N
The pattern is: for (int i = n - j; i < nrows; ++i). You would fill that first half with n - j.
Second, you want to fill the second half, i.e. from column n + 1 to 2n: for (int j = n + 1; j < ncols; ++j).
J | End | Start | Pattern of Start
------------------------------------------
N + 1 | N | 1 | N + 1 - N = J - N
------------------------------------------
N + 2 | N | 2 | N + 2 - N = J - N
------------------------------------------
N + 3 | N | 3 | N + 3 - N = J - N
------------------------------------------
..... | ... | ..... | N + X - N = J - N
------------------------------------------
2N | N | N | 2N - N = J - N
The pattern is: for (int i = j - n; i < nrows; ++i). You would fill that second half with j - n.
Now, you can do two separate for loops to fill the first and second halves.
// Fill first half
for (int j = 0; j <= n; ++j) {
for (int i = n - j; i < nrows; ++i) {
matrix[i][j] = '0' + n - j;
}
}
// Fill second half
for (int j = n + 1; j < ncols; ++j) {
for (int i = j - n; i < nrows; ++i) {
matrix[i][j] = '0' + j - n;
}
}
You can write one for loop by replacing n - j and j - n with abs(n - j), since both of them are positive values (see TL;DR above, or the code below).
Full functionning code:
#include <stdio.h>
#include <stdlib.h>
void print_matrix(const int nrows, const int ncols, const char matrix[nrows][ncols])
{
for (int i = 0; i < nrows; ++i) {
for (int j = 0; j < ncols; ++j)
printf("%c ", matrix[i][j]);
printf("\n");
}
}
void init_matrix(const int nrows, const int ncols, char matrix[nrows][ncols], const char value)
{
for (int i = 0; i < nrows; ++i)
for (int j = 0; j < ncols; ++j)
matrix[i][j] = value;
}
void print_pyramid(const int n)
{
// Calculate the number of rows and columns
const int nrows = n + 1;
const int ncols = n * 2 + 1;
char matrix[nrows][ncols];
// Initialization
init_matrix(nrows, ncols, matrix, '\0');
// Fill the matrix
for (int j = 0; j < ncols; ++j) {
for (int i = abs(n - j); i < nrows; ++i) {
matrix[i][j] = '0' + abs(n - j);
}
}
// Printing
print_matrix(nrows, ncols, matrix);
}
int main(void)
{
print_pyramid(5);
}
You have to include all 3 for loops in one for loop which runs 6 times. First you have to print spaces. Then first half of the triangle and then the other half. After that you have to print \n .
#include<stdio.h>
int main()
{
int i, j,k,l;
for (i = 0; i <=5; i++)
{
for (j = 5; j > i; j--)
{
printf(" ");
}
for (k = i; k >=0; k--)
{
printf("%d ", k);
}
for (l = 1; l <=i; l++)
{
printf("%d ", l);
}
printf("\n");
}
}

Length of a growing substring in matrix

Given a square matrix find the length of sub string that is growing for example.
matrix | result because of
5 |
1 2 3 4 5 |
2 5 2 5 9 |
7 8 9 0 1 --> 5 --> 1 2 3 4 5
0 0 0 0 0 |
2 3 6 1 2 |
I try to compare a[i][j] with a[i][j+1] and increment the counter but I think my problem is when the program is on the final elements and it does not increment the counter.
Here I have my code:
int main(){
int n;
scanf("%d",&n);
int i,j,a[n][n];
for(i = 0;i < n;i++){
for(j = 0;j <n;j++){
scanf("%d",&a[i][j]);
}
}
int max=-9999;
int counter;
for(i = 0;i < n;i++){
counter=0;
for(j = 0;j <n;j++){
if(a[i][j]<a[i][j+1]){
counter++;
}
if(counter>max){
max = counter;
}
}
}
printf("%d",max);
return 0;
}
For starters as the range of indices can not be negative then there is no sense to declare the variable max as having a negative value
int max=-9999;
It could be initialized at least like
int max = 0;
In this if statement
if(a[i][j]<a[i][j+1]){
there can be an access to memory beyond the allocated array when i and j are equal to n - 1 due to the expression a[i][j+1].
Also this if statement
if(counter>max){
max = counter;
}
should be moved outside the inner if statement.
And the variable count should be declared inside the outer loop
You could rewrite the inner for loop the following way
int counter=1;
for(j = 1;j <n;j++){
if(a[i][j-1]<a[i][j]){
counter++;
}
}
if(counter>max){
max = counter;
}

analyze array in a specific direction

I have a dynamically allocated array that contains data for a piece of land:
0| 1| 2| 3| 4| 5| ->coordinates
0| 1 0 8 4 1 1
1| 7 4 2 6 7 8
2| 7 4 2 4 3 4
3| 7 1 6 2 0 8
4| 0 0 3 3 6 6
The numbers inside represent height. I have to analyze specific data inside to figure out where i can have suitable jumps(Suitable jumps have 3 squares of reinforcement with an increasing slope of up to 45 degrees,followed by 2 squares steep descending slope -80 degrees).
But the catch is that I only need to analyze the heights that are from the direction from east to west:[1]: https://i.stack.imgur.com/axiNh.png
How can I implement that direction specifically? this is a simplified version of my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int length=4, width=5;
struct LandData
{
int height;
};
struct LandData* WritingData()
{
struct LandData *arr = (struct LandData*)malloc(length* width* sizeof(struct LandData));
for (int i = 0; i < length ; i++){ //len
for (int j = 0; j < width; j++){//wid
((arr + i*width + j)->height) = rand() % 10;
}
}
int l = 1, h;
float jumps;
for (int i = 0; i < length ; i++) {
for (int j = 0; j < width; j++){
h = ((arr + i*width + j)->height);
jumps = tan(h/l); // cause the angle for the jumps should be 45 deg
if(jumps <= 1)
printf("suitable jumps: %d %d\n", i ,j);
}
}
return(arr);
}
int main()
{
struct LandData *arr = WritingData();
}
as far as I understand, the direction is important for you. if it's, then the following
changing is enough for that.
for (int i = 0; i < length ; i++) {
for (int j = width; j > 0; j--){
h = ((arr + i*width + j)->height);
jumps = tan(h/l); // cause the angle for the jumps should be 45 deg
if(jumps <= 1)
printf("suitable jumps: %d %d\n", i ,j);
}
}

Simple Pyramid In C

the code I've written creates a pyramid with given input. I need the first part Incrementing by 2, but the code written does not really Incrementing by 2. Aprrechiate any help.
Code:
int main() {
int i, j, n, a, rows;
printf("Enter a Number: ");
scanf("%d", &rows);
printf("\nPattern for %d:\n\n", rows);
for (i = 0; i <= rows; i++) {
printf("%d | ", i);
for(a = 2; a <= i; a+=2) {
printf("%d ", a);
}
for (j = 0; j <= i; j++) {
if (j == i){
printf("%d ", j);
}
}
for(n = 1; n < i; n++){
printf("%d ", j);
j++;
}
printf("\n");
}
return 0;
}
Needed Output:
0 | 0
1 | 0 1
2 | 0 2 2 3
3 | 0 2 4 3 4 5
4 | 0 2 4 6 4 5 6 7
5 | 0 2 4 6 8 5 6 7 8 9
6 | 0 2 4 6 8 10 6 7 8 9 10 11
Current Output:
0 | 0
1 | 1
2 | 2 2 3
3 | 2 3 4 5
4 | 2 4 4 5 6 7
5 | 2 4 5 6 7 8 9
6 | 2 4 6 6 7 8 9 10 11
I had to add an extra if condition for i = 0 because it was not fitting in the pattern I figured out. I have done it in just 2 loops instead of you using 3 loops.
Here is the brief explanation. Comment on this answer if you don't understand the code still, I will add a detailed explanation.
Case i = 0 is a special case and it is handled separately using an if.
for i > 0, you can notice that there are 2 series in parallel
even numbers always starting from 0 and if you count them then they are equal to value of i in that row.
another series whose first number is the value of i in that row and it also has number of elements equal to value of i in that row.
That's why in both the loops that handle the series they are run from 0 till i-1.
I hope it helps you and please accept as correct answer if it did.
#include <stdio.h>
int main() {
int i, j, n, a, b, c, rows;
printf("Enter a Number: ");
scanf("%d", &rows);
printf("\nPattern for %d:\n\n", rows);
for (i = 0; i <= rows; i++) {
if(i == 0){
printf("0 | 0\n");
continue;
}
printf("%d | ", i);
// For handling the even number series
for(a = 0, b = 0; a < i; a++, b+=2) {
printf("%d ", b);
}
// For handling the incremental series
for (j = 0, c = i; j < i; j++, c++) {
printf("%d ", c);
}
printf("\n");
}
return 0;
}
You try to overcomplicate simple task.
void pyramid(int rows)
{
for(int row = 0; row < rows; row++)
{
for(int even = 0; even < row * 2; even += 2)
{
printf("%d ", even);
}
if(row == 0) printf("%d ", row);
else
{
for(int remain = row; remain < row * 2; remain++)
{
printf("%d ", remain);
}
}
printf("\n");
}
}
https://godbolt.org/z/cdWqsq

Multidimensional Array Printing Gives Something Different

#include <stdio.h>
int main(int argc, char **argv) {
int x[5][5] = {{0,1,2,3,4},{5,6,7,8,9}};
for (int i = 0; i < 4; i++) {
for (int j = 0; i < 4; i++) {
printf("%d\n", x[i][j]); } }
return 0; }
This was supposed to give me: 0 1 2 3 4 5 6 7 8 9
And the result is: 0 5 0 0
And then, when I change them to chars:
#include <stdio.h>
int main(int argc, char **argv) {
char x[5][5] = {{'0','1','2','3','4'},{'5','6','7','8','9'}};
for (int i = 0; i < 4; i++) {
for (int j = 0; i < 4; i++) {
printf("%d\n", x[i][j]); } }
return 0; }
I get 48 53 0 0.
Why? The code is pretty clear for me, but it seems that is happening something obscure on background (Or my brain works in a very "pythonic" way...)
Like #Keith Thompson said, you didn't initialize all 25 elements. So the remaining elements are initialized to 0. As a result, the data will be stored this way:
0 | 1 | 2 | 3 | 4 // Row 0
5 | 6 | 7 | 8 | 9 // Row 1
0 | 0 | 0 | 0 | 0 // Row 2
0 | 0 | 0 | 0 | 0 // Row 3
0 | 0 | 0 | 0 | 0 // Row 4
You only initialized the first two rows of your array. This is the reason why you got 0 5 0 0 as your output.
To get the correct output, you need to loop through the first two rows of your array.
Steps to fix this :
First
You need to change your first for-loop from:
for (int i = 0; i < 4; i++)
to
for (int i = 0; i < 2; i++)
Reason: Because you only want to loop through the first two rows (row 0 and row 1).
Second
You need to change your second for-loop from:
for (int j = 0; i < 4; i++)
to:
for (int j = 0; j < 5; j++)
Reason: You need variable j for your loop condition, not i. You also need to change from 4 to 5; because in an array, the index starts with 0. So, the indexes of each columns are 0,1,2,3,4 , respectively.
To sum up, your code supposed to be...
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
printf("%d\n", x[i][j]);
}
}
Additionally, when you are changing to char x[5][5], you need to use %c, to print a character, instead of %d.
Moreover, the reason you are getting weird numbers like 48 because when you print a char with %d, you are actually printing its ASCII values. Referring to the ASCII table below, number 48 represents character '0'.
Image from http://www.asciitable.com/
for(i = 0 ; i < 2 ; i++)
for(j = 0 ; j < 5 ; j++)
printf("%d\n",x[i][j]);
i dont know why you initialized only 2 1-d arrays. but changing the bounds in the for loop should suffice your needs

Resources