04

算法的思想来自与和同事的一次聊天,做了改进,使得精度可以通过参数控制。

Frequence.h

#pragma once
 
class Frequence 
{
  public:
	Frequence( int precision = 10 );
	~Frequence( );
 
	int Check( );
 
  private:
	int		_precision;
	int 	_slot_num;
 
	struct stSlot
	{
		int count;
		int time;
	};
 
	stSlot *_slot;
 
	inline int calculate( int now );
 
	inline int get_current_slot_num( int now );
};

Frequence.cpp

#include "Frequence.h"
 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
 
static const int kMinute = 60;
 
Frequence :: Frequence( int precision )
	:	_precision( precision )
{
	if( _precision > 60 ) _precision = 10;
	if( _precision <= 0 ) _precision = 10;
 
	_slot_num = kMinute / _precision + 1;
	_slot = ( stSlot * )calloc( _slot_num, sizeof( stSlot ) );
}
 
Frequence :: ~Frequence( )
{
	free( _slot );
}
 
int Frequence :: Check( )
{
	int now = time( NULL );
	int current_slot_num = get_current_slot_num( now );
	stSlot *current_slot = _slot + current_slot_num;
 
	int diff = now - current_slot->time;
	if( diff > kMinute )
	{
		current_slot->count = 1;
	}
	else
	{
		current_slot->count++;
	}
 
	current_slot->time = now;
 
	return calculate( now );
}
 
int Frequence :: calculate( int now )
{
	int current_slot_num = get_current_slot_num( now );
	stSlot *last_slot = NULL;
 
	int total = 0;	
	int index = 0;
	while( index < _slot_num - 1 )
	{
		int last_slot_num = ( _slot_num + current_slot_num - index ) % _slot_num;
		last_slot = _slot + last_slot_num;
		int diff = now - last_slot->time;
		if( diff > kMinute )
		{
			last_slot->count = 0;
		}
 
		total += last_slot->count;
		index++;
	}
	return total;
}
 
int Frequence :: get_current_slot_num( int now )
{
	return ( now % ( _slot_num * _precision ) ) / _precision;
}
25

闲来没事,睡觉前写了这个程序。

#include <cctype>
#include <string>
#include <iostream>
 
using namespace std;
 
void ToOtherCase(char &c) 
{
    if( isupper(c) )
        c = tolower(c); 
    else
        c = toupper(c);
}
 
void AllCase(string &sInput, int iIndex)
{
    if( iIndex == sInput.size() )   
    {   
        cout << sInput << endl;
        return;
    }   
 
    AllCase(sInput, iIndex + 1); 
 
    if( !isalpha(sInput[iIndex]) )
        return;
 
    ToOtherCase(sInput[iIndex]);
    AllCase(sInput, iIndex + 1); 
}
 
int main(int c, char **v)
{
    if( c != 2 ) 
    {   
        cout << "Usage: " << v[0] << " word" << endl;
        return 0;
    }   
    string sInput = v[1];
    AllCase(sInput, 0);
    return 0;
}

ps, 为什么我的网站这么慢?

Tagged with:
preload preload preload

无觅相关文章插件,快速提升流量