Calculating the dispersion in C - c
I'm trying to calculate the dispersion between two values, one I get from and certain parameter('age') from each entry on the array of structures.
I've got an auxiliary .txt file and, the whole point of this is to go through each of the lines of the .txt file individually (each line is a string). It's better if I state an example, so, here we go:
matrix[n][n]:
1 2 3 4
1 2 3
1 2
So, the structure would look a bit like this:
struct person {
int id; //where im comparing between the matrix and the structure;
int age; //what I need to calculate the dispersion
}
I gotta compare the each value of each line of the .txt, and if it matches any of the id's on the structure, I gotta get its age. Now comes the tricky part.
To calculate the dispersion I need to get the following working out for me:
Let's take as example the first row of the .txt file: the dispersion would be:
let's say that 'age' = age of the id (n);
//in this case nGroups = 6 (number of age(n)-age(m) operations)
dispersion(first_row)= [ [|age(1)-age(2)|] + [|age(1)-age(3)|] + [|age(1)-age(4)|] + [|age(2)-age(3)|] + [|age(2)-age(4)|] + [|age(3)-age(4)|] ]/nGroups
So I have to do this for each row of the matrix. I've tried it and managed the following code, but in the 'math' part my brain freezes a bit.
// going through each line of the matrix
for(i=0; i<nconjuntos; i++) {
// going through each column of the matrix
for(j=0; j<strlen(aux[i]); j++) {
// going through all the structures in the structure array
for(k=0; k<TOTAL; k++) {
// comparing each number with it's id equivalent in
// each structure.id parameter in the array
if(aux[i][j] - 48 == pessoas[k].id) {
}
}
}
}
Any help that would help me to advance in my code would be really appreciated!
You have two problems here requiring a solution:
Match the id in the matrix with the id in the structure and get a list of ages for a given row
Calculate the dispersion
It's probably easiest if you separate these two tasks instead of doing them both inside the same nested for loop. You can write a function to calculate the dispersion according to the formula you gave like this:
double calculateDispersion(double* values, int count)
{
if(count < 2)
return 0.0; // need at least 2 values
double total = 0.0;
// iterate through each combination of values and sum the absolute
// differences of each combination:
int i, j;
for(i = 0; i < (count - 1); i++)
{
for(j = i + 1; j < count; j++)
{
double difference = values[i] - values[j];
if(difference < 0.0) // find absolute value
difference = 0.0 - difference;
total += difference; // add to the total
}
}
int groups = (count * (count - 1)) / 2;
return total / (double)groups;
}
Inside your main loop create an array of doubles equal in size to the largest row in your matrix, to store the ages for the current row (or floats, but using ints will give you rounding errors). Fill it up by cross-referencing with the structs containing the id and age. Then call calculateDispersion() to calculate the dispersion for the row.
Something like roughly this:
double rowArray[MAX_SIZE]; // or initialize to maximum matrix row length dynamically
// going through each line of the matrix
for(i=0; i<nconjuntos; i++) {
int count = 0;
// going through each column of the matrix
for(j=0; j<strlen(aux[i]); j++) {
// going through all the structures in the structure array
for(k=0; k<TOTAL; k++) {
// comparing each number with it's id equivalent in
// each structure.id parameter in the array
if(aux[i][j] - 48 == pessoas[k].id) {
// set array value:
rowArray[count++] = (double)pessoas[k].age;
break; // break out of the loop
}
}
}
// compute the dispersion for the row:
doubleDispersion = calculateDispersion(rowArray, count);
}
Related
How i can find all unique sets of positions of elements in matrix in C?
I need to solve the following problem for a 5×5 matrix, but to explain I will use an example with a 3×3 matrix: A = { { 1, 3, 2 } ,{ 3, 2, 3 } ,{ 0, 4, 5 } }; I need to find all distinct sets of 3 (because the matrix is 3x3) positions sharing no row or column with the others, compute the sum of elements of A for each set of positions, and print the minimum of these sums. Position = (0,0),(1,1),(2,2) sum = 1+2+5 = 8 (0,0),(1,2),(2,1) sum = 1+3+4 = 8 (0,1),(1,0),(2,2) sum = 3+3+5 = 11 (0,1),(1,2),(2,0) sum = 3+3+0 = 6 (2,0),(1,1),(0,2) sum = 0+2+2 = 4 . . . (I think you understood the main principle). So the output must include: (2,0),(1,1),(0,2) minimal sum = 4 Remember: I actually need to do it for a 5×5 matrix.
A functional, albeit naive, way to do this is to use 6 for-loops (5 nested). Loop from 0 to 2 with the top loop storing its iteration # in an int (called firstRow for example). Similarly the second loop will store firstCol. The third loop will be used to store secondRow so you'll need to continue if secondRow == firstRow. For the last two loops you'll need to check against the indeces for the other two. In the innermost nested loop, call your findSum function with the 3 coordinate pairs. testCoords(*arr1, *arr2, *arr3) { #get the sum } #algorithm defined for n = 3 mySearch(n) { int coord1[2], coord2[2], coord3[2]; #assume 3by3 int minSum = n * MAX_VAL, obsSum; for (int r1 = 0; r1 < n; r1++) { coord1[0] = r1; for (int c1 = 0; c1 < n; c1++) { coord1[1] = c1; for (int r2 = 0; r2 < n; r2++) { if (r1 != r2) { coord2[0] = r2; for (int c2 = 0; c2 < n; c2++) { if (c1 != c2) { coord2[1] = c2; for (int r3 = 0; r3 < n; r3++) { if (r1 != r3 && r2 != r3) { coord3[0] = r3; for (int c3 = 0; c3 < n; c3++) { coord3[1] = c3; obsSum = testCoords(coord1, coord2, coord3); if (obsSum < minSum) { minSum = obsSum; } } } } } } } } } } } This will be fine for small arrays such as n=3 or n=5, but the number of iterations quickly gets ridiculous as its n^(n*2). For example, even with 5x5 matrix you'll do 10 million iterations (not too mention a long winded algorithm). A more dynamic algorithm or perhaps a tree implementation is probably a good fit here. For example, a recursive approach could find one index pair (which eliminates a row and column), then calls itself with the resultant (n-1)*(n-1) 2d array -- as so: int minSum = n * MAX_VAL; coordSearch(int **matrix, n) { int thisCoord[2]; if (n == 1) { return matrix[0][0]; } else { for (int i = 0; i < n; i++) { thisCoord[0] = i; for (int j = 0; j < n; j++) { thisCoord[1] = j; ##need to update the matrix s.t. row represented by i is removed and col represented by j is removed ##ill leave that up to you -- assume its called updatedMatrix updatedMatrix = reduce(matrix, i, j); return matrix[thisCoord[0], thisCoord[1]] + coordSearch(updatedMatrix, n-1); } } } } int main(void) { #have some 2d structure that is n * n int minSum = n * MAX_VAL, obsSum; int row, col; for (int i = 0; i < n; i++) { row = i for (int j = 0; j < n; j++) { col = j; updatedMatrix = reduce(matrix, row, col); obsSum = coordSearch(updatedMatrix, n- 1); if (obsSum < minSum) { minSum = obsSum; } } } } For a 3x3 2d array, the recursive approach will look at the 9 coordinate pairs at the top level, then in the next level we will be dealing with a 2x2 2d array so we will only consider 4 coordinate pairs, then in the bottom level we just return whichever value resides in our 1x1 "2d array". Complexity is n^2 * (n-1)^2 * .. * 1. Keep in mind though, that each "step" requires updating the matrix which is a operation dense procedure.
Here's another suggestion: all of the sets of locations in the matrix that you want to use can be represented as permutations of an identity matrix whose "1" entries tell you which matrix elements to add up. You then take the minimum over the set of sums for all of the permutations. You can represent a permutation with a simple array since there are only N elements equal to 1 in a permutation of the NxN identity matrix. So call that array p where p(i) tells you which column on the i'th row to use. So the fundamental observation here is that you want all permutations of the NxN identity matrix, and you can represent these as permutations of (0,1,...,N-1). Pseudocode might look like: Given: an NxN matrix (2-D array), M, for which you want the minimal sum of N elements with no subset falling on the same row or column minsum = N * max entry in M (just initialized to guarantee >= min sum sought) foreach permutation p of (0,1,...,N-1): sum = 0 for i = 0:N-1: sum += M(i,p(i)) if sum >= minsum: break; # (if we already know this isn't a new min, move on) if sum < minsum: minsum = sum print("minimum sum = ", minsum) Adding a bit of code to remember a particular set of locations that add up to the minimum is left here as an exercise for the reader. Note that this gives up on any permutation as soon as it's not going to be a new minimum sum. For an NxN array, there are N! permutations, so in practice this gets expensive fast for large N (not your current problem at N = 5). At that point, deeper dynamic programming techniques to quit early on partial results or avoid recomputing subset sums by using, say, memoization would be applicable and desirable. Most other algorithms are going to do the same basic work in some way that may or may not look obviously similar in code. I like this approach because it has a nice mapping onto a fairly straight-forward understanding in mathematical terms and you can readily identify that what makes it get expensive quickly as N grows is the need to calculate a minimum over a rapidly-expanding set of permutations. Algorithms to compute all permutations of an array are pretty easy to come by and you get one for free in C++ in the function next_permutation, which is part of the STL. My recommendation is to google "list all permutations" and if you need to work in a particular programming language, add that to the query as well. The algorithm isn't terribly complicated and exists in both recursive and iterative forms. And hey, for the 5x5 case you could probably statically list all 120 permutations anyway.
Find location of numbers in 2d array
I have two arrays. Array A and Array B. Now I need to get where in array B is sequence from array A located. I need to get location of last number and I don't know how. A[4]={6,3,3,2}; B[10][18]={ {5,3,6,5,6,1,6,1,4,4,5,4,4,6,3,3,1,3}, {6,2,3,6,3,3,2,4,3,1,5,5,3,4,4,1,6,5}, {6,4,3,1,6,2,2,5,3,4,3,2,6,4,5,5,1,4}, {5,3,5,6,6,4,3,2,6,5,1,2,5,6,5,2,3,1}, {1,2,5,2,6,3,1,5,4,6,4,4,4,2,2,2,3,3}, {4,1,4,2,3,2,3,6,4,1,6,2,3,4,4,1,1,4}, {5,3,3,2,6,2,5,2,3,1,2,6,5,1,6,4,1,3}, {4,5,2,1,2,5,2,6,4,3,3,2,3,3,3,1,5,1}, {1,3,5,5,2,1,3,3,3,1,3,3,6,3,3,3,6,5}, {4,5,2,4,2,3,4,2,5,6,5,2,6,3,5,4,5,2} }; For example: Sequence 6,3,3,2 start in second row and in forth column and ends in seventh column. I need to get location of number 2. My result should be: Row = 2, Column= 7 Sequence isn't always in row. It can be in column to. For example: 3,2,4,3 and I ned to know location of number 4. I know how to search one number in one dimensional array but in this case I don't have solution. Language is C.
You can compare blocks using memcmp: for (i = 0; i < rows; i++) { /* For each row */ for (j = 0; j < cols - size; j++) { /* For each col until cols - 4 */ if (memcmp(A, &B[i][j], sizeof(A)) == 0) { /* Compare entire block */ #include <stdio.h> #include <string.h> int main(void) { int A[4] = {6,3,3,2}; int B[10][18] = { {5,3,6,5,6,1,6,1,4,4,5,4,4,6,3,3,1,3}, {6,2,3,6,3,3,2,4,3,1,5,5,3,4,4,1,6,5}, {6,4,3,1,6,2,2,5,3,4,3,2,6,4,5,5,1,4}, {5,3,5,6,6,4,3,2,6,5,1,2,5,6,5,2,3,1}, {1,2,5,2,6,3,1,5,4,6,4,4,4,2,2,2,3,3}, {4,1,4,2,3,2,3,6,4,1,6,2,3,4,4,1,1,4}, {5,3,3,2,6,2,5,2,3,1,2,6,5,1,6,4,1,3}, {4,5,2,1,2,5,2,6,4,3,3,2,3,3,3,1,5,1}, {1,3,5,5,2,1,3,3,3,1,3,3,6,3,3,3,6,5}, {4,5,2,4,2,3,4,2,5,6,5,2,6,3,5,4,5,2} }; size_t i, j, size, rows, cols; int founded = 0; size = sizeof(A) / sizeof(A[0]); rows = sizeof(B) / sizeof(B[0]); cols = sizeof(B[0]) / sizeof(B[0][0]); for (i = 0; i < rows; i++) { for (j = 0; j < cols - size; j++) { if (memcmp(A, &B[i][j], sizeof(A)) == 0) { founded = 1; break; } } if (founded) break; } if (founded) printf("Row: %zu Col: %zu\n", i + 1, j + size); return 0; }
The problem is not the language. The problem you face is you need to come out with the algorithm first. Actually this can be easily done by just looking at the first number of the 1D array. In your example it is 6 from (6,3,3,2). Look for 6 in your 2D array. Once 6 is found use a loop which loop 4 times (because there are 4 numbers to look for - (6,3,3,2). In the loop, check whether the subsequent numbers are 3,3,2. If it is, return the location Else continue the process to look for 6. Done! It will look like this: for(x=0; x<rows; x++) for(y=0; y<cols; y++) { if(matrix[x][y] == array1D[0]) for(z=1; z<array1DSize; z++){ if(matrix[x][y] != array1D[z]) break; location = y; } }
If you know how to do it with a one dimensional array, you can do it like that in C with multidimensional arrays too! For instance, say you have a two dimensional array like so: int array[5][5]; // 5x5 array of ints You can actually access it in linear fashion, by doing: (*array)[linear offset] So that means if you want to access the 2nd column of the 2nd row, you can do: (*array)[6] Because the 2nd row starts at index 5, and the second column is at index 1, so you would do (5+1) to get 6. Likewise, the 3rd row would start at index 10, so if you wanted the 2nd column in the third row, you can do (10+1). Knowing that, you can take your original algorithm and adapt it to access the multidimensional array in a linear fashion. This takes place of the "wrap around" possibility as well.
Computing the frequency of 5 in an array
Very basic query here from a beginner... I'm looking to find the frequency of a number within an array... In the (mangled) code below I have tried to calculate the occurances of the number 5 in the array I'm running into problem in formulating the for loop Heres my code attempt: //Compute the frequency of 5 in the array named numbers public class find //Begin class { public static void main (String []args) //Begin main { double numbers[] = {6,7,12,5,4,2,4,6,9,5,7,11,1,23,32,45,5}; //Initialise and populate array int total = 0; int counter = 0; for (int x : numbers) { if (numbers[] == 5; counter ++) {System.out.println( numbers[i] + " "); } } // end code // *****************
int numbers[] = {6,7,12,5,4,2,4,6,9,5,7,11,1,23,32,45,5}; for(int x : numbers) { if(x == 5) counter++; } System.out.println(counter); I can see that you were trying to use a for each loop in your implementation. #Code Whisperer provides a good alternative to that, but if you do want to use a for each loop then you have to make sure you loop type and array type match. In your case, your array is type double but your loop type is int. Within each iteration, you're selecting an individual value in the array, so you don't need to include any brackets.
for (int i = 0; i < numbers.length; i++) { if (numbers[i] == 5) { counter++; System.out.println(counter); // shows how many 5s you have so far } } Loop through array, compare every element in the array to 5. If it is 5, increment counter by 1.
How to count how many times values were used in the array C?
Here's my problem If certain number has been entered into an array I need that number to be displayed and occurrence of that number in the array. for example if user enters number 5 three times then "The number 5 has been entered 3 times so far" and so on Here's my code so far: int i,j; int num_count = 0; for(i=0;i<6;i++) { num_count = 0; for(j=1;j<43;j++) { if( *(num + i) == j) { printf("The number %d has been used %d times\n",j,num_count); }//end if }//end inner for }//end outer for
I will like to suggest you a very time efficient method for this, but it needs some extra memory. Assume the upper limit of numbers inside array is 'MAX_NUM_IN_ARRAY', so you should create array (say counter) of size 'MAX_NUM_IN_ARRAY+1' and initialize it to 0. int counter[MAX_NUM_IN_ARRAY+1]={0}; now scan the input array from first to last element, for each number: //say number is num counter[num]++; and at the end you have to just scan that counter array from index 1 to MAX_NUM_IN_ARRAY. Sample code: Suppose input array is a[], number of elements in array is n, maximum limit of number inside array is MAX_LIMIT int counter[MAX_LIMIT]={0}; int i; for(i=0; i<n; i++) { counter[a[i]]++; } for(i=0; i<MAX_LIMIT; i++) { printf("Number %d is appeared for %d times\n", i, counter[i]); }
============EDIT You could write a series of functions that handle your collection. the collection could be a 2 dimentional array like so numbers[][] where numbers[n][0] is your number, and numbers[n][1] is the number of times it occurred... and the gold would be in your add() function add() does a few things, a user passes a value to add(), first checks if number exists in numbers[n][0] if the value exists at numbers[n][0] numbers[n][1]++; if it doesn't already exist, check if the array is full if it is full, copy all the data to a new, larger array add it to the end of the array.. this is how to do it. ==OR just design a 1 dimentional array numbers[] that holds all of your numbers.. and the add() function only: if(it is full){copies to larger array} adds number to the end; and modify the code I wrote earlier (Below).. to print the most common number and it's occurrence count ============EDIT I'm a Java guy so you'll need to translate (shouldn't be too hard..) This is going to be just like a sorting algorithm with a little bit of extra logic (later search for Selection Sort) int[] temp = {4,3,2,4,4,5}; ////// find the most commonly occuring value int times; int moreTimes = 1; int value = temp[0]; for(int i = 0; i < temp.length; i++) { times = 1; for(int j = i+1; j < temp.length; j++) { if(temp[i] == temp[j]) times++; } if(times > moreTimes) { moreTimes = times; value = temp[i]; } } /////// count the most common value int count = 0; for(int i = 0; i < temp.length; i++) { if(temp[i] == value) count++; } System.out.println("number: " + value + ", count: " + count);
Getting an average from values obtained by a sensor using C
Ok so I get this code to do the averaging : (written in C ) . . int sum[3]; int j; int avg; for(;;) //infinite loop { for(j=0;j<3;j++){ i = ReadSensor(); // function that keeps saving sensor values as int i sum[j]=i; } avg=sum[0]+sum[1]+sum[2]+sum[3]; printf("Sonar: %d \r \n", avg >> 2); } . . Is this correct ? im shifting by 2 to divide by avg / 2^(2) which is 4 The problem is im expecting a value of about 15, however I get about 8--9 .. Im not sure why this is happening ? Basically the sensor's readings fluctuate between 15-17, I want to get an average instead of printing noise values. Is my code correct ? Then why do I get wrong outputs !?
Looks like your script only captures three values (j=0, j=1, j=2), then divides by four.
You have a few problems, here are some suggestions: You're iterating through the inside loop 3 times, however you're saying you have 4 sensors, you should change your for loop to: for (j = 0; j < 4; j++). sum is an array of 3 elements, yet you're accessing an element 1 past the end of the array when calculating avg (sum[3]). This will cause undefined behaviour. sum should be declared as char sum[4] for this reason and the one above. (Optional) sum does not need to be an array in the above example, it can simply be an int. (Optional) If you want to divide an int by 4, use the division operator. The compiler should be better at optimizing the code for your particular architecture than you. This is how your code could now look, depending on whether you need to keep an array or not: int sum[4]; int total, j; for (;;) { total = 0; /* reset at every iteration of the outside loop */ for (j = 0; j < 4; j++) { sum[i] = ReadSensor(); total += sum[i]; } printf("Sonar: %d \r \n", total / 4); } OR int total, j; for (;;) { total = 0; /* reset at every iteration of the outside loop */ for (j = 0; j < 4; j++) total += ReadSensor(); printf("Sonar: %d \r \n", total / 4); }
Isn't this avg=sum[0]+sum[1]+sum[2]+sum[3]; should be avg=sum[0]+sum[1]+sum[2]; as the loop as well declaration int sum[3]; means we are trying to store only 3 values. Now if you want 4 and ok with divide operator. There are the new code which should replace the mentioned lines int sum[4]; for(j=0;j<4;j++) avg=sum[0]+sum[1]+sum[2]+sum[3]; // this part stays the same
The number of values read from sensor is required twice. First, to control the number of iterations of for loop. Second, as the divisor of sum. Introduce a variable (say, N) to capture that. Also, the division by shifting does not sound right, because that restricts the number of readings from the sensor to power of two. enum { N = 4 }; sum = 0; for( j = 0; j < N; j++) { i = ReadSensor(); // function that keeps saving sensor values as int i sum += i; } avg = sum / N; printf( "Sonar average: %d\n", avg );