【发布时间】:2017-11-20 16:37:56
【问题描述】:
我试图表示 N 个给定正整数的排列。
例如。表示数字 1-16 的任意排列,每个数字使用 4 位或更少位.
这个想法是我们可以用 8*4 + 4*3 + 2*2 + 1*1 = 49 位而不是 64 位来表示 16 的排列。
我有一个示例数据集如下 [10 1 3 11 2 12 8 7 4 6 9 13 15 16 5 14]。
我尝试了以下 c 程序来实现这一点,但我不确定如何在 C 程序中使用向量来存储给定整数的位置。
我有这个问题:
如果整数范围为 1-16,那么在我需要进一步计算时将存储在位置 [0] 中的内容。
以下是我用过的一段代码:
void main()
{
int position[16];// a vector
int buffer[16] = {10, 1,3, 11, 2, 12, 8, 7, 4, 6, 9, 13, 15, 16, 5, 14};
int buffer_copy[16];// copy of original buffer
int i, j;
for (i=0; i<16; i++)
{
buffer_copy[i]=buffer[i];
}
for(i=0; i<16; i++)
{
position[buffer[i]]= i;
printf("\n the position of element %d in position array is: %d",
buffer[i], position[buffer[i]]);
}
int next = 8;
for (i =1; i<16; i++)
{
int pos, q=0;
pos = position[i];
// **To check the number of positions unchecked between 0 and pos.**
for (j=0; j<pos; j++)
{
if(buffer_copy[j]>=0)
{
q=q+1;
}
buffer_copy[pos] =-1;
}
printf("\n the value for Q is :%d", q);
}
}
上面的代码显示了以下输出,我不确定它是否正确。
位置数组中元素10的位置为:0
位置数组中元素 1 的位置为:1
位置数组中元素 3 的位置为:2
位置数组中元素 11 的位置为:3
位置数组中元素 2 的位置为:4
位置数组中元素 12 的位置为:5
位置数组中元素 8 的位置为:6
位置数组中元素 7 的位置为:7
位置数组中元素 4 的位置为:8
位置数组中元素 6 的位置为:9
位置数组中元素 9 的位置为:10
位置数组中元素 13 的位置为:11
位置数组中元素 15 的位置为:12
位置数组中元素 16 的位置为:13
位置数组中元素 5 的位置为:14
位置数组中元素 14 的位置为:15
Q 的值为:1
Q 的值为:3
Q 的值为:1
Q 的值为:5
Q 的值为:10
Q 的值为:5
Q 的值为:4
Q 的值为:3
Q 的值为:3
Q 的值为:0
Q 的值为:1
Q 的值为:1
Q 的值为:1
Q 的值为:3
Q 的值为:1
对于完成此任务的任何帮助或建议,我将不胜感激。
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c compression permutation