Posts List

2013년 3월 20일 수요일

Calculate the M-moving average

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <iostream>
using namespace std;
// calculate M-moving average
vector<double> movingAverage1(const vector<double>& A, int M)
{
    vector<double> outVec;
    int n = A.size();
    for (int i=0; i<n; i++)
    {
        int sum = 0;
        int cnt = 0;
        for (int j=i; i-j < M && j >= 0; j--)
        {
            sum += A[j];
            cnt ++;
        }
        if (cnt < M)
        {
            outVec.push_back(A[i]);
        }
        else
        {
            outVec.push_back(sum / cnt);
        }
    }
    return outVec;
}
void main()
{
    srand((unsigned)time(NULL));
    vector<double> A;
    for (int i=0; i<24; i++)
    {
        A.push_back(rand());
    }
    movingAverage1(A, 3);
}

Find the most frequent number in a vector

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
/*
 * desc : Find the most frequent score in score vector
          if there are more than two scores, return any of them
 * in   : score vector scores
 * out  : the most frequent score
 */
int frequentNumber2(const vector<int>& scores)
{
    int score_frequent_arr[100] = {0, };
    int n = scores.size();
    for (int i=0; i<n; i++)
    {
        score_frequent_arr[scores.at(i)]++;
    }
    int max_frequent_number = -1;
    int max_frequent_frequency = -1;
    for (int i=0; i<100; i++)
    {
        if (score_frequent_arr[i] > max_frequent_frequency)
        {
            max_frequent_number = i;
            max_frequent_frequency = score_frequent_arr[i];
        }
    }
    printf("number=(%d), frequent=(%d)\n", max_frequent_number, max_frequent_frequency);
    return max_frequent_number;
}

/*
 * desc : Find the most frequent number in vector
          if there are more than two numbers, return any of them
 * in   : vector A
 * out  : the most frequent number
 */
int frequentNumber1(const vector<int>& A)
{
    int arr[10000][2] = {0, };
    int arr_n = 0;
    int n = A.size();
    for (int i=0; i<n; i++)
    {
        int d = A.at(i);
        int found = 0;
        for (int j=0; j<arr_n; j++)
        {
            if (arr[j][0] == d)
            {
                arr[j][1]++;
                found = 1;
                break;
            }
        }
        if (!found)
        {
            arr[arr_n][0] = d;
            arr[arr_n++][1]++;
        }
    }
    int max_number = 0;
    int max_frequent = -1;
    for (int i=0; i<arr_n; i++)
    {
        if (arr[i][1] > max_frequent)
        {
            max_number = arr[i][0];
            max_frequent = arr[i][1];
        }
    }
    printf("number=(%d), frequent=(%d)\n", max_number, max_frequent);
    return max_number;
}
void main()
{
    vector<int> A ;
    srand((unsigned)time(NULL));
    for (int i=0; i<100; i++)
    {
        A.push_back(rand()%101);
    }
    frequentNumber1(A);
    frequentNumber2(A);
}