I just worked to my final exam with simple codes; when I try to sorting strings, I face annoying error. Why 2 is not smaller than 10 on my CodeBlocks IDE but is smaller than 10 on real and onlinegdb.com?
This is the annoying code:
#include <string.h>
#include <stdio.h>
#define STR_SIZ 20
int main()
{
char strArr[][STR_SIZ] = {"abc", "hdas", "sdfasf", "kakldf", "caksl", "casd", "keam", "cznjcx", "mnxzv", "jkalkds"};
char minStr[STR_SIZ];
strcpy(minStr, strArr[0]);
int N = sizeof(strArr)/sizeof(minStr);
// int N = 10;
for(int x = 0; x < N-1; x++)
{
printf("%d", x);
strcpy(minStr,strArr[x]);
int j;
for(j=1+x; j < 10; j++)
{
printf("%4d\n", j);
int cmp = strcmp(strArr[j], minStr);
if(cmp < 0)
strcpy(minStr,strArr[j]);
}
char temp[STR_SIZ];
strcpy(temp,strArr[x]);
strcpy(strArr[x], minStr);
strcpy(strArr[j], temp);
}
return 0;
}
Output on onlinegdb.com:
0 1
2
3
4
5
6
7
8
9
1 2
3
4
5
6
7
8
9
2 3
4
5
6
7
8
9
3 4
5
6
7
8
9
4 5
6
7
8
9
5 6
7
8
9
6 7
8
9
7 8
9
8 9
Output on CodeBlocks:
0 1
2
3
4
5
6
7
8
9
1 2
3
4
5
6
7
8
9
2
PS: I just have used Codeblock in the morning and it was okey with executing.
strArr has 10 elements. At the end of your loop, you call strcpy(strArr[j], temp);. This will write to strArr[10], which is out of bounds and will overwrite some unknown memory. Anything can happen after that.
You should save the j value when you copy a string into minStr.
FYI, your code above prints this as your final string order with onlinegdb:
abc
caksl
caksl
caksl
caksl
casd
cznjcx
cznjcx
jkalkds
jkalkds
So I think you have other problems as well.
try this
#include <string.h>
#include <stdio.h>
#define STR_SIZ 20
int main()
{
char strArr[][STR_SIZ] = {"abc", "hdas", "sdfasf", "kakldf", "caksl", "casd", "keam", "cznjcx", "mnxzv", "jkalkds"};
strcpy(minStr, strArr[0]);
// Calculate the number of elements this way.
const int N = sizeof(strArr)/sizeof(strArr[0]);
// int N = 10;
for(int x = 0; x < N-1; x++)
{
printf("%d", x);
int j;
for(j=1+x; j < N; j++) // Use N here too!
{
printf("%4d\n", j);
int cmp = strcmp(strArr[j], strArr[x]);
if(cmp < 0)
{
// Do the swaps only when needed.
char temp[STR_SIZ];
strcpy(temp,strArr[x]);
strcpy(strArr[x], strArr[j]);
strcpy(strArr[j], temp);
}
}
}
// Verify result
for(int x = 0; x < N; x++) printf("%s\n", strArr[x]);
return 0;
}
I moved your swap into your if check and got rid of your minStr as it was not needed. Notice how I calculate the N size too. Honestly, you were close, but you needed to verify your output.
Related
So i got an assignment in class to make an empty sudoku that every time creates a random solution of 9x9.
I got to the point where i get different number each row and column but not on every 3x3 matrix and i cannot figure out how to go on from here.
We didnt learn recursion yet and can use only the libraries listed in the code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NINE 9
#define ONE 1
void solve_sudoku(int board[9][9])
{
srand(time(0));
int count = 0;
for (int i = 0;i <= NINE;i++)
{
for (int j = 0;j < NINE;j++)
{
board[i][j] =(rand() % NINE)+ONE;
for (int k = 0;k < 9;k++)
{
int clone_i = i;
int clone_j = j;
while (board[i][k] == board[i][j])
{
if (j == k)
{
break;
}
count++;
board[i][j] = (rand() % NINE) + ONE;
k = 0;
}
while(board[k][j]==board[i][j])
{
if (i == k)
{
break;
}
count++;
board[i][j] = (rand() % NINE) + ONE;
k = 0;
}
if (count > 300 || (board[i][j] == board[i][k] && j != k))
{
for (int i = clone_i;i < clone_i + 1;i++)
for (int l = 0;l < 9;l++)
{
board[i][l] = 0;
}
count = 0;
k = 0;
j = 0;
}
}
}
}
}
void print_sudoku(int board[][9])
{
printf("The soduko solution is: \n");
for (int i = 0;i < NINE;i++)
{
for (int k = 0;k < NINE;k++)
{
printf("%d ", board[i][k]);
}
printf("\n");
}
}
int main()
{
int sud[9][9] = { 0 };
int matrix_size = 9;
solve_sudoku(sud);
print_sudoku(sud);
return 0;
}
I take you to mean that you need to generate random 9 x 9 grids of digits that meet the Sudoku criterion that each row, column and block contains all nine digits. In that case, you are going about it a very difficult way. Perhaps that was inspired by viewing the program as a solver, instead of what it really needs to be: a generator.
Consider that it is easy to write down at least one valid Sudoku algorithmically:
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 7 8 9 | 1 2 3
7 8 9 | 1 2 3 | 4 5 6
------+-------+------
2 3 4 | 5 6 7 | 8 9 1
5 6 7 | 8 9 1 | 2 3 4
8 9 1 | 2 3 4 | 5 6 7
------+-------+------
3 4 5 | 6 7 8 | 9 1 2
6 7 8 | 9 1 2 | 3 4 5
9 1 2 | 3 4 5 | 6 7 8
Now consider that you can always transform one valid Sudoku into a different one by swapping two rows or two columns such that no entries move from one block to another. For example, you can swap the first row with the third, or the fifth column with the sixth. If you perform a bunch of random swaps of that kind on a valid starting Sudoku then you will end up with a random grid that meets the Sudoku criteria.
Note that it is a different story if you need to produce only Sudoku that can be solved by deduction alone, without trial & error. For that you probably do need a solver-based approach, but that starts with a bona fide solver, and nothing in your code is anything like that.
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 am working on a pattern that prints the following code using for loop
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
code is as follows, which results in slightly wrong output.
main(){
int i,j,k,n,num;
printf("\n Enter no of rows: ");
scanf("%d",&num);
for(i=1;i<=num;i++,k=num){
for(j=1,n=i;j<=i;j++,n+=k){
printf("%d ",n);
}
printf("\n");
}
}
And the code gives me this .
which is wrong from the output i wanted
1
2 6
3 7 11
4 8 12 16
5 9 13 17 21
The key to this is how you update n in the inner loop. You need it to take into account not just num but also i as you descend through each iteration. I've fixed num at 5 here and placed the assignment to k at the start of the outer loop as this will always be constant:
#include <stdio.h>
int main(void) {
int i, j, k, n, num;
num = 5;
for(i = 1, k = num; i <= num; i++){
for(j = 1, n = i; j <= i; n += k - j, j++){
printf("%d ", n);
}
printf("\n");
}
}
Gives:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This code is designed by someone to change array [a1 a2...am b1 b2..bn ] to the array [b1 b2 ..bn a1 a2..am], but it involves the greatest common divisor which I can't get the point.
void Exchange(int a[],int m,int n,int s){
int p=m,temp=m+n;int k=s%p;
while(k!=0){temp=p;p=k;k=temp%p;}
for(k=0 ; k<p ;k++){ //below is where i cant't understand
temp=a[k];i=k;j=(i+m)%(m+n);
while(j!=k)
{a[i]=a[j];i=j;j=(j+m)%(m+n);}
a[i]=temp;
}
};
EDIT: "Properly" indented:
void Exchange(int a[], int m, int n, int s) {
int p = m, temp = m + n, k = s % p;
while (k != 0) {
temp = p;
p = k;
k = temp % p;
}
for (k = 0 ; k < p; k ++) { // below is where i cant't understand
temp = a[k];
i = k;
j = (i + m) % (m + n);
while (j != k) {
a[i] = a[j];
i = j;
j = (j + m) % (m + n);
}
a[i] = temp;
}
};
The code is using a single value of overhead to implement array rotation. If the lengths are mutually prime, a single pass suffices. If not, you have to repeat the shift cycle by the GCD of the lengths
I said earlier that there are other questions on SO that cover this. A look found SO 3333-3814 which deals with a single rotation. I did some messing with code to support that a while ago, demonstrating the need for GCD, but I didn't previously post it.
Here's the code — it uses C99 VLAs — variable length arrays.
#include <stdio.h>
static int gcd(int x, int y)
{
int r;
if (x <= 0 || y <= 0)
return(0);
while ((r = x % y) != 0)
{
x = y;
y = r;
}
return(y);
}
static void dump_matrix(int m, int n, int source[m][n])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
printf("%4d", source[i][j]);
putchar('\n');
}
}
static void init_matrix(int m, int n, int source[m][n])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
source[i][j] = (i + 1) * (j + 2);
}
}
static void rotate_1col(int n, int vector[n], int z)
{
z %= n;
if (z != 0)
{
int c = gcd(n, z);
int s = n / c;
for (int r = 0; r < c; r++)
{
int x = r;
int t = vector[x];
for (int i = 0; i < s; i++)
{
int j = (x + z) % n;
int v = vector[j];
vector[j] = t;
x = j;
t = v;
}
}
}
}
static void rotate_cols(int m, int n, int source[m][n], int z)
{
for (int i = 0; i < m; i++)
rotate_1col(n, source[i], z);
}
int main(void)
{
int m = 3;
for (int n = 2; n < 9; n++)
{
int source[m][n];
for (int z = 0; z <= n; z++)
{
init_matrix(m, n, source);
printf("Initial:\n");
dump_matrix(m, n, source);
rotate_cols(m, n, source, z);
printf("Post-rotate %d:\n", z);
dump_matrix(m, n, source);
putchar('\n');
}
}
return 0;
}
The code demonstrates different sizes of rotation on different sizes of array. Example sections of the output:
…
Initial:
2 3 4
4 6 8
6 9 12
Post-rotate 1:
4 2 3
8 4 6
12 6 9
…
Initial:
2 3 4 5
4 6 8 10
6 9 12 15
Post-rotate 3:
3 4 5 2
6 8 10 4
9 12 15 6
…
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 1:
7 2 3 4 5 6
14 4 6 8 10 12
21 6 9 12 15 18
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 2:
6 7 2 3 4 5
12 14 4 6 8 10
18 21 6 9 12 15
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 3:
5 6 7 2 3 4
10 12 14 4 6 8
15 18 21 6 9 12
…
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 4:
6 7 8 9 2 3 4 5
12 14 16 18 4 6 8 10
18 21 24 27 6 9 12 15
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 5:
5 6 7 8 9 2 3 4
10 12 14 16 18 4 6 8
15 18 21 24 27 6 9 12
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 6:
4 5 6 7 8 9 2 3
8 10 12 14 16 18 4 6
12 15 18 21 24 27 6 9
…
First of all, to get the result you said you expected, I have set m and n to be half the array size. I also assumed that s would be initialised to zero, in which case, the first while loop does not iterate. Also, there are several declarations missing in your code so my explanation makes some assumptions.
The variable p holds the number of array elements to swap;
// This is to keep the value to be overwritten by the swap
temp=a[k];
// This is the array index of the bottom half element to write the top half element to
i=k;
// this is to get the current index of the top half;
j=(i+m)%(m+n);
// This assignes the bottom index value with the top half value
while(j!=k)
{
// Write top half element to corresponding bottom half element
a[i]=a[j];
// We can now overwrite top half element; this assignes the index at wich to copy the bottom half element
i=j;
// This is to get out of the loop
j=(j+m)%(m+n);
}
// The bottom half element held at the beginning is now written to the top half at the corresponding index
a[i]=temp;
Hope this is the answer you were looking for. I arrived at this result by using a debugger and by stepping in the code line by line. I don't know if you know how to use a debugger but if not, then I highly recommend your lean how to use one; it it time well spent and it returns an awesome dividend :-)
I have the following program -
#include <stdio.h>
int main() {
int counter = 0;
int responses[28];
printf("Enter student section values: \n");
while(counter != 27) {
scanf("%d", &responses[counter]);
counter++;
}
int i = 0;
int arrayBlank[100];
int temp = 0;
int past = 0;
int present = 0;
int future = 0;
int flag = 0;
for(i = 0; i < counter; i++) {
if((i - 1) < 0 || (i + 1 >= counter)) {
;
}
else {
past = responses[i - 1];
present = responses[i];
future = responses[i + 1];
if(present == past || present == future) {
temp = present;
flag=1;
arrayBlank[temp]++;
} else {
arrayBlank[i] = 0;
}
}
}
if(flag == 0) {
printf("\nThe order input does not assign any adjacent students from the same team\n");
return 0;
} else {
int chut[28];
int index = 0;
for(i = 0; i < 27; i++) {
index = responses[i];
chut[index]++;
}
for(i = 0; i < 27; i++) {
if(chut[i] <= 0 || chut[i] > 26) {
chut[i] = 0;
}
}
printf("\nThe order input currently assigns adjacent students from the same team.\n");
printf("\nTeam Students\n");
for(i = 0; i < 27; i++) {
if(chut[i] != 0) {
printf("%d %d\n", i, chut[i]);
}
}
//1 2 3 3 4 5 6 7 8 9 1 2 3 4 5 5 7 8 9 1 2 3 4 5 6 7 8 8
}
return 0;
}
Basically for a given range of numbers, it checks if there is any particular number in the given entries that has an adjacent value which is the same as that number. If there is, it will just print how many times a particular element appeared in the given range of numbers.
Example - For a list of numbers
1 2 3 3 4 5 6 7 8 9 1 2 3 4 5 5 7 8 9 1 2 3 4 5 6 7 8 8
The program execution would be like -
Enter student section values: 1 2 3 3 5 6 7 8 9 1 2 3 4 5 5 7 8 9 1 2 3 4 5 6 7 8 8
The order input currently assigns adjacent students from the same team.
Team Students
1 3
2 3
3 4
4 2
5 4
6 2
7 3
8 4
9 2
Issue : I am not able to figure out the reason why the output is different on different machines and how I could fix that. For example, the output is correct on my Macbook running the program with XCode although it is different when I run it on a Linux machine with gcc compiler (Big Endian machine). I am not sure if the Endianess has anything to do with the outputs being different though.
On a Little Endian Linux machine -
On a Big Endian Linux machine -
On an online compiler (Tutorial's Point) -
The main problem, as far as I can see, is that you haven't initialized arrayBlank and are using it in:
arrayBlank[temp]++;
That certainly is cause for undefined behavior. I would initialize arrayBlank to zero using
int arrayBlank[100] = {0};
The secondary problem is that the loop counter to read the data is not right. Instead of:
while(counter != 27) {
scanf("%d", &responses[counter]);
use:
while(counter != 28) {
scanf("%d", &responses[counter]);
When you use counter != 27 to stop, the last element of responses, which can be accessed using index 27 is never read from file.