any stronger test case to check code - c

this code is getting a wrong answer in spoj
i want stronger test cases to check my code.. help appreciated..
The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) belongs to A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n
Input
The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 2^28 ) that belong respectively to A, B, C and D .
Example
Input:
6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45
Output:
5
#include<stdio.h>
#include<stdlib.h>
int binarys(int a,long int b[],int low,int up,int k)
{
int par;
if(low <= up) {
par = partition(low,up,b);
if(b[par] + a == 0) {
k = k + 1;
k = binarys(a,b,low,par-1,k);
k = binarys(a,b,par+1,up,k);
}
if(b[par] > -1*a)
k = binarys(a,b,low,par-1,k);
if(b[par] < -1*a)
k = binarys(a,b,par+1,up,k);
}
return k;
}
int partition(int low,int up,int b[])
{
int i;
int j;
int m;
int a;
j = low - 1;
m = b[up];
for(i=low; i < up; i++) {
if(b[i] <= m ) {
j++;
a = b[i];
b[i] = b[j];
b[j] = a;
}
}
a = b[j+1];
b[j+1] = b[up];
b[up] = a;
return j + 1;
}
int main()
{
long int *A = NULL;
long int *B = NULL;
long int *C = NULL;
long int *D = NULL;
long int *a = NULL;
long int *b = NULL;
int n;
int i;
int j;
int k;
int l;
int sum;
scanf("%d",&n);
k = 0;
sum = 0;
A = (long int*)malloc(n*sizeof(long int));
B = (long int*)malloc(n*sizeof(long int));
C = (long int*)malloc(n*sizeof(long int));
D = (long int*)malloc(n*sizeof(long int));
a = (long int*)malloc(n*n*sizeof(long int));
b = (long int*)malloc(n*n*sizeof(long int));
for(i=0; i < n; i++) {
scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]);
}
for(i=0; i < n; i++) {
for(j=0; j < n; j++) {
a[k] = A[i] + B[j];
b[k] = C[i] + D[j];
k++;
}
}
for(i=0; i < n*n; i++) {
l = binarys(a[i],b,0,n*n,0);
sum = sum + l;
}
printf("%d",sum);
return 0;
}

Compiling with gcc 4.7.2, -Wall -Wextra -Wshadow
a.c: In function ‘binarys’:
a.c:9:9: warning: implicit declaration of function ‘partition’ [-Wimplicit-function-declaration]
a.c: In function ‘main’:
a.c:75:9: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘long int *’ [-Wformat]
a.c:75:9: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘long int *’ [-Wformat]
a.c:75:9: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘long int *’ [-Wformat]
a.c:75:9: warning: format ‘%d’ expects argument of type ‘int *’, but argument 5 has type ‘long int *’ [-Wformat]
Your example test case
$ ./a
6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45
0$
It neither matches the expectation you provided (5), nor does it print a newline after the output. The grader may be expecting the newline and rejecting your program simply by you not writing it.
Other basic test cases
$ ./a
1
0 0 0 0
2
Expected 1.
$ ./a
2
1 1 1 1
-3 100 100 100
0
Expected 1.
$ ./a
2
-1 2 2 2
-2 3 3 3
2
Expected 0.
$ ./a
1
9223372036854775807 -9223372036854775808 1 0 // LONG_MAX, LONG_MIN on my architecture
0
Expected 1.
$ ./a
0
0
Correct answer 0!

Related

How to parallelize knight tour problem with Pthreads?

I am trying to paralelize knight tour problem with pthreads but I am getting some errors. I am very new at c language. I guess the code has pointer related problem. can you give me some clue about how to solve it?
I am trying to apply paralel recursive approach. First i was supposed to create 8 threads, then based on moves, new threads are created. perDepth is the limit of creating new threads. i am planing to rewrite this code with multple number of "perDepth"s and compare performance based on perDepth.
\#define HAVE_STRUCT_TIMESPEC
\#include \<pthread.h\>
\#include \<stdio.h\>
\#include \<time.h\>
\#define N 5
int perDepth = 1;
pthread_t thread\[N\];
int count = 0;
int is_valid(int i, int j, int sol\[N + 1\]\[N + 1\])
{
if (i \>= 1 && i \<= N && j \>= 1 && j \<= N && sol\[i\]\[j\] == -1)
return 1;
return 0;
}
int knight_tour(int sol\[N + 1\]\[N + 1\], int i, int j, int step_count, int x_move\[\], int y_move\[\])
{
if (step_count == N \* N)
{
count++;
return 1;
}
int k;
for (k = 0; k \< 8; k++)
{
int next_i = i + x_move\[k\];
int next_j = j + y_move\[k\];
if (is_valid(i + x_move[k], j + y_move[k], sol))
{
sol[next_i][next_j] = step_count;
if (step_count <= perDepth)
{
pthread_create(&thread[k], NULL, knight_tour, NULL);
}
else
{
knight_tour(sol, next_i, next_j, step_count + 1, x_move, y_move);
sol[i + x_move[k]][j + y_move[k]] = -1; // backtracking
}
}
}
return 0;
}
int start_knight_tour()
{
int sol[N + 1][N + 1];
int i, j;
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
sol[i][j] = -1;
}
}
int x_move[] = {2, 1, -1, -2, -2, -1, 1, 2};
int y_move[] = {1, 2, 2, 1, -1, -2, -2, -1};
sol[1][1] = 0; // placing knight at cell(1, 1)
if (knight_tour(sol, 1, 1, 1, x_move, y_move))
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
printf("%d\t", sol[i][j]);
}
printf("\n");
}
return 1;
}
return 0;
}
int main()
{
clock_t t;
t = clock();
pthread_create(&thread\[N\], NULL, start_knight_tour, NULL);
pthread_join(thread\[N\], NULL);
t = clock() - t;
double time_taken = ((double)t) / CLOCKS_PER_SEC; // in seconds
printf("start_knight_tour() took %f seconds to execute \\n", time_taken);
printf("%d\\n", count);
return 0;
}
error message
main.c: In function ‘knight_tour’:
main.c:38:50: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type \[-Wincompatible-pointer-types\]
38 | pthread_create(&thread\[k\], NULL, knight_tour, NULL);
| ^\~\~\~\~\~\~\~\~\~\~
| |
| int (*)(int (*)\[6\], int, int, int, int *, int )
In file included from main.c:2:
/usr/include/pthread.h:204:36: note: expected ‘void \* (*)(void *)’ but argument is of type ‘int (*)(int ()\[6\], int, int, int, int \*, int *)’
204 | void (*\__start_routine) (void *),
| \~\~\~\~\~\~\~\~^\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~
main.c: In function ‘main’:
main.c:90:38: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type \[-Wincompatible-pointer-types\]
90 | pthread_create(&thread\[N\], NULL, start_knight_tour, NULL);
| ^\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~
| |
| int (*)()
In file included from main.c:2:
/usr/include/pthread.h:204:36: note: expected ‘void \* ()(void *)’ but argument is of type ‘int (*)()’
204 | void *(*\__start_routine) (void \*),
| \~\~\~\~\~\~\~\~^\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~

2D Array Void Dereferencing Definition Error in C

I want to create a dynamic dimensional matrix by taking the type variable from the user through the terminal. These types will be integer, float and double type matrices. But my function and matrix that I have defined in void type cannot do this job and I get an error. I think my problem is void dereferencing but I can't solve it. Thank you very much if you help.
I run it like this from terminal
./run arg1 arg2 i arg4 ...
i = integer
f = float
d = double
The function I have written is as follows
void ** random_matrice_gen(int row, int column, int upper, int lower, char * option){
void **matrice;
if(strcmp(option,"i") == 0){
matrice = malloc(row*sizeof(int *));
for(int i = 0 ; i < row ; i++){
matrice[i] = malloc( column*sizeof(int) );
}
}
else if(strcmp(option,"f") == 0){
matrice = malloc(row*sizeof(float *));
for(int i = 0 ; i < row ; i++){
matrice[i] = malloc( column*sizeof(float) );
}
} else {
matrice = malloc(row*sizeof(double *));
for(int i = 0 ; i < row ; i++){
matrice[i] = malloc( column*sizeof(double) );
}
}
srand((unsigned)time(0));
for(int i=0; i<row; i++){
for(int j=0; j<column; j++){
if(strncmp(option,"i", 1) == 0){
int rand_num_i = ((int) rand() / RAND_MAX) * (int) ((upper- lower ) + lower);
matrice[i][j] = rand_num_i;
}
else if(strncmp(option,"f" , 1) == 0){
float rand_num_f = ((float) rand() / RAND_MAX) * (float)((upper- lower ) + lower);
printf("%f debug f\n", rand_num_f);
matrice[i][j] = rand_num_f;
} else {
double rand_num_d = ((double) rand() / RAND_MAX) * (double) ((upper- lower) + lower);
matrice[i][j] = rand_num_d;
}
}
}
return matrice;}
Errors as follows
'''50:15: warning: dereferencing ‘void *’ pointer
50 | matrice[i][j] = rand_num_i;
| ^
matrixgen.c:50:19: error: invalid use of void expression
50 | matrice[i][j] = rand_num_i;
| ^
matrisgen.c:57:15: warning: dereferencing ‘void *’ pointer
57 | matrice[i][j] = rand_num_f;
| ^
matrixgen.c:57:19: error: invalid use of void expression
57 | matrice[i][j] = rand_num_f;
| ^
matrixgen.c:61:15: warning: dereferencing ‘void *’ pointer
61 | matrice[i][j] = rand_num_d;
| ^
matrixgen.c:61:19: error: invalid use of void expression
61 | matrice[i][j] = rand_num_d;
'''
(void *) is a pointer to something unknown, as such, the size isn't known so you can't perform pointer arithmetic over it.
You need to cast it beforehand, ie
((int **)matrice)[i][j] = rand_num_i;
does compile.
It's not possible to dereference void * pointers, and matrice[i] is such a pointer (and array indexing is equal to pointer dereference).
You need to cast this pointer to the correct type:
((int *) matrice[i])[j] = rand_num_i;

Sorting an Array with Selection Sort

#include<stdio.h>
#include <time.h>
int selectionSort(int data[], int count)
{
int a,b;
int tmp;
int minimum;
for(a=0; a<count-1;a++){
minimum = a;
for(b=a+1;b<count;b++){
if(data[minimum]>data[b]) {
minimum = b;
}
}
tmp = data[a];
data[a]=data[minimum];
data[minimum]=tmp;
}
return 0;
}
int main(){
int randomarray[10];
int i;
int k;
srand(time(NULL));
for(i=1; i<=10; i++){
randomarray[i]=rand()%100;
selectionSort(randomarray[i], k = 10 );
printf("%d\n",randomarray[i]);
}
return 0;
}
I am trying to create a program that sorts an array of random integers. I think there is a problem with the declaration of my function, but I am not used to using C. The errors are shown below:
semihosting_example.c:13:5: warning: implicit declaration of function 'srand' [-Wimplicit-function-declaration]
semihosting_example.c:15:5: warning: implicit declaration of function 'rand' [-Wimplicit-function-declaration]
semihosting_example.c:16:5: warning: passing argument 1 of 'selectionSort' from incompatible pointer type [enabled by default]
semihosting_example.c:6:6: note: expected 'int *' but argument is of type 'int (*)[10]'ing_example.c:6:6: note: expected 'int *' but argument is of type 'int (*)[10]
Here's the updated code with the appropriate HEADERS. I am trying to create a function with an array that calls the function with an array:
#include<stdio.h>
#include <time.h>
#include<stdlib.h>
int selectionSort(int (*)[10], int count)
{
int a,b;
int tmp;
int minimum;
for(a=0; a<count-1;a++){
minimum = a;
for(b=a+1;b<count;b++){
if(data[minimum]>data[b]) {
minimum = b;
}
}
tmp = data[a];
data[a]=data[minimum];
data[minimum]=tmp;
}
return 0;
}
int main(){
int randomarray[10];
int i;
int k;
srand(time(NULL));
for(i=1; i<=10; i++){
randomarray[i]=rand()%100;
selectionSort(randomarray[i], k = 10 );
printf("%d\n",randomarray[i]);
}
return 0;
}
Here's a revised version of your program:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
static void selectionSort(int data[], int count)
{
for (int a = 0; a < count - 1; a++)
{
int minimum = a;
for (int b = a + 1; b < count; b++)
{
if (data[minimum] > data[b])
minimum = b;
}
int tmp = data[a];
data[a] = data[minimum];
data[minimum] = tmp;
}
}
int main(void)
{
int randomarray[10];
srand(time(NULL));
for (int i = 0; i < 10; i++)
randomarray[i] = rand() % 100;
printf("Before:\n");
for (int i = 0; i < 10; i++)
printf("%d: %d\n", i, randomarray[i]);
selectionSort(randomarray, 10);
printf("After:\n");
for (int i = 0; i < 10; i++)
printf("%d: %d\n", i, randomarray[i]);
return 0;
}
When run, it produces output such as:
Before:
0: 73
1: 63
2: 73
3: 80
4: 28
5: 19
6: 63
7: 96
8: 82
9: 46
After:
0: 19
1: 28
2: 46
3: 63
4: 63
5: 73
6: 73
7: 80
8: 82
9: 96
Note that it prints the array before sorting as well as afterwards so that you can tell whether it sorted correctly.
The code doesn't use k; it declares variables as late as possible.
If you replace the line:
selectionSort(randomarray, 10);
with:
selectionSort(&randomarray, 10);
you get the error messages:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
> sort53.c -o sort53
sort53.c: In function ‘main’:
sort53.c:32:19: error: passing argument 1 of ‘selectionSort’ from incompatible pointer type [-Werror=incompatible-pointer-types]
32 | selectionSort(&randomarray, 10);
| ^~~~~~~~~~~~
| |
| int (*)[10]
sort53.c:5:31: note: expected ‘int *’ but argument is of type ‘int (*)[10]’
5 | static void selectionSort(int data[], int count)
| ~~~~^~~~~~
$
That's from GCC 10.1.0, but it is very similar to the error messages posted in the question. If you instead replace the call with:
selectionSort(randomarray[0], 10);
then the error messages are:
sort53.c: In function ‘main’:
sort53.c:32:30: error: passing argument 1 of ‘selectionSort’ makes pointer from integer without a cast [-Werror=int-conversion]
32 | selectionSort(randomarray[0], 10);
| ~~~~~~~~~~~^~~
| |
| int
sort53.c:5:31: note: expected ‘int *’ but argument is of type ‘int’
5 | static void selectionSort(int data[], int count)
| ~~~~^~~~~~
cc1: all warnings being treated as errors

Pointer to Array in function call in c

i'm a bit confused about using pointers.
I want to hand over the array to the pointer and then get the result of the function from the pointer.
The function just returns the minimum of an array.
int *minimum(int (*A)[5]){
int min = 0;
int A_result[1];
for (int i = 0; i < 5; i++) {
if ((*A)[i]< (*A)[min])
min = i;
}
A_result[0] = (*A)[min];
return A_result; //line 39
}
int main(void) {
int A[5] = {5, 7, 3, 6, 4};
int (*array_ptr)[5] = minimum(&A); //line 45
printf("%d ", *array_ptr);
return EXIT_SUCCESS;
}
by now i get the following errors:
line 45: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
initialization from incompatible pointer type [-Wincompatible-pointer-types]
line 39:
function returns address of local variable [-Wreturn-local-addr]
There is no need to pass pointer to array to the function second_lowest. Also, no point in returning a pointer from the function second_lowest. I modified your code :
int second_lowest(int *A) {
int min = 0;
int A_result;
for (int i = 0; i < 5; i++) {
if (A[i] < A[min])
min = i;
}
A_result = A[min];
return A_result; //line 39
}
int main(void) {
int A[5] = { 5, 7, 3, 6, 4 };
int res = second_lowest(A); //line 45
printf("%d ", res);
return EXIT_SUCCESS;
}
Hope it helps.

2D array in by reference

I have this...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//definições de constantes usadas para agilizar a implementação.
#define MINA 'M'
#define SUB 'S'
#define JOG 'U'
#define CC 'I'
//Função que inicializa posição do jogador.
void posjog(char **mesa,int lin, int col){
srand(time(NULL));
int i = rand() % 2;
int j = rand() % 2;
if(i==1){
i = lin;
}
if(j==1){
j = col;
}
mesa[i][j] = JOG;
}
//Função que inicializa a matriz vazia.
void arfill(char **mesa,int lin, int col){
for(int i=0;i<=lin;i++){
for(int j=0;j<=col;j++){
mesa[i][j]='.';
}
}
}
void show(char **mesa,int lin,int col){
for(int i=0;i<=lin;i++){
for(int j=0;j<=col;j++){
printf("%c",mesa[i][j]);
}
printf("\n");
}
}
int main(void) {
char campo[9][9]; //matriz de jogo
arfill(campo,9,9);
posjog(campo,9,9);
show(campo,9,9);
return EXIT_SUCCESS;
}
My code always crashes, i dunno why.
Can some of you please help me with this?
I have some Warnings on the Eclipse too...
"passing argument 1 of 'arfill' from incompatible pointer type [enabled by default]"
"expected 'char **' but argument is of type 'char (*)[9]'"
Array indexing starts from 0 and ends in size of array - 1.
So, this
for(int i=0;i<=lin;i++){
for(int j=0;j<=col;j++){
will go from 0 to 9 for an array of size 9x9, thus it will go out of bounds.
Similarly the rest of the code has similar problems.
You should definitely enable the warning of your compiler (-Wall flag would suffice for a start). Warnings are good to be treated like errors by us. Here is what I got:
../main.c: In function ‘main’:
../main.c:45:5: warning: passing argument 1 of ‘arfill’ from incompatible pointer type [enabled by default]
../main.c:26:6: note: expected ‘char **’ but argument is of type ‘char (*)[9]’
../main.c:46:5: warning: passing argument 1 of ‘posjog’ from incompatible pointer type [enabled by default]
../main.c:12:6: note: expected ‘char **’ but argument is of type ‘char (*)[9]’
../main.c:47:5: warning: passing argument 1 of ‘show’ from incompatible pointer type [enabled by default]
../main.c:34:6: note: expected ‘char **’ but argument is of type ‘char (*)[9]’
Finished building: ../main.c
So one way to deal with this is to use define for the sizes of the matrix. Then your code should look like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//definições de constantes usadas para agilizar a implementação.
#define MINA 'M'
#define SUB 'S'
#define JOG 'U'
#define CC 'I'
#define N 9
#define M 9
//Função que inicializa posição do jogador.
void posjog(char mesa[N][M]) {
srand(time(NULL));
int i = rand() % 2;
int j = rand() % 2;
if (i == 1) {
i = N;
}
if (j == 1) {
j = M;
}
// if i and j have the value of N and M, this will go out of bounds
// mesa[i][j] = JOG; <---- modify this
}
//Função que inicializa a matriz vazia.
void arfill(char mesa[N][M]) {
// Replaces <= with < in both for loops
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
mesa[i][j] = '.';
}
}
}
void show(char mesa[N][M]) {
// Replaces <= with < in both for loops
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
printf("%c", mesa[i][j]);
}
printf("\n");
}
}
int main(void) {
char campo[N][M]; //matriz de jogo
arfill(campo);
posjog(campo);
show(campo);
return EXIT_SUCCESS;
}
Of course you could dynamically allocate the memory for the array, which would get rid of the define. In that case don't forget to de-allocate your memory.

Resources