数字出现在数组中的次数

时间:2013-08-31 07:20:11

标签: c++ algorithm recursion

我在C ++书中找到了一个练习,上面写着“编写一个函数来计算一个数字出现在数组中的次数。”一切都很好,该计划正在运作。但是练习也说该函数应该是递归的。

如何使递归函数像这样工作?

#include <iostream>

int count(int number, int array[], int length)
{
    int counter = 0; 
    for(int i = 0; i < length; i++)
        if(array[i] == number)
            counter++;
    return counter;
}

int main()
{
    int numbers[10] = {3,4,1,2,4,5,6,5,4,5};
    int number_to_search = 5;
    std::cout << number_to_search << " appears "
              << count(number_to_search, numbers, 10)
              << " times in the array.";
    return 0;
}

7 个答案:

答案 0 :(得分:4)

使用此count功能:

int count(int number, int array[], int length) {
    if (length == 0) return 0;
    return (number == *array) + count(number, array+1, length-1);
}

答案 1 :(得分:3)

取代您现在拥有的循环和计数器,返回0 + recursive_step1 + recursive_step,其中recursive_step是对count(...)的调用,您已增加数组指针并减少length。您的基本情况length == 0时间,此时您只需返回0

理解递归的一个很好的方法是逐步研究如何进行计算。在您的示例中,您将执行以下操作:

count(5, {3,4,1,2,4,5,6,5,4,5})
0+count(5, {4,1,2,4,5,6,5,4,5})
0+0+count(5, {1,2,4,5,6,5,4,5})
0+0+0+count(5, {2,4,5,6,5,4,5})
0+0+0+0+count(5, {4,5,6,5,4,5})
0+0+0+0+0+count(5, {5,6,5,4,5})
0+0+0+0+0+1+count(5, {6,5,4,5})
0+0+0+0+0+1+0+count(5, {5,4,5})
0+0+0+0+0+1+0+1+count(5, {4,5})
0+0+0+0+0+1+0+1+0+count(5, {5})
0+0+0+0+0+1+0+1+0+1+count(5,{})
0+0+0+0+0+1+0+1+0+1+0  <---The last 0 is the base case
3

如果允许您更改功能规范,您还可以执行一些名为尾递归的酷炫功能。而不是return 1 + count(...),将积累的数字添加到一个参数计数器来计算:int count(int number, int array[], int length, int acc)

return count(..., acc+1)return count(..., acc+0)。然后,一些编译器能够进行尾调用优化,将其转换为编译代码中的循环。与常规递归相比,这节省了内存。

答案 2 :(得分:2)

如何尝试这样: -

int count(int num, int* arr, int length) {
    if (!length)
        return 0;
    int c = count(num, arr+1, length-1);
    return arr[0] == num? c + 1: c;
}

int main(void) {
int arr[10] = {3,4,1,2,4,5,6,5,4,5};

std::cout << count(2, arr, 10);

return 0;
}

答案 3 :(得分:1)

这是你做的事情(我不会向你展示任何代码以避免破坏你的锻炼)。

首先,请记住,为了递归,您的函数需要调用自身。接下来,请考虑以下两点:

  • length参数等于零时,count(...)的返回值必须为零
  • length参数不为零时,请考虑count(...)array + 1的{​​{1}}的返回值;我们称之为length-1。如果prior等于count(...),则当前prior+1的返回值将等于array[0];如果number不等,则返回prior等于array[0]

当您从此描述中创建代码时,请观察递归函数开头的number。这个if将您的代码拆分为基本案例(if)和递归步骤(基于递归调用计算结果)。这是递归函数的常见结构:每次编写递归代码时都必须重现此结构。

答案 4 :(得分:1)

#include <iostream>

void count(int number, int array[], int length, int &occurence)
{
    if (*array == number) ++occurence;  

    if (length == 1)
        return;
    else    
        count(number, array+1, length-1, occurence);
}

int main()
{
    int numbers[10] = {3,4,1,2,4,5,6,5,4,5};
    int number_to_search = 5;
    int occurence = 0;
    count(number_to_search, numbers, 10,occurence);
    std::cout << number_to_search << " appears "
              << occurence
              << " times in the array.";
}

答案 5 :(得分:0)

 #include <iostream>
 #include <ctime>
 #include <cstdlib>
 using namespace std;
 int i, j,n,c=0, k=0;
 int a[1000], b[1000];
 class Array {


    public:
        void input ()
        {
            cout<<"Enter how many values: ";
            cin>>n;
        }

        void arraySeries ()
        {
            cout<<"Array elements: ";
            srand(time(0));
            for (i=0; i<n; i++)
            {
                a[i]=rand()%100+1;
                cout<<a[i]<<" ";

            }
            cout<<endl<<endl;
            cout<<"Odd elements of array: ";
            for (i=0; i<n; i++)
            {   
                if(a[i]%2==1)
                {
                    b[i]=a[i];
                    k++;
                    cout<<b[i]<<" ";
                }

            }
        }
        // i want to find out how many times an odd number is found in b[i]
        // but i am not being able to do so. SOMEONE PLEASE HELP!!
        void OddSearch ()
        {
            cout<<endl<<endl;
            for (int k=1;k<100;k++)
            {
                c=0;
                for (i=0;i<n; i++)
                {

                    if (b[i]==k)
                    {
                        c++;
                    }
                    cout<<b[i]<<"occurs"<<c<<"times"<<endl;
                }
            }
        }
 };

 int main ()
 {
    Array obj;
    obj.input();
    obj.arraySeries();
    obj.OddSearch();

    return 0;
 }

答案 6 :(得分:0)

#include <stdio.h>

int count(int number,int array[],int size){
   int counter=0;
   if(size == 0) return 0;
   if(array[0] == number){
      counter++;
      return counter+count(number,array+1,size-1);
   }    
   return count(number,array+1,size-1);    
 }

int main() {
 
  int array[] = {1,2,2,4,4,8,7,3,4};
  int size = sizeof(array)/sizeof(int);

  printf("%d",count(2,array,size));

  return 0;    
}