2017-05-28 37 views
-2

我应该从现有数组中取出新数组(例如1 0 4 5 4 3 1),以便新数组包含已存在于现有数组中的数字及其出现次数。因此,新的看起来像这样:1 2 0 1 4 2 5 1 3 1(1出现2次,0出现1次... 3出现1次;它们出现在第一个数组中的次序应该也保存在新的一个);我知道如何计数。一个值出现在数组中的时间,但是我如何插入no.of外观? (C语言)如何通过计算值的出现次数并将其打印在该值旁边来创建新数组?

#include <stdio.h> 
    #define max 100 
    int main() { 


int b, n, s, i, a[max], j, k; 

printf("Enter the number of array elements:\n"); 
scanf("%d", &n); 

if ((n > max) || (n <= 0)) exit(); 

printf("Enter the array:\n"); 
for (i = 0; i < n; i++) 
    scanf("%d", a[i]); 

for (i = 0; i < n; i++) { 
    for (j = i + 1; j < n;) { 
      if (a[j] == a[i]) { 
       for (k = j; k < n; k++) { 
        a[k] = a[k + 1]; 
}}}} 

    //in the last 5 rows i've tried to compare elements, and if they are same, to increment the counter, and I've stopped here since I realised I don't know how to do that for every digit/integer that appears in array// 
+6

你尝试过这么远吗? – InternetAussie

+3

由于您没有向我们展示您的进展,我将从顶部开始。按下电源按钮打开电脑... – DeiDei

+0

让我们来看看。 “新阵列”需要是原始长度的两倍。每个奇数元素将保持一个等于原始元素的值。每个偶数元素将包含元素之前的值出现在原始数组中的次数。根据该描述生成算法应该是微不足道的。但有很多方法可以做到这一点。 – Peter

回答

0

如果知道,现有的阵列由0到9之间的数字,则可以使用该阵列的索引,以指示您的值递增。

int in[12] = {1,5,2,5,6,5,3,2,1,5,6,3}; 
int out[10] = {0,0,0,0,0,0,0,0,0,0}; 

for (int i = 0; i < 12; ++i) 
{ 
    ++out[ in[i] ]; 
} 
+0

可以有整数,不仅有0-9个数字,而且数组最多可以有100个数字。另外,用户必须输入数组,所以基本上我们有n(n> 0,n <100)数组元素,但必须通过循环访问它们。 :| – Tanya

+0

在这种情况下,你正在寻找的是一个“地图”。这是一组键值对,其中键是整数,值是该整数的频率。 – Stewart

+1

我认为这正是我需要的! – Tanya

0

如果你提供任何代码片段,它的社区很容易为你提供帮助。
试试这个,即使你优化节数环:)

#include <stdio.h> 

void func(int in[], int in_length, int *out[], int *out_length) {   
    int temp[10] = {0}, i = 0, j = 0, value; 
    //scan the input 
    for(i=0; i< in_length; ++i) { 
     value = in[i]; 
     if(value >= 0 && value <= 9) { //hope all the values are single digits 
      temp[value]++; 
     } 
    } 

    // Find no.of unique digits 
    int unique_digits = 0; 
    for(i = 0; i < 10; ++i) { 
     if(temp[i] > 0) 
      unique_digits++; 
    } 
    // Allocate memory for output 
    *out_length = 2 * unique_digits ; 
    printf("digits: %d out_length: %d \n",unique_digits, *out_length); 

    *out = malloc(2 * unique_digits * sizeof(int)); 
    //Fill the output 
    for(i = 0, j = 0; i<in_length && j < *out_length; ++i) { 
     //printf("\n i:%d, j:%d val:%d cout:%d ", i, j, in[i], temp[in[i]]); 
     if(temp[in[i]] > 0) { 
      (*out)[j] = in[i]; 
      (*out)[j+1] = temp[in[i]]; 
      temp[in[i]] = 0; //Reset the occurrences of this digit, as we already pushed this digit into output 
      j += 2; 
     } 
    } 
} 

int main(void) { 
    int input[100] = {1, 0, 4, 5, 4, 3, 1}; 
    int *output = NULL, output_length = 0, i = 0; 

    func(input, 7, &output, &output_length); 

    for(i=0; i < output_length; i+=2) { 
     printf("\n %d : %d ", output[i], output[i+1]); 
    } 
    return 0; 
} 
+0

我试图添加代码,只是第二个:) – Tanya

+0

嗯,你现在提供了代码:'(,首先试试这个,如果它的工作,然后添加你的输入提示这里,而不是我的固定输入数组。 – Ajay

+0

好的,我将 (是的,因为我没有看到你的答案发布之前,抱歉) – Tanya

相关问题