Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on How do I filter an array in C?

Parent

How do I filter an array in C?

+1
−2

No, I'm not trying to get the full program written completely in C by you guys. I only need some way to implement the functionalities of each function I found confusing.

In this challenge in Code Golf CD, I have to make a program that computes the determinant of a two-dimensional array. It also has a program written in JavaScript that solves the challenge which looks like this:

function laplaceDet(matrix) {
	if (matrix.length === 1) return matrix[0][0];

	let sum = 0;
	for (let rowIndex = 0; rowIndex < matrix.length; ++rowIndex) {
		let minorMatrix = matrix.filter((_, index) => index !== rowIndex)
			          .map(row => row.slice(1));
		sum += ((-1) ** rowIndex) * matrix[rowIndex][0] * laplaceDet(minorMatrix);
	}
	return sum;
}

I want to challenge myself into using C for solving the challenge. First, I'll need to reimplement the program, whereas the golfing part will be dealt with later, although I've already been golfing it. Here's what I got so far.

Why'd I stop? There's a function named filter() and I'm not so sure how to get it implemented, and since C has no maps (at least I think none exist in C), it's also difficult to complete the program without it.

So I'll have to improvise... How? How do I implement the filter() method, maybe without using a function to save bytes, and what's a C equivalent to the line of code matrix.filter((_, index) => index !== rowIndex).map(row => row.slice(1));?

History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

I don't know how you normally approach those things. I usually start with getting something working b... (2 comments)
Post
+3
−1

It looks like filter() effectively takes two arguments; the array to be filtered, and a predicate expression resulting in a boolean indicating whether the entry should be included in the output or not.

(I also note that the implementation in your question appears to be at least O(n^2) time complexity, which is pretty bad for anything but the smallest arrays.)

Beginning at the point of not concerning oneself with source code byte count, the tool in C's toolbox that I would reach for for this is either a specialized function for this one usage, or one that takes a pointer to a function that serves the purpose of the filter predicate. The latter is slightly more complex, but also generic as it can accept any predicate function.

The function pointer syntax in C takes some getting used to.

First, write a function that does whatever filtering you want. (For a real-world application, unless I had some highly specialized need, I would first see if there are already-debugged third-party library implementations of this rather than trying to come up with my own implementation.)

int* filter(int* input, bool (*predicate)(int))
{
    int* output;
    while (*input != -1)
    {
        if(predicate(*input))
        {
            // somehow include *input in the output
        }
        input++;
    }
    return output;
}

Then, write a predicate function which will be called once per entry:

bool my_predicate(int value)
{
    return (value & 3) != 0; // or whatever
}

Then put them together:

int* filtered = filter(unfiltered, my_predicate);

Adding some boilerplate this compiles cleanly with gcc -Wall -std=c99 -pedantic-errors -Wextra -Werror.

Reducing the character count in the source code is kind of what code golfing is about as I understand it, so I will leave that part entirely up to you.

History
Why does this post require moderator attention?
You might want to add some details to your flag.

2 comment threads

Missing and misleading details (2 comments)
Complexity (1 comment)
Missing and misleading details
Derek Elkins‭ wrote over 2 years ago

Other than illustrating function pointers, this answer doesn't seem particularly helpful and doesn't really illustrate good or effective practices while also leaving implicit some pretty crucial information. Starting with your approach, there are two major issues: 1) it seems to assume (without explicitly pointing this out) that arrays will be terminated by -1 values, which is bizarre in this context where -1 is a valid value, is not idiomatic, and is not a good approach for a general purpose function; 2) if you actually tried to use this filter function for the problem you'd find it wasn't usable. Why? The lambda in the JavaScript code closes over a free variable, rowIndex. As such you need a full closure and not just a function pointer to represent it. The way I've typically seen this addressed in C is to pass the environment along with the function pointer leading to a type like: int *filter(int *input, size_t len, bool (*predicate)(void *, int), void *env).

Derek Elkins‭ wrote over 2 years ago · edited over 2 years ago

For this particular example, we could specialize env to an int, i.e. the row index. One thing you don't mention or illustrate but is fairly important is that this function will need to allocate memory. This also makes it not very idiomatic C. So taking output pointer as an input would arguably be a bit better, but arguably a C programmer wouldn't make or use a general purpose function to do this. Of course, for the overall goal of making a determinant function, the best approach would be to not try to blindly copy some JavaScript code, but I do appreciate that the OP asked about filtering arrays.