在 C 中构造数组补集的惯用方法
我正在编写一个函数,它传递一个指向长度为 4 的数组的指针。该数组将包含整数 0 <= x <= 52
并且我想构造一个长度为 48 的数组与 da kine 中不在传入数组中的每个整数一起。在Python中,这在C中是
# just included for specificity
cards = [card for card in deck if card not in hand]
最好的,我能做的就是
int i, j, k, found_flag;
int cards[48]; /* int hand[4] is passed in */
k = 0;
for (i = 0; i < 52; i++) {
found_flag = 0;
for (j = 0; j < 4; j++) {
if (i == hand[j]) {
found_flag = 1;
break;
}
}
if (!found_flag) {
cards[k++] = i;
}
}
这对于这种情况来说是最佳的吗?一般来说,是“首选”模式吗?
I'm writing a function that gets passed a pointer to an array of length 4. This array will contain integers 0 <= x <= 52
and I would like to construct an array of length 48 with every integer from da kine that's not in the passed in array. In python this would be
# just included for specificity
cards = [card for card in deck if card not in hand]
in C the best I can do is
int i, j, k, found_flag;
int cards[48]; /* int hand[4] is passed in */
k = 0;
for (i = 0; i < 52; i++) {
found_flag = 0;
for (j = 0; j < 4; j++) {
if (i == hand[j]) {
found_flag = 1;
break;
}
}
if (!found_flag) {
cards[k++] = i;
}
}
Is this optimal for this circumstance? Generally, is the 'go-to' pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然,你的例子对于只有 4 手的大小来说是很好的——它足够清楚了。在数组更大的情况下,可以使用基于各种排序的更有效的算法。
例如,基数排序消除了嵌套循环:
Sure, your example is fine for a hand size of only 4 - it's clear enough. In situations where the arrays were much larger, then more efficient algorithms based on various kinds of sorting could be used.
For example, a radix sort eliminates the nested loops:
可以这样吗?
cards_in_deck 是一个数组,对于不在牌组中的卡片,其值为 1。这是您要找的吗?
Could this be done this way?
The cards_in_deck is an array with value of 1 for those that are not in the deck. Is this what you are looking for ?
这是我为解决这个问题而编写的小测试程序。它创建一个集合来显示选择了哪些卡片,并扫描该集合以构建剩余卡片的数组。
Here's the little test program I put together to solve this one. It creates a set to show which cards are selected and scans through the set to build the array of the cards that are left.
在 C 中,迭代手中已排序的卡片:
在 python 中,代码如下所示:
In C, iterate over the sorted cards in hand:
In python the code looks like this: