fork() to search through a 3D array C programming [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 6 years ago.
Improve this question
I just learned about fork on the web, I understand the main principle with the child and parent processes but I am still a little bit confused on how we can use fork to search faster through a 3D array. Can anyone give a quick coded example to show how it works ?
Thanks

Fork can make things run faster by allowing the calculations to be split up amongst the processors. Here's example code using a flat array (it's easier to get the concept across with a flat array instead of 3d array):
int main() {
int i;
int array[] = {0,1,2,3,4,5,6,7,8,9,10};
int findThisNumber = 8;
int pid = fork(); //split into two processes
//the parent return the childs pid
//and the child returns 0
if(pid == 0) { //this is the child
for(i = 0; i < 5; i++) { //scan the first half of the array
if(array[i] == findThisNumber) {
printf("%d found at index %d\n", findThisNumber, i);
}
}
} else { //this is the parent
for(i = 6; i < 10; i++) { //scan the second half
if(array[i] == findThisNumber) {
printf("%d found at index %d\n", findThisNumber, i);
}
}
}
}
In this example, the program splits into two processes and each process searches half of the array. I ran a the same program with 1000000000 elements in the array and these are the times:
time ./noFork.exe
real 0m0.796s
time ./a.exe
real 0m0.391s
I hope that helps, if I can clear anything else up let me know.

I recommend you to check out posix threads. The difference is that threads work in the same process so they share address space (imo it is faster and easier to exchange data between threads then between processes). To search faster you should divide N dimensional array to X groups(smaller arrays - one for each thread/process) and pass each group of N dimensional data to particular thread(pthread)/process(fork).

Related

Undestanding for loop in pipe creation 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 3 years ago.
Improve this question
I have a comprension question about this code that I am currently studying: this function is used in a C Shell implementation to execute piped commands. I can't understand how the person who wrote it got to know how many pipes to close (why is the limit 2*com- 2)?
for(i = 0; i < 2*com - 2; i++) close(pip[i]);
for(i = 0; i < com; ++i) {
waitpid(pid, &status, WUNTRACED);
In this program, num_pipe is not actually the number of pipes
but the number of commands (very bad name indeed!).
Between two commands you need one pipe, between three commands
you need two pipes ... between N commands you need N-1 pipes.
Each pipe relies on two file descriptors (one for reading, one
for writing) thus 2*(num_pipe-1) file descriptors are needed
for num_pipe commands.
note: the malloc() does not allocate an array of integer pointers
(as stated in the question) but an array of integers.
Following this logic, I would have written
for(i = 0; i < 2*(num_pipe-1); i += 2)
but 2*(num_pipe-1) equals to 2*num_pipe-2 and since the step
is 2, the loop condition is the same with the limit
2*num_pipe-3.
It's just terribly confusing in my opinion.

Program won't exit for first for loop and I have no idea why [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The program is supposed to find amicable pairs. The first input tells you how many numbers will follow and the program is supposed to figure out which of those numbers are amicable pairs. I don't know if the program is actually able to do that though, since I can't even get past the first for loop, which is literally just putting the elements that need to be checked into an array.
int main(int argc, char *argv[]) {
int numberOfNumbers, num;
scanf("%d", &numberOfNumbers);
int numbers[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
scanf("%d", &num);
numbers[i] = num;
}
I expect the program to move onto the calculation part of the code (which I didn't include) and produce some output, whether it's right or not, but instead after I've entered the last number it just acts as if it wants another input. At that point I could enter every digit of Graham's number and it still won't exit.
The first step of debugging a problem is validating you have the problem you're considering fixing.
for (int i = 0; i < numberOfNumbers; i++) {
scanf("%d", &num);
numbers[i] = num;
}
Is the loop that you are thinking of fixing.
printf("entering loop\n");
for (int i = 0; i < numberOfNumbers; i++) {
printf("i is %d, numberOfNumbers is %d\n", i, numberOfNumbers);
scanf("%d", &num);
numbers[i] = num;
}
printf("loop finished\n");
is the code you would would need to completely validate that your guess about the loop is correct (or wrong).
I hope this helps, even if it is not a direct answer. Your code looks good, but could be wrong based on a lot of items (including the user input).

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

Variable Number of for loops with code in between [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 6 years ago.
Improve this question
So the problem I have is that I want to implement N for loops in the following way (where N is a variable):
for i0=0:MAX
cOR[0] = initial + move[i0];
for i1=0:MAX
cOR[1] = cOR[0] + move[i1];
....
some other stuff inside the final loop
(cOR is a vector of length equal to the number of for loops)
So I found this solution that works when you just have the nested loops (https://stackoverflow.com/a/20577981/3932908) but have been struggling to modify it for my particular case which requires code in between the for loops. Is there a simple way to implement this or is a different approach needed?
The general approach is to
Write a recursive function.
If recursion is not for some reason appropriate for your code (e.g. very long recursion depth, or the ability to suspend the execution is required), then convert the recursive version to an iterative one by explicitly modeling the stack.
Doing №1 is easy:
void f(int depth, int initial, int *cOR)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
return;
}
for(int i = 0; i < MAX; ++i)
{
cOR[depth] = initial + move[i];
f(depth+1, cOR[depth]);
}
}
And call it like so:
f(0, initial, cOR);
Now we head to №2, i.e. converting to a non-recursive version. The extra state we need is what was stored on the stack before: the values of the i variables. So here we go:
int i[max_depth];
int depth = 0;
for(;;)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
do {
if(--depth < 0)
return;
} while(++i[depth] >= MAX);
}
else
i[depth] = 0;
cOR[depth] = (depth > 0 ? cOR[depth-1] : initial) + move[i[depth]];
++depth;
}
If you can't estimate max_depth a priori then you can switch to a dynamically allocated array that grows as you need.

What is the complexity of the following simple program? [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 6 years ago.
Improve this question
I am having trouble finding understanding complexity. Could someone help me understand what the complexity of the code below is and why.
for (int i = 1; i < n; i++) { // (n is a number chosen by the user)
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
An explanation would be great.
Assuming i starts at 0, the complexity would be constant. The complexity is always expressed relative to a variable defining the number of executions, which is not the case here.
If one term should be used to describe this behavior, it is "constant". There will be a number of executions, but this number will never change
Original Question: Because i's initial value is undefined, the behavior of the code is unpredictable. There is no way to usefully answer the question other than that the complexity is undefined. There is no way to know how many operations the code will perform.
Updated Question: It's O(1). The code will always do precisely the same amount of work.
You can compute the time complexity of this code fragment by evaluating the number of operations, namely the number of calls to printf() which for simplicity's sake we shall assume to be equivalent:
Assuming i starts at 1 (you initially forgot to initialize it), the outer loop runs 99 times, for each iteration, the inner loop runs i times. Gauss was supposedly 9 years old when he computed the resulting number of iterations to be 99 * (99 + 1) / 2.
The complexity of the original piece of code was O(1) since it did not depend on any variable, but since instead you updated the code as:
void fun(int n) {
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
}
The time complexity would come out as O(n2).

Resources