I am trying to create a 2d matrix board which side is determined by the user input. I created the two D array but it is not printing the right numbers. For example if the user enters 3, it is suppose to create a 3 * 3 board with the number 8, 7, 6, 5, 4, 3, 2, 1, 0.
However it keeps printing the same numbers in each row eg 876, 876, 876
I know it is doing what I have written but I cant figure out how to correct it...I am thinking that I need a counter that resets to zero and perhaps the [i][j] = counter's value.
Anyway here is the code that is giving the trouble.
for (i =0; i< row; i++)
{
for (j =0; j < col; j++)
{
game [i][j] = ((row * row)-1) - j;
printf( "%i", game[i][j] );
}
How can I populate the board so it prints from (row * col) - 1 to zero. Thanks a million.
for ((i=0, k=0); i< row; i++)
{
for (j =0; j < col; j++)
{
game [i][j] = ((row * col)-1) - (k++);
printf( "%i", game[i][j] );
}
}
The basic mistake in the code is that, in each iteration, the value getting subtracted from the game[i][j] gets re-initialized to 0. Since, the value of (row * col) is constant for a given value of both, subtracting (0, 1, 2) each time from the sum results in the reproduction of the same numbers.
As given in the example, row=3, col=3, so 3*3 = 9 (Indexed from 0 to 8).
So, we do :
8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
again j gets re-init to 0, so again we have,
8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
.
The solution is, the value getting subtracted should get uniformly reduced, such that it doesn't get re-init inside the loop.
Result :
8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
8 - 3 = 5
.
.
.
.
8 - 8 = 0.
Hope this clears the problem.
As suggested by "self", using a third variable is the easiest way (and actually the most efficient : only one decrement per iteration)
int count = row * col - 1;
for (size_t i =0; i< row; i++)
{
for (size_t j =0; j < col; j++)
{
game [i][j] = count--;
printf( "%i", game[i][j] );
}
}
Output:
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Related
Link to CodeChef problem MAXSC
Attempted solution:
#include<stdio.h>
int main()
{
long long int n, t, k, i, j, max[701], a[701][701], sum, flag;
scanf( "%lld", &t );
for( k = 0 ; k < t ; k++ )
{
scanf( "%lld", &n );
for( i = 1 ; i <= n ; i++ )
{
for( j = 1 ; j <= n ; j++ )
{
scanf( "%lld", &a[i][j] );
if( j == 1)
max[i] = a[i][1];
if( a[i][j] > max[i] )
max[i] = a[i][j];
}
}
sum = 0, flag = 0;
for( i = 1 ; i <= n-1 ; i++ )
{
if( max[i] < max[i+1])
sum = sum + max[i];
else
{
flag = 1;
break;
}
}
if(flag == 1)
printf("-1\n");
else
{
sum = sum + max[n-1];
printf("%lld\n", sum );
}
}
}
Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead.
Constraint:
Code should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1.
Does this constraint mean we have to choose max element from each line?
If you look at example given:
Example Input:
1
3
1 2 3
4 5 6
7 8 9
Output:
18
Explanation
Example case 1: To maximize the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18.
If you notice they have mentioned "maximize".
Though my code finds the max, it isn't being accepted.
why is this code not being accepted?
Code's logic is flawed. When max[i] < max[i+1] is false, it sets flag = 1; instead of considering other elements from a[i].
Does this constraint mean we have to choose max element from each line?
No. The goal is a maximal sum, not a sum of maximums.
// if( max[i] < max[i+1])
if(max[i] < max[i+1])
sum = sum + max[i];
else {
flag = 1;
break;
}
The solution lies in tying other elements. Even if that fails, perhaps a prior selection should be changed. Recursion may be employed or other analysis. I think it would make sense to first sort each row of data to avoid this code taking n*n run-time. It should be trivial to code a n*n solution (trying every combination).
As this is homework, leave to OP to develop the solution.
1
3
6 10 12
4 5 7
8 9 10
-1
but output should be 6+7+10=23.
question is given Ei should be strictly greater than Ei-1
1
3
1 2 3
4 5 6
7 8 9
Output is 3+6+9=18 means 3<6 and 6<9 which satisfy the above problem
3
6 10 12
4 5 7
8 9 10
Output is 6+7+10=23 means 12<7 which is false and 6<7 which is true and 7<10 also true so sum=23.
3
8 9 10
11 12 13
10 5 9
Output is -1 because 10<13 is true but 13 is not less than 10 or 5 or 9 which is false hence output is -1.
Lets says I have a number m = 9. I want to divide it into n=5 parts like given below:
As m>n, each part will get at least 1.
First give 1 to all 5 parts
part0: 1,
part1: 1,
part2: 1,
part3: 1,
part4: 1
Now for the remaining (9 - 5 = 4) divide again starting from 1st. final allocation looks like:
part0: 2
part1: 2
part2: 2
part3: 2
part4: 1
algo:
take an array arr[n]={0}.
x=0
while(m) {
arr[x]+=1;
m--;
x=(x+1)%n;
}
My question is I don't want to run this loop to divide n into m parts. Mathematically, how can I know the value allocated to a part directly. i.e part0: 2 for above example.
Integer division gets you the "base" size of all parts: 9 / 5 == 1.
Modulo gives you the remainder, 9 % 5 == 4. This means you should add 1 to the first 4 parts.
int partCount = 5;
int number = 9;
int base = number / partCount;
int remain = number % partCount;
for (int i=0; i<partCount; i++) {
part[i] = base;
if (i < remain) part[i]++;
}
The algorithm might be clearer if you use larger numbers. E.g. 31 in 7 parts:
31 / 7 == 4 - so we have 7 parts of 4 each, (== 28) plus the remainder:
31 % 7 == 3 - give the first 3 parts 1 more each to make 31 total.
for (i=0; i<n; i++) {
arr[i] = m/n + (m%n < i ? 1 : 0);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am having trouble with implementing the sort function on pset3. I have used the GDB and found that my sort function does not sort anything. I am not sure if there is a syntax issue, or if the logic is a bit screwed up.
void sort(int values[], int n)
{
for (int k = 0; k < n; k++)
{
for (int j = 0; j < n; j++)
{
if (values[k] >= values[j])
{
int temp = values[k];
values[k] = values[j];
values[j] = temp;
}
}
}
}
You are close, but your loops are not quite right - change:
for (int k = 0; k < n; k++)
{
for (int j = 0; j < n; j++)
{
to:
for (int k = 0; k < n - 1; k++)
{
for (int j = k + 1; j < n; j++)
{
To understand why you need to make this change, consider that the inner loop (j) need only compare elements above index k with the current element at index k. So the outer loop (k) needs to iterate from 0 to n - 2 (one less than the last element), and for each outer loop iteration the inner loop needs to iterate from k + 1 (first element above k) to n - 1 (the last element).
NOTE: by pure chance it seems that the original code does appear to work correctly, even though it appears at first glance that it shouldn't. I have tested it with various edge cases and even though it performs many redundant swaps, the final result always seems to be sorted (suprisingly though the output is in descending order whereas the fixed code generates results in ascending order, as expected). Credit to Jonathan Leffler for spotting this - see his answer and demo program.
One other minor point -- this test:
if (values[k] >= values[j])
should really just be:
if (values[k] > values[j])
It's not incorrect as it stands (the code will still work), but there is no point in swapping elements that are equal, so it's somewhat inefficient as written.
I took your code and converted into a complete program. It's larger than an MCVE because it has support code for shuffling arrays, and for printing results, as well as a main() that exercises these, of course.
#include <stdio.h>
#include <stdlib.h>
static int rand_int(int n)
{
int limit = RAND_MAX - RAND_MAX % n;
int rnd;
while ((rnd = rand()) >= limit)
;
return rnd % n;
}
static void shuffle(int *array, int n)
{
for (int i = n - 1; i > 0; i--)
{
int j = rand_int(i + 1);
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
static void print_array(int n, int a[n])
{
for (int i = 0; i < n; i++)
printf(" %d", a[i]);
putchar('\n');
}
static void sort(int values[], int n)
{
for (int k = 0; k < n; k++)
{
for (int j = 0; j < n; j++)
{
if (values[k] >= values[j])
{
int temp = values[k];
values[k] = values[j];
values[j] = temp;
}
}
}
}
int main(int argc, char **argv)
{
if (argc > 1)
{
long l = strtol(argv[1], 0, 0);
unsigned u = (unsigned)l;
printf("Seed: %u\n", u);
srand(u);
}
int data3[3] = { 3, 1, 2 };
print_array(3, data3);
sort(data3, 3);
print_array(3, data3);
int data5[5] = { 0, 2, 6, 1, 5, };
for (int i = 0; i < 5; i++)
{
shuffle(data5, 5);
print_array(5, data5);
sort(data5, 5);
print_array(5, data5);
}
int data9[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < 9; i++)
{
shuffle(data9, 9);
print_array(9, data9);
sort(data9, 9);
print_array(9, data9);
}
return 0;
}
The shuffle code implements a Fisher-Yates shuffle, and is
based on code from an answer by Roland Illig. If invoked without a seed argument, it generates the same output each time.
Code compiled and tested on macOS Sierra 10.12.1 with GCC 6.2.0.
An example output:
Seed: 123456789
3 1 2
3 2 1
6 0 1 5 2
6 5 2 1 0
0 6 1 2 5
6 5 2 1 0
0 1 2 6 5
6 5 2 1 0
5 0 6 1 2
6 5 2 1 0
1 6 5 2 0
6 5 2 1 0
0 4 8 3 7 5 1 6 2
8 7 6 5 4 3 2 1 0
7 4 0 5 6 8 3 2 1
8 7 6 5 4 3 2 1 0
1 2 7 5 0 8 3 6 4
8 7 6 5 4 3 2 1 0
3 8 7 5 2 1 0 6 4
8 7 6 5 4 3 2 1 0
1 4 2 6 3 0 7 5 8
8 7 6 5 4 3 2 1 0
2 3 7 4 8 0 5 6 1
8 7 6 5 4 3 2 1 0
3 4 5 8 6 2 0 7 1
8 7 6 5 4 3 2 1 0
3 6 7 4 8 2 5 1 0
8 7 6 5 4 3 2 1 0
0 8 7 3 4 6 5 1 2
8 7 6 5 4 3 2 1 0
This shows the data being sorted in descending order every time, despite different randomized inputs.
I tried to sort arr by excluding those who were already selected as the largest numbers but it didn't work.
The result is this:
As I intended, at first cycle, the store is {9, 0, 0, 0, 0 ... } and when arr[i] becomes 9, the rest of process should be skipped. I have to sort it without additional functions and it's too difficult to me. What is the problem?
int i = 0;
int j = 0;
int num = 0;
int sign = 0;
int arr[10] = { 1,5,3,4,8,7,5,9,8,0 };
int max = arr[0];
int store[10] = { 0 };
int k = 0;
for (j = 0; j < 10; j++) {
printf("store: ");
for (int n = 0; n < 10; on++)
printf("%d ", store[n]);
printf("\n");
for (i = 0; i < 10; i++) {
sign = 0;
k = 0;
while (k < 10) {
if (arr[i] == store[k]) {
sign = 1;
break;
}
k++;
}
if (sign == 1) {
continue;
}
if (arr[i] > max) {
max = arr[i];
}
}
store[j] = max;
}
You have several errors here:
The array store has a size of 10, but in the jth pass through the outer loop, only j values have been filled in; the rest is still zero. So whenever you iterate over store, you should use j as upper limit.
You are looking for the max in each iteration. Therefore, it is not enough to initialise max once outside the outer loop. You do that, and it will stay 9 ever after. You should reset max for every j.
Finally, your idea to go through the array to see whether you have already processed a certain value does not work. Your array has duplicates, two 8's and two 5's. You will only place one eight and one five with your strategy and re-use the last value of max for the last two elements. (Plus, that idea lead to O(n³) code, which is very wasteful.
You can work around that by keeping an extra array where you store whether (1) or not (0) you have already processed a value at a certain index or by setting processed entries in the array to a very low value.
What you want to implement is selection sort: Find the maximum value in the whole list and move it to the front. Then find the maximum in the whole list except the first item and move it to the second slot and so on:
* 1 5 3 4 8 7 5 9 8 0
9 * 5 3 4 8 7 5 1 8 0
9 8 * 3 4 5 7 5 1 8 0
9 8 8 * 4 5 7 5 1 3 0
9 8 8 7 * 5 4 5 1 3 0
9 8 8 7 5 * 4 5 1 3 0
9 8 8 7 5 5 * 4 1 3 0
9 8 8 7 5 5 4 * 1 3 0
9 8 8 7 5 5 4 3 * 1 0
9 8 8 7 5 5 4 3 1 * 0
9 8 8 7 5 5 4 3 1 0 *
Here, all items to the left of the asterisk have been sorted and everything to the right of the asterisk is still unsorted. When the * (at position j) has moved to the right, the whole array is sorted.
This sort is in-place: It destroys the original order of the array. That is useful, because the position of an element tells us whether it has been processed or not. In the third iteration, the algorithm can distinguish between the 8 that has been sorted and the 8 that hasn't been sorted yet. (This sort is often described as sorting a hand of cards: Look fo the lowest, put it to the left and so on. If you must sort into a second array, copy the original array and sort the copy in place.)
Here's the code that sorts your array and prints out the diagram above:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int arr[10] = {1, 5, 3, 4, 8, 7, 5, 9, 8, 0};
int i = 0;
int j = 0;
for (j = 0; j < 10; j++) {
int imax = j;
int swap = arr[j];
// print array
for (i = 0; i < 10; i++) {
if (i == j) printf("* ");
printf("%d ", arr[i]);
}
printf("\n");
// find index of maximum item
for (i = j + 1; i < 10; i++) {
if (arr[i] > arr[imax]) {
imax = i;
}
}
// swap first unsorted item and maximum item
arr[j] = arr[imax];
arr[imax] = swap;
}
// print fully sorted array
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("*\n");
return 0;
}
Use i and j.
N is 10 and the data consists of shuffled numbers 0 to N-1.
j goes from 0 to N-1. At each step, you want to fill it with
the maximum of the unprocessed input.
So i goes from j+1 to N-1, in the inner loop. If arr[j] < arr[i],
swap arr[i] and arr[j].
It speeds up considerably as you get towards the end.
The malloc'd 2d array I have to work from is
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
This isn't constructed from a [][] array but rather malloc'd memory separated by printf("\n");
I'd like to manipulate it and make a for loop to traverse through the list so the result is
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 25
so the result is
Row 1 * Column 1-4
Row 2 * Column 1-4 ...
Any help would be appreciated, I'm having a brain fart right now (just got out of class)
typedef struct array {
int cols, rows;
int *arr;
} array;
array mkSum(array node)
{
int i;
for (i = 1; i <= ((node.cols) * (node.rows)); i++) //goes through all 25
{
//CODE TO MANIPULATE
}
for (i = 0; i < ((node.cols) * (node.rows)); i++) //goes through all 25
{
if (i % node.cols == 0)
printf("\n");
printf(" %d", node.arr[i]); //prints out elements
}
return(node);
}
mkSum is called by passing in a pointer to the array which comes in as the one i have to work from (first example)
mkSum(array);
The question is a bit unclear (in particular about the desired result), but I think for the manipulation you best use two nested loops, and simulate node.arr being a 2d array:
for (int col = 0; col < node.cols; col++ ) {
for (int row = 0; row < node.rows; row ++ ) {
... Element to modify: node.arr[row * node.cols + col]
}
}
You'll have to adjust to calculation formula for the fact that row/col starts with 0 in this approach.
Try this
for (int col = 1; col <= node.cols; col++ ) {
for (int row = 1; row <= node.rows; row ++ ) {
printf(" %d", col*row);
}
printf("\n");
}