I want to implement Shortest path with Bellman & Ford algorithm. my idea is I use adjacent matrix
to save the information of digraph. If I want to find the shorest path of vertex i ,then I observe in-
degree of vertex i by the ith column of adjacent matrix ,and I save the shortest value of ith column
to a variable "min".if I want to find the shorest path from source vertex v to vertex i.
I only compare distance[i] with (distance[j]+ min ), because "min" is equal to adjmatrix[j][i].
In addition, I make the traverse(source, k) function to comfirm which vertex we can reach it in k
steps and use the data structure stack to save information of vertex i. I assume to that i'll get all the
shortest path from source vertex v to every vertex o graph except v itself. But the consequence after
compiling isn't that I expected. I finally got distance[i], 0 <= i < MAX_VERTEX, 1000,-1, 5, 5, 0 ,1000,
1000, respectively. What is my problem? Thanks for answer.
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX 7
#define FALSE 0
#define TRUE 1
#define MAX_DISTANCE_LIMIT 1000
#define MAX_STACK_LENGTH 100
#define MIN(x, y) ((x) < (y) ? x : y)
int stack[MAX_STACK_LENGTH];
int top = -1; //pointer to top of stack.
int adjmatrix[MAX_VERTEX][MAX_VERTEX];
short found[MAX_VERTEX]; //traverse(v ,k) : reach the vertex i By taking the k steps at most
int distance[MAX_VERTEX]; //save the shortest path that source v to every vertex i
int init_matrix(void);
void BellmanFord(int v); //v is source
void traverse(int v,int times);
void push(int vertex);
int pop(void);
int main(void){
int i,j;
init_matrix(); //initial matrix and found[] array
for(i = 0; i < MAX_VERTEX; i++){
for(j = 0; j < MAX_VERTEX; j++)
printf("%2d ", adjmatrix[i][j]);
printf("\n");
}
printf("--------------------------------------------------\n");
BellmanFord(0);
for(i = 0; i < MAX_VERTEX; i++)
printf("%4d ", i);
printf("\n");
for(i = 0; i < MAX_VERTEX; i++)
printf("%4d ", distance[i]);
return 0;
}
int init_matrix(void){
int num_edge = 0, i, j, w;
for(i = 0; i < MAX_VERTEX; i++){
found[i] = FALSE;
for(j = 0; j < MAX_VERTEX; j++)
adjmatrix[i][j] = MAX_DISTANCE_LIMIT; //set a large value to the entry of the vertice which aren't adjacent
}
while(1){
printf("enter the vertices and weight of edge connected between them(w,tail,head): ");
scanf("%d%d%d", &w, &i, &j);
if((i >= MAX_VERTEX) || (j >= MAX_VERTEX)){
fprintf(stderr, "index if the matrix should be less than %d");
exit(EXIT_FAILURE);
}
if(w == 0) break;
adjmatrix[i][j] = w;
num_edge++;
}
return num_edge;
}
void BellmanFord(int v){//compute all shortest path from v to every vertex ,and allow edge is negative
int i, k, min = MAX_DISTANCE_LIMIT, j, minpos;
for(int i = 0; i < MAX_VERTEX; i++)
distance[i] = adjmatrix[v][i]; //value of dist"1"
for(k = 2; k <= MAX_VERTEX - 1; k++){
traverse(v,k); //traverse(v ,k)will set found[i] that we can reach in k steps TRUE.
for(i = 0; i < MAX_VERTEX; i++ ){
if( found[i] == FALSE)
continue;
for(j = 0; j < MAX_VERTEX; j++)
if(adjmatrix[j][i]+distance[j] < min) {
min = adjmatrix[j][i]+distance[j];
minpos = j;
}
distance[i] = MIN(distance[i],adjmatrix[minpos][i]+distance[j]);
}
for(i = 0; i < MAX_VERTEX; i++ ) //initial found array to FALSE
found[i] = FALSE;
}
}
void traverse(int v,int times){
int i, next_order ,count = 0;
if (times == 0) return ;
for(i = 0; i < MAX_VERTEX; i++){
if((adjmatrix[v][i] != MAX_DISTANCE_LIMIT) && (!found[i])){
found[i] = TRUE;
if(times == 1)
return;
push(i);
count++;
}
}
for(i = 0; i < count; i++){
next_order = pop();
traverse(next_order,times-1);
}
return;
}
void push(int vertex){
if(top >= MAX_STACK_LENGTH){
fprintf(stderr, "The stack is full.");
exit(EXIT_FAILURE);
}
stack[++top] = vertex;
}
int pop(void){
if(top == -1){
fprintf(stderr, "The stack is empty.\n");
exit(EXIT_FAILURE);
}
else
return stack[top--];
}
/************************************
*graph information (w,tail,head)
input
6 0 1
5 0 2
5 0 3
-1 1 4
1 2 4
-2 2 1
-2 3 2
-1 3 5
3 5 6
3 4 6
0 0 0 //end the input
************************************
adjmatrix:
0 6 5 5 0 0 0
0 0 0 0 -1 0 0
0 -2 0 0 1 0 0
0 0 -2 0 0 -1 0
0 0 0 0 0 0 3
0 0 0 0 0 0 3
0 0 0 0 0 0 0
**************************************/
Related
I've been trying to do this exercise for a while but i cant seem to find where the problem may lie.
So the exercise goes like this:
We are given a matrix with 1's and 0's with 1 representing islands and 0 representing water
We have to build a code that finds us
The highest(more 1 in y direction)
The widest (more 1 in x direction)
The island with the biggest area
We also have to print the initial coordinates where this island starts(the first 2 are the dimensions of the matrix. the reading is done from a file)
5 6
1 1 0 0 0 0
0 0 1 1 0 0
0 0 1 1 0 1
0 0 0 0 0 1
1 0 1 0 0 1
Here it should print:
Max height 3: coordinates(2,5)
Max width 2: coordinates(0,0) (in case there are many with same width we just print one of
them)
Max area 4:coordinates (1,2)
I have a basic idea on how to do it.
I tried to implement it but i cant seem to understand why its not working. For now im focusing on finding the max height and width. Im sorry in advance for the messy code(i'm a beginner so for now im more focused on solving the problem than making it look pretty)
This is what i have done so far
#include <stdio.h
#include <stdlib.h>
#include <ctype.h>
int main()
{
FILE *file;
file = fopen("file", "r");
int n, m;
int i, j;
fscanf(file, "%d %d", &n, &m);
int v[n][m];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
fscanf(file, "%d", &v[i][j]);
}
}
printf("Original Matrix:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("%d ", v[i][j]);
}
printf("\n");
}
int maxheight = 0;
int height = 0;
int posx;
int posy;
i = 0;
j = 0;
while (i < n && j < m)
{
if (v[i][j] == 1)
{
height++;
i++;
}
else if (v[i][j] != 1)
{
if (maxheight <= height)
{
maxheight = height;
if (maxheight == height)
{
posx = i;
posy = j;
}
}
height = 0;
i++;
}
if (i == n)
{
i = 0;
j++;
height = 0;
}
}
printf("The biggest height =%d in position (%d ,%d)", maxheight, posx, posy);
int width = 0;
int maxwidth = 0;
int posx1;
int posy1;
i = 0;
j = 0;
while (i < n && j < m)
{
if (v[i][j] == 1)
{
width++;
j++;
}
else if (v[i][j] != 1)
{
if (maxwidth <= width)
{
maxwidth = width;
if (maxwidth == width)
{
posx1 = i;
posy1 = j;
}
}
width = 0;
j++;
}
if (j == m)
{
j = 0;
i++;
width = 0;
}
}
printf("\nThe biggest width =%d in position (%d ,%d)", maxwidth, posx1, posy1 - maxwidth);
return 0;
}
Think about the vertical max tests.
In the entire map was 1, codes reports the maxheight as 0.
Code needs to assess maxheight<=height after every height++;, not in the if(v[i][j]!=1) block.
Likewise for width.
I need to find elements of array which are hold in two of three given arrays.
It seems easy, but it's quite dificult and i have been strugling with this for few days.
I hope you can help me..
For input:
1 2 3 5
1 2 4 6 7
1 3 4 8 9 10
Output should be 3 (because 3,4,2 are common for two arrays)
for input
1 2 3 4
2 3 4
3 4 1
Output should be: 2 (because 1 is common for two arrays)
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main()
{
int duzina_prvog_niza = 0, duzina_drugog_niza = 0, duzina_treceg_niza = 0; //deklaracija duzina nizova
printf("Unesite broj clanova prvog niza:\n"); // unosimo duzine nizova i elemente nizova
do
{
scanf("%d", &duzina_prvog_niza);
} while (0 > duzina_prvog_niza || duzina_prvog_niza > 50); // mozda ne bi trebalo stavljati gornju granicu za duzinu niza
int niz1[duzina_prvog_niza]; //zavisi kako vam sistem provjere radi, mislim da nece praviti problem
// alociramo niz odgovarajuce duzine, iterativno popunimo niz uz odgovarajucu provjeru
for (int i = 0; duzina_prvog_niza > i; i++)
{
do
{
scanf("%d", &niz1[i]);
} while (0 > niz1[i] || niz1[i] > 10); // citaj elemente sve dok ne ucitas cifre iz odgovarajuceg opsega
}
for (int i = 0; duzina_prvog_niza > i; i++)
printf(" %d ", niz1[i]);
printf("\n");
// ** drugi niz ** -- bilo bi zgodno ovo sve strpati u jednu fju, meni je ovako bilo lakse.. c/p
printf("Unesite broj clanova drugog niza:\n");
do
{
scanf("%d", &duzina_drugog_niza);
} while (0 > duzina_drugog_niza || duzina_drugog_niza > 50);
int niz2[duzina_drugog_niza];
// alociramo niz odgovarajuce duzine, iterativno popunimo niz uz odgovarajucu provjeru
for (int i = 0; duzina_drugog_niza > i; i++)
{
do
{
scanf("%d", &niz2[i]);
} while (0 > niz2[i] || niz2[i] > 10); // citaj elemente sve dok ne ucitas cifre iz odgovarajuceg opsega
}
for (int i = 0; duzina_drugog_niza > i; i++)
printf(" %d ", niz2[i]);
printf("\n");
// ** treci niz **
printf("Unesite broj clanova treceg niza:\n");
do
{
scanf("%d", &duzina_treceg_niza);
} while (0 > duzina_treceg_niza || duzina_treceg_niza > 50);
int niz3[duzina_treceg_niza];
// alociramo niz odgovarajuce duzine, iterativno popunimo niz uz odgovarajucu provjeru
for (int i = 0; duzina_treceg_niza > i; i++)
{
do
{
scanf("%d", &niz3[i]);
} while (0 > niz3[i] || niz3[i] > 10); // citaj elemente sve dok ne ucitas cifre iz odgovarajuceg opsega
}
for (int i = 0; duzina_treceg_niza > i; i++)
printf(" %d ", niz3[i]);
printf("\n");
//pocetna vrijednost brojaca mora biti nula!
int brojac = 0;
int pomocni_brojac = 0;
// (S_1 intersect S_2) union (S_2 intersect S_3) union (S_3 intersect S_1) -- matematicko rjesenje problema
int x;
int pomocni_niz[duzina_prvog_niza + duzina_drugog_niza + duzina_treceg_niza];
for (int i = 0; duzina_prvog_niza + duzina_drugog_niza + duzina_treceg_niza > i; i++)
pomocni_niz[i] = 0;
int max;
if(duzina_prvog_niza>=duzina_drugog_niza && duzina_prvog_niza>=duzina_treceg_niza) max=duzina_prvog_niza;
if(duzina_drugog_niza>=duzina_prvog_niza && duzina_drugog_niza>=duzina_treceg_niza) max=duzina_drugog_niza;
if(duzina_treceg_niza>=duzina_drugog_niza && duzina_treceg_niza>=duzina_prvog_niza) max=duzina_treceg_niza;
//prolazimo kroz sve elemente u sva tri niza i poredimo sve elemente sa svim elementima
for (int i = 0; duzina_prvog_niza > i; i++)
{
for (int j = 0; duzina_drugog_niza > j; j++)
{
for (int k = 0; duzina_treceg_niza > k; k++)
{ // ako je element iz prvog niza jednak elementu iz drugog niza, ili je element
if (((niz1[i] == niz2[j]) && (niz2[j] == niz3[k]) && (niz1[i] == niz3[k])))
1;
else if ((niz1[i] != niz2[j]) && (niz2[j] == niz3[k]) && (niz1[i] != niz3[k]))
pomocni_niz[pomocni_brojac++] = niz2[j];
else if ((niz1[i] == niz2[j]) && (niz2[j] != niz3[k]) && (niz1[i] != niz3[k]))
pomocni_niz[pomocni_brojac++] = niz1[i];
else if ((niz1[i] != niz2[j]) && (niz2[j] != niz3[k]) && (niz1[i] == niz3[k]))
pomocni_niz[pomocni_brojac++] = niz2[j];
}
}
}
int y = 0;
for (int g = 0; pomocni_brojac > g; g++)
{
for (int l = 0; pomocni_brojac > l; l++)
{
if (pomocni_niz[g] == pomocni_niz[l])
y++;
}
if (y == 0)
brojac++;
y = 0;
}
for (int i = 0; brojac > i; i++)
printf("%d ", pomocni_niz[i]);
printf("U dva od tri niza se nalazi %d clanova.", brojac);
return 0;
}
Thanks!
There exists a pretty fast solution to your problem. You will need three more arrays each having a size of 100. Each array will record the frequency of any particular input array. The size of each frequency array is 100 since any input array will only consist of numbers in the range 0-99.
For example:
Input arrays:
A: 1 2 3 5
B: 1 2 4 6 7
C: 1 3 4 8 9 10
Frequency arrays:
0 1 2 3 4 5 6 7 8 9 10
A: 0 1 1 1 0 1 0 0 0 0 0
B: 0 1 1 0 1 0 1 1 0 0 0
C: 0 1 0 1 1 0 0 0 1 1 1
In the frequency arrays section:
The top row denotes number which may be present in any input array and the rows below contains their frequency in each input array..
Algorithm
1 : let frequencyA[100]
2 : let frequencyB[100]
3 : let frequencyC[100]
4 :
5 : for i = 0 to A.length-1
6 : if (frequencyA[A[i]] == 0) frequencyA[A[i]]++
7 : for i = 0 to B.length-1
8 : if (frequencyB[B[i]] == 0) frequencyB[B[i]]++
9 : for i = 0 to C.length-1
10: if (frequencyC[C[i]] == 0) frequencyC[C[i]]++
11:
12: for i = 0 to 99
13: if (frequencyA[i]+frequencyB[i]+frequencyC[i] == 2) Print i
The algorithm is pretty straight forward. The only that lines that deserve some explanation are mentioned below.
Line 5-10:
For each input array, we loop though each of its element and record their frequency. We record the frequency of any particular element only once, that is, if any element repeats in a single array, we will record its frequency only once. This is made sure by the if condition which checks if we have recorded the frequency of any element before or not.
Line 12-13:
We start a loop from 0 to 99 since they are the possible values of the array. In the loop, we check if sum of the frequency in the all the three frequency arrays of any element is 2 or not. If its 2, then that element is present in present exactly twice else not.
Time Complexity
The algorithm has a time complexity of O(A.length + B.length + C.length). It is a linear time complexity which is quite fast.
I can not provide you with any code as I do not code in C a lot. I hope I have helped you. If you face any trouble in understanding my answer, please do comment. I will be happy to update my answer.
For starters always use English words for identifiers. In this case your code will be readable for a larger auditorium. Otherwise it is difficult to read it.
This statement in your program
if (((niz1[i] == niz2[j]) && (niz2[j] == niz3[k]) && (niz1[i] == niz3[k])))
1;
does not make a sense.
If you need to output common elements that are present exactly in two of three arrays then there is no great sense to create a forth array with the size equal to the sum of sizes of the three arrays.
If the arrays can be unsorted and you may not sort the arrays then a straightforward approach can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
void f( const int a1[], size_t n1, const int a2[], size_t n2, const int a3[], size_t n3 )
{
size_t total = 0;
for ( size_t i1 = 0; i1 < n1; i1++ )
{
size_t count = 1;
size_t i2 = 0;
while ( i2 < n2 && a2[i2] != a1[i1] ) i2++;
count += i2 != n2;
size_t i3 = 0;
while ( i3 < n3 && a3[i3] != a1[i1] ) i3++;
count += i3 != n3;
if ( count == 2 )
{
++total;
printf( "%d ", a1[i1] );
}
}
for ( size_t i2 = 0; i2 < n2; i2++ )
{
size_t i1 = 0;
while ( i1 < n1 && a1[i1] != a2[i2] ) i1++;
if ( i1 == n1 )
{
size_t i3 = 0;
while ( i3 < n3 && a3[i3] != a2[i2] ) i3++;
if ( i3 != n3 )
{
++total;
printf( "%d ", a2[i2] );
}
}
}
if ( total != 0 ) putchar( '\n' );
printf( "%zu\n", total );
}
int main(void)
{
int a[] = { 1, 2, 3, 5 };
int b[] = { 1, 2, 4, 6, 7 };
int c[] = { 1, 3, 4, 8, 9, 10 };
size_t n1 = sizeof( a ) / sizeof( *a );
size_t n2 = sizeof( b ) / sizeof( *b );
size_t n3 = sizeof( c ) / sizeof( *c );
f( a, n1, b, n2, c, n3 );
return 0;
}
The program output is
2 3 4
3
I am trying to implement Dijkstras algorithm in c and I almost have the right output. Something is happening it the dist array. It is giving extremely large and small numbers.
Link to site I'm basing most of my algorithm code on: https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ this also explains the algorithm if you're not familiar.
Here is the code:
#include <limits.h>
#include <stdio.h>
#include<stdbool.h>
#define N 10 /* max matrix size is 10 x 10 */
#define INF INT_MAX /* infinity? */
int src; /* global */
void getdata(int amtrx[3][N], int *n, int *src) {
int i, j, nsz, nedg, fr, to, vtx, wt;
scanf("%d %d %d", &nsz, &nedg, &vtx);
for (i = 0; i < nsz; i++)
for (j = 0; j < nsz; j++)
amtrx[i][j] = INF;
for(i=0; i < nedg; i++) {
scanf("%d %d %d", &fr, &to, &wt);
amtrx[fr][to] = wt;
}
*n = nsz;
*src = vtx;
}
void printpaths(int dist[], int n) {
int i;
for (i = 0; i < n; i++)
if(i == src);
else if (dist[i] < INF) {
printf("%d %d %d\n", src, i, amtrx[i]);
} else {
printf("%d %d INF (no path)\n", src, i);
}
}
void dijkstras(int amtrx[][N], int n) {
int dist[n], v;
bool spt[n];
int min = INF, u;
for (v = 0; v < n; v++)
if (spt[v] == false && dist[v] <= min) {
min = dist[v], u = v;
spt[u] = true;
}
for (v = 0; v < n; v++)
if (!spt[v] && amtrx[u][v] != INF && dist[u] != INF && dist[u] + amtrx[u][v] < dist[v])
dist[v] = dist[u] + amtrx[u][v];
printpaths(dist, n);
}
int main() {
int amtrx[N][N];
int n;
getdata(amtrx, &n, &src);
dijkstras(amtrx, n);
return 0;
}
Here is the input:
6 11 0
0 1 50
0 2 10
0 4 45
1 2 15
1 4 10
2 0 20
2 3 15
3 1 20
3 4 35
4 3 30
5 4 03
Output:
0 1 32701
0 2 -1996178040
0 3 -1996178014
0 4 -1996178044
0 5 32765
Expected output:
0 1 45
0 2 10
0 3 25
0 4 45
0 5 INF (no path)
Thanks for the help in advance! I'm hoping it's just a simple fix that I can't seem to see :)
update
I think the algorithm was wrong and I worked on it a little, the output is still wrong but i think this is more right than before:
void dijkstras(int amtrx[][N], int n) {
int dist[n], v, q;
bool spt[n];
int min = INF, u;
for (v = 0; v < n; v++) {
dist[v] = INF;
spt[v] = false;
}
dist[n] = 0;
for (v = 0; v < n - 1; v++) {
for (q = 0; q < n; q++) {
if (spt[v] == false && dist[v] <= min) {
min = dist[v], u = v;
}
spt[u] = true;
}
for (v = 0; v < n; v++)
if (!spt[v] && amtrx[u][v] != INF && dist[u] != INF && dist[u] + amtrx[u][v] < dist[v])
dist[v] = dist[u] + amtrx[u][v];
}
printpaths(dist, n);
}
Output now:
0 1 INF (no path)
0 2 INF (no path)
0 3 INF (no path)
0 4 INF (no path)
0 5 INF (no path)
update 2
void dijkstras(int amtrx[][N], int n) {
int min = INF, dist[N], count, v, u;
bool spt[N];
for (v = 0; v < N; v++) {
dist[v] = INF;
spt[v] = false;
}
dist[src] = 0;
for (count = 0; count < N - 1; count++) {
for (v = 0; v < N; v++)
if (spt[v] == false && dist[v] <= min)
min = dist[v], u = v;
spt[u] = true;
for (v = 0; v < N; v++)
if (!spt[v] && amtrx[u][v] && dist[u] != INF && dist[u] + amtrx[u][v] < dist[v])
dist[v] = dist[u] + amtrx[u][v];
}
printpaths(dist, n);
}
output:
0 1 50
0 2 10
0 3 INF (no path)
0 4 45
0 5 INF (no path)
I'm so close I can taste it! Any help is appreciated!
void dijkstras(int amtrx[][N], int n) {
int min = INF, dist[n], count, v, u;
bool spt[n];
for (v = 0; v < n; v++) {
dist[v] = INF;
spt[v] = false;
}
dist[src] = 0;
for (count = 0; count < n - 1; count++) {
min=INF;
for (v = 0; v < n; v++)
if (spt[v] == false && dist[v] <= min)
min = dist[v], u = v;
spt[u] = true;
for (v = 0; v < n; v++)
if (!spt[v] && amtrx[u][v] != INF && dist[u] != INF && dist[u] + amtrx[u][v] < dist[v])
dist[v] = dist[u] + amtrx[u][v];
}
printpaths(dist, n);
}
I want to get output like this using nested for loops:
0 0
0 1
0 2
0 3
1 3
1 2
1 1
1 0
2 0
2 1
2 2
2 3
3 3
3 2
3 1
3 0
So I came up with this solution:
for(i=0;i<4;i++) {
if(i == 1){
for(j=3;j>=0;--j) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}else if(i == 3){
for(j=3;j>=0;--j) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}else{
for(j=0;j<4;j++) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
}
This works but is there way to do this without if conditions inside the loops?
Here you are.
#include <stdio.h>
int main(void)
{
const int N = 3;
for ( int i = 0; i <= N; i++ )
{
for ( int j = 0; j <= N; j++ )
{
printf( "%d %d\n", i , i % 2 == 0 ? j : N - j );
}
}
return 0;
}
The program output is
0 0
0 1
0 2
0 3
1 3
1 2
1 1
1 0
2 0
2 1
2 2
2 3
3 3
3 2
3 1
3 0
Or the loops can be written like
const int N = 4;
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
printf( "%d %d\n", i , i % 2 == 0 ? j : N - j - 1 );
}
}
I am not the Arduino guy, but as its similar to C and this question is more about the algorithm let me sketch an approach in C:
#define LEFT_START (0)
#define LEFT_END (3)
#define RIGHT_START (0)
#define RIGHT_END (3)
enum DIRECTION {
DOWN = -1,
UP = 1
};
int main(void)
{
for (int direction = UP, i = LEFT_START, j = RIGHT_START - sign;
i <= LEFT_END;
++i, direction *= -1)
{
for (j += direction;
j >= RIGHT_START && j <= RIGHT_END;
j += direction)
{
printf("%d %d\n", i, j);
}
}
}
No if/then, not explicitly, nor implicitly via ternary-operator, BTW. ;)
I don't know what your purpose was, but you need to use if statement. This code will do the thing you want
int n =3;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
for (int i=0; i<=n; i++){
if(i%2 == 0){
for (int j=0; j<=n; j++){
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
else{
for (int j=n; j>=0; j--){
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
}
}
The output looks like this,
Defining variables/constant n, i, j is entirely up to you based on your project. This code is just a simple demonstration.
I wrote a code to find median filtering (median window). But, I can't make scannig to every number. What can I use instead of size in the for loops. When I use size it ensures just 5 Also, what about boundries ? What can I do for boundries ? Thank you for all appreciated answers. (I've opened new topic because users said that every topic is based on one question.If I did mistake,please delete the question, I will suffix the current question)
<size of array>
<size filter>
<data>
8
3
0 0 0 0 0 0 0 0
0 5 0 0 6 0 0 0
0 0 0 0 0 7 0 0
0 0 0 0 5 0 0 0
0 0 0 5 6 0 0 0
0 0 8 5 5 0 0 0
0 0 0 7 0 0 9 0
0 0 0 0 0 0 0 0
Output:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 5 5 0 0 0
0 0 0 5 5 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
#include <stdio.h>
int median(int a[100],int n);
int main()
{
int a[100][100];
int temp[100];
int i,j,k,count=0;
int sizefilter;
int sizearray;
scanf("%d", &sizearray);
scanf("%d", &sizefilter);
for(i = 0; i < sizearray; i++)
for(j = 0; j < sizearray; j++)
scanf("%d", &a[i][j]);
for(k = 0; k < sizearray; k++)
for(i = 0; i < sizefilter; i++)
for(j = 0; j < sizefilter; j++)
{
temp[count] = a[i][j];
count++;
a[i][j] = median(temp, count);
}
printf("\n");
printf("\n");
for(i = 0; i < sizearray; i++)
for(j = 0; j < sizearray; j++)
{
printf("%d ", a[i][j]);
if(j == sizearray-1)
printf("\n");
}
return 0;
}
int median(int a[100],int n)
{
int i,j,t;
int result;
/* Sorting begins */
for (i = 1 ; i <= n-1 ; i++)
{ /* Trip-i begins */
for (j = 1 ; j <= n-i ; j++)
{
if (a[j] <= a[j+1])
{ /* Interchanging values */
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
else continue ;
}
} /* sorting ends */
/* calculation of median */
if ( n % 2 == 0)
return result = (a[n/2] + a[n/2+1])/2 ;
else
return result = a[n/2 + 1];
}
There are some logical errors in your code:
When you filter, you need four nested loops: The outer two iterate over columns and rows of the matrix, the inner two iterate over columns and rows of the filter area. (That shouldn't be news to you; you have already been told that in an answer to your previous question.)
The constraints of the filter area are simple: The left and top indices must not fall below zero and the right and bottom indicies must be smaller than sizearray. If they are not, adjust them.
You need two arrays, the original array a and a second array that contains the filtered values. You cannot filter in-place, because if you look upwards and to the left, you'll see only filtered values, whereas your filter should always look at the original values.
Your wrong filtering loops apart: You never reset count, which you should reset, of course, for every median value you calculate. You also calculate the median in the inner loop, which is too often. A solution to this is to make count local to the loop that accumulates filter values and determines the median.
Your sorting has index errors. Instead of comparing i with i + 1, compare with ´i - 1. Your indices start from 1, soi - 1` will always yield a valid index.
You buble-sort the array, which is fine for small arrays, but slow in general. The <stdlib.h> has qsort, which may be useful to you for general sorting.
Your median indices are also off by one towards the right.
There are also some stylistic issues:
Please make a habit of using braces for code blocks for for, while and if. Only very trivial code blocks in the innermost scope can be written without braces. In your case, a lot has to be done "between" the loops, and having braces there makes it easy to add stuff.
Yor variable result in median is superfluous. You assign it and then immediately lose the variable itself, because you return. Just returning is enough.
Below is a version of your code that gives the desired output:
#include <stdint.h>
#include <stdio.h>
int min(int a, int b)
{
return a < b ? a : b;
}
int max(int a, int b)
{
return a > b ? a : b;
}
int median(int a[], int n)
{
int i, j;
for (i = 1 ; i < n ; i++) {
for (j = 1 ; j < n ; j++) {
if (a[j] < a[j - 1]) {
int t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}
}
if (n % 2) return a[n / 2];
return (a[n / 2 - 1] + a[n / 2]) / 2 ;
}
int main()
{
int a[100][100];
int b[100][100];
int temp[100];
int i, j, ii, jj;
int sizefilter;
int sizearray;
scanf("%d", &sizearray);
scanf("%d", &sizefilter);
for(i = 0; i < sizearray; i++) {
for(j = 0; j < sizearray; j++) {
scanf("%d", &a[i][j]);
}
}
for(i = 0; i < sizearray; i++) {
for(j = 0; j < sizearray; j++) {
int imin = max(0, i - sizefilter / 2);
int imax = min(sizearray, i + sizefilter / 2 + 1);
int jmin = max(0, j - sizefilter / 2);
int jmax = min(sizearray, j + sizefilter / 2 + 1);
int count = 0;
for (ii = imin; ii < imax; ii++) {
for (jj = jmin; jj < jmax; jj++) {
temp[count] = a[ii][jj];
count++;
}
}
b[i][j] = median(temp, count);
}
}
for(i = 0; i < sizearray; i++) {
for(j = 0; j < sizearray; j++) {
printf("%3d", b[i][j]);
}
printf("\n");
}
return 0;
}