Matrix in C without arrays [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hello my coding teacher give us this exercise:
"Write a C program that, considering two values row and col (both int) chosen by the user, prints a matrix composed by row rows and col columns in which the first element is 1 and every next element is the previous one incremented by one."
I know that a matrix can be composed with arrays but we haven't study them yet so I have to make that only using basic C functions. How can I do?

It is true that, arrays can be used to store matrices like data in memory.
In your case, yout don't have to store anything. The problem is only about displaying matrix.
Please try to implement following steps in C.
Initialize counter to 1
For i = 1 to row
For j = 1 to col
Display counter
Increment counter
Put a line break
That's all.

Try this on a bit of paper.
Choose rows, say 2, and columns say 3.
You need a current value, starting at 1.
Write this down
1
Now move a bit and write the next value
1 2
Same again
1 2 3
... keep an eye on how many numbers you have printed out... We're at the 3 columns now.
So, print a new line '\n' and continue
1 2 3
4
This might end up being a bit wonky if the numbers get big, but you need a current_value starting at 1, and a loop, over rows and columns.
You can walk over the numbers and print as you go, rather than storing them.
int current_value = 1;
for(int row=0; row < rows; ++row)
{
for(int column = 0; column < columns; ++column)
{
printf("%i ", current_value++);
}
printf("\n");
}

Allocate memory for the matrix elements using malloc(). You'll need columns * rows * element size bytes.
malloc() will return you a pointer to the memory.
Use pointer arithmetic to access the elements.

Related

Reproduce values from an original array after substitution of each element with the mean value of its neighbours in C [closed]

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 2 years ago.
Improve this question
I have substituted the values in an array with the values of the arithmetic mean of its neighbours in C:
int main(void) {
int tab[5] = {1,2,4,6,8};
for (int i = 1; i<4; i++) {
tab[i] = (tab[i-1]+tab[i+1])/2;
}
return 0;
}
I have excluded the first and the last element. Then, I want to reproduce the orginal values in the modified array. I have tried:
for (int i = 3; i>=1; i--) {
tab[i-1] = 2*tab[i] - tab[i+1];
}
but it doesn't work. How to reproduce the original values? I want to modify the original list in order to avoid the memory usage for initialization of the new array.
You can't do that IN THIS CASE.
Also there are hidden mistake in your code (explained at bottom)
look at the modified array in your case
arr[0] = 1 //unmodified in loop
arr[1] = 2 //(5/2 = 2) in int data type
arr[2] = 4 //(arr[1]+6)/2 = (2+6)/2 = 4
arr[3] = 6 //(arr[2]+8)/2 = (4+8)/2 = 6
arr[4] = 8 //unmodified
since, its a specific case where the modified array is same, so some of the mistakes would be hidden.
but what happens when your second loop has i=1
arr[i-1]=2*arr[i] - arr[i+1]
arr[0]=2*arr[1] - arr[2]
taking values from above
arr[0] = 0 // which is different from original arr[0]
If you want to just examine this use float instead of int as data type of array and see what happens.
also try putting an even value in the first element while using the int data type.
Now, the mistakes
you said you want to replace elements with avg of their neighbours. but (not in this special case where original elements are retained) what happens is the loop works correctly only 1st time and from 2nd run it is taking a value tab[i-1] which you modified in the previous loop run.
same is the case of your second de-modification loop, from 2nd run onwards, it takes a value tab[i+1] that you modified in previous run.
even if everything else works,
do you realize that in second loop, you are assigning original values from 2nd to 0th positions instead of their original 3rd to 1st.

Find Three Identical Numbers in an Array in C with Nested Loops [closed]

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 4 years ago.
Improve this question
I am trying to create an application in C that finds three similar elements in an array. For example, 1 2 3 4 3 5 3 and three is repeated three times using nested for loops.
You need to be more clear about your question...
This code will help you if you want to find only the first triple.
And I will refer to the above writers, if this is your HW, its only hurts you.
int findrpt(int* arr,int len){
int cnt = 0;
int i = 0, j = 0;
for(i = 0; i < len; i++)
{
cnt = 0;
for(j = i; j < len - i; j++)
if(arr[j] == arr[i])
cnt++;
if(cnt >= 3)
return arr[i];
}
}
Why use nested loops? its basically O(n^3) time. Basically just sort the array in time O(nlogn) and find the element using single for loop. Benefit of sorting. In case you want to find all triples only then a single loop is required but if you want to check if some specific element is occurs three times, just apply binary search.
If the input elements are restricted to a smaller range like [1,100], you can use a counter array of length 1000 initialized as counter[[i]] = 0 . Now just run a single loop and increment the counter as:
for(i = 0 to length of input_array - 1)
{
counter[input_array[i]]++;
}
if(counter[i] == 3)
input_array[i] is a triplet
In this case you wont even require sorting. Cause the array counter will have the count of each element.
If you want to go nested loops, you can make three nested loops, initialized from 0 to 2 elements of the array and check the condition.
There are other easy ways too.
sort the array and check the condition
Count elements

Optimising this small function which will run a huge number of times in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Here is the worst case scenario for each part of the function:
The while loop runs 53,402 times when size is equal to 9.
This means that each call of find_square() calls find_square() itself 53,402 times, until row == size, which in this case is 9.
So the total number of calls to find_square() is thus (53,402) ^ 10 =
188 quattuordecillion.
This isn't even the entirety of the final function, but if it's this slow already, I'm wanting to fix that first. Obviously this is a ludicrous amount of calls, but I can't really see a way around it. I'm open to any ideas, and any help here would be great, thank you!
void find_square(char*** hashed_dict, char*** grouped_dict, char** square, int size, int row) {
if (row == size) {
return;
}
int i = 0;
while (grouped_dict[size - 1][i] != NULL) {
fill_row(square, row, size, grouped_dict[size - 1][i]);
find_square(hashed_dict, grouped_dict, square, size, row + 1);
i++;
}
}
void fill_row(char** square, int row, int size, char* word) {
for (int i = 0; i < size; i++) {
square[row][i] = word[i];
}
}
Your comment about creating “word squares” implies you want to print or otherwise report 9⨉9 squares in which each row and column is a word in grouped_dict. In this case, you ought to at least return from find_square when the characters filled so far contain a partial row or column that is impossible to complete with a word.
One approach is to add code in find_square after the call to fill_row that checks the columns. After fill_row, each column is at least partially filled. For each column, check that there is at least one word in grouped_dict that matches the column so far. If there is not, return from find_square without attempting to fill any more.
This will speed up your program tremendously, but other optimizations may be possible. Things you should consider include:
Sort grouped_dict so that search for matches in it is fast.
Index grouped_dict in sophisticated ways to search for matches even faster.
Alternately filling rows and columns to attempt to increase conflicts that may reveal impossible-to-complete states sooner.
Use the partial matches found by examining grouped_dict to limit the possibilities attempted when filling the next row or column.
Focus on infrequent letters in grouped_dict as key points.

Using one array print frequency of elements in array? [closed]

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 8 years ago.
Improve this question
Write an algorithm called occurrences that, given an array of numbers A, prints all the distinct values in A each followed by its number of occurrences.
For example, if A = <28, 1, 0, 1, 0, 3, 4, 0, 0, 3>, the algorithm should output the following five lines (here separated by a semicolon 28 1; 1 2; 0 4; 3 2; 4 1.
The algorithm may modify the content of A, but may not use any other memory.
Each distinct value must be printed exactly once.
Values may be printed in any order.
Possible solution will have 2 steps:
Sort your array
Iterate on array storing current value and number of its occurrences and printing current value/count pair when current value changes
This solution does not require extra memory and has complexity O(n*log(n)) as sorting is the "heaviest" part of algorithm

Reading, Processing & Outputting numbers from files in C [closed]

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 8 years ago.
Improve this question
Before I go on a mission to write some code, I was hoping someone could confirm the following is possible (or at least fairly simple) to do.
I am wanting to read a file containing numbers that are in 9 columns (separated by a single space) and many rows. The second column is ordered numerically, from largest to smaller. I want to discard all rows that contain below a specified number in this second column and then generate a new file and output just the top rows that conform to this rule.
Additionally, I would like to add a 10th column that is the result of a calculation between 2 other columns.
Is this done using arrays?
Many thanks in advance.
This is trivial in awk. Suppose $N is a shell variable that contains the minimum value you want from the second column, and you want to make column 10 the sum of columns 3 and 5:
awk '$2 > '$N'{ $10 = $3 + $5 }1' input-file
This outputs all of the rows. Pipe the output to head to reduce the number of lines output, or add a counter in the awk script. If you write C code to do this, you are wasting your time unless it is an exercise to help learn C.
On the other hand, it's pretty straightforward in C. For simplicity, assume you only have 2 columns:
int c[2];
do {
rc = scanf( "%d %d", c, c + 1 );
if( c[1] > N && rc == 2 )
printf( "%d %d %d", c[0], c[1], c[0] + c[1] );
} while( rc > 0 );
The most strait-forward approach is probably to convert each column within the file into an array, then manipulate it as you describe from there.
Keep in mind, the file stores characters not integers, make sure you allocate your arrays accordingly to what you desire to store.
You may also find this question discussing the conversion of characters to integers useful.

Resources