• STATISTIQUES
  • Il y a eu un total de 0 membres et 5159 visiteurs sur le site dans les dernières 24h pour un total de 5 159 personnes!
    Membres: 2 609
    Discussions: 3 580
    Messages: 32 820
    Tutoriels: 78
    Téléchargements: 38
    Sites dans l'annuaire: 58


  • ANNUAIRE
  • [FR] µContest
    µContest est un site de challenges de programmation, c'est à dire qu'il propose des épreu...
    Hacking
    [FR] Secuser
    Actualité de la sécurité informatique, fiches virus et hoax, alertes par email, antivirus gratui...
    Hacking
    [EN] This is legal
    Basic: 10, Realistic: 5, Programming: 1, Bonus: 11, SQL: 2, Encryption: 6, Application: 4, User Contributed: 3
    Challenges
    [FR] Forum-Webmaster
    Une communauté webmaster pour apporter / recevoir de l'aide en création de site internet. Webmaster...
    Webmaster
    [EN] Astalavista
    Un site aux ressources incontournable depuis plusieurs années, Astalavista est réellement devenue un cl...
    Hacking
    [FR] Asp-php
    Tutoriaux sur ASP, PHP, ASP.net, XML, SQL, Javascript, HTML, VML - Scripts et ressources pour webmasters - Forums d&#...
    Programmation
    [FR] WeChall
    Audio: 3, Coding: 11, Cracking: 9, Crypto: 18, Encoding: 11, Exploit: 44, Forensics: 1, Fun: 6, HTTP: 6, Image: 8, Java:...
    Challenges

  • DONATION
  • Si vous avez trouvé ce site internet utile, nous vous invitons à nous faire un don du montant de votre choix via Paypal. Ce don servira à financer notre hébergement.

    MERCI!




Note de ce sujet :
  • Moyenne : 0 (0 vote(s))
  • 1
  • 2
  • 3
  • 4
  • 5
[C++] Frequency Analysis
22-09-2011, 22h03 (Modification du message : 19-11-2012, 19h27 par ark.)
Message : #1
Fr3ak Hors ligne
Banni



Messages : 25
Sujets : 4
Points: 1
Inscription : Sep 2011
[C++] Frequency Analysis
Bonjour,

Voici une classe d'analyse fréquentielle de flux.

FrequencyAnalysis.cpp

Code PHP :
#include <algorithm>
#include <stdexcept>

#include "FrequencyAnalysis.h"
#include "PrintPair.hpp"
#include "TotalPair.hpp"

using namespace std;

void FrequencyAnalysis::analyze()
{
    
// Set position of the get pointer
    
m_in.seekg(0ios::beg);
    
    
// Get unformatted data from stream while eofbit is not set
    // and check if character is alphabetic using locale
    
while (not m_in.eof()) {
        
int c(m_in.get());
        
        if (
isalpha(c))
            ++
m_stats[static_cast<char>(c)];
    }
}

FrequencyAnalysis::FrequencyAnalysis(istream &in) : m_in(in), m_stats()
{
    
// Check input stream
    
if (not in)
        throw 
runtime_error("FrequencyAnalysis@FrequencyAnalysis: bad in");
}

statsMap FrequencyAnalysis::stats() const
{
    
// Return statistics
    
return m_stats;
}

ostream &operator<<(ostream &outFrequencyAnalysis const &freqAnalysis)
{
    
// Check output stream
    
if (not out)
        throw 
runtime_error("operator<<: bad out");
    
    
// Accumulate total number of occurrences
    // and print statistics for each pair
    // then return output stream
    
statsMap stats(freqAnalysis.stats());
    
unsigned total(accumulate(stats.begin(), stats.end(), 0TotalPair<charunsigned>()));
    
PrintPair<charunsigned> print(outtotal);
    
for_each(stats.begin(), stats.end(), print);
    return 
out;


FrequencyAnalysis.h

Code PHP :
#ifndef FREQUENCY_ANALYSIS_H
#define FREQUENCY_ANALYSIS_H

#include <iostream>
#include <map>

typedef std::map<charunsignedstatsMap;
typedef statsMap::iterator statsIt;

class 
FrequencyAnalysis
{
    
std::istream &m_in;
    
statsMap m_stats;
    
    public:
        
void analyze();
        
FrequencyAnalysis(std::istream &in);
        
statsMap stats() const;
};

std::ostream &operator<<(std::ostream &outFrequencyAnalysis const &freqAnalysis);

#endif 

main.cpp

Code PHP :
#include <fstream>
#include <stdexcept>
#include "FrequencyAnalysis.h"

using namespace std;

int main(int argcchar **argv)
{
    try {
        
// Check count of arguments
        
if (argc != 2)
            throw 
runtime_error("main: bad argc");
        
        
// Open file
        
ifstream file(argv[1]);
        
        
// Check file
        
if (not file)
            throw 
runtime_error("main: bad file");
        
        
// Analyze file
        
FrequencyAnalysis freqAnalysis(file);
        
freqAnalysis.analyze();
        
cout << "Letter\tCount\t%" << endl << freqAnalysis;
    } catch (
exception const &e) {
        
// Print exception
        
cout << e.what() << endl;
    }


Makefile.sh

Code PHP :
#!/bin/bash

g++ *.cpp -pedantic -Wall -Wextra -Wold-style-cast -Woverloaded-virtual 
-Wfloat-equal -Wwrite-strings -Wpointer-arith -Wcast-qual -Wcast-align 
-Wconversion -Wshadow -Weffc++ -Wredundant-decls -Wdouble-promotion 
-Winit-self -Wswitch-default -Wswitch-enum -Wundef -Wlogical-op -Winline 
-Werror -Wfatal-errors -std=c++0x -O2 -s

sstrip a
.out
upx a
.out 

PrintPair.hpp

Code PHP :
#ifndef PRINT_PAIR_HPP
#define PRINT_PAIR_HPP

template<class T1, class T2>
class 
PrintPair
{
    
std::ostream &m_out;
    
T2 m_total;
    
    public:
        
void operator()(std::pair<T1T2> const &x)
        {
            
// Print pair
            
m_out << x.first << "\t" << x.second << "\t" << 100 x.second m_total << "%" << std::endl;
        }
        
        
PrintPair(std::ostream &outT2 total) : m_out(out), m_total(total)
        {
            
// Check output stream
            
if (not out)
                throw 
std::runtime_error("PrintPair@PrintPair: bad out");
            
            
// Check total
            
if (not total)
                throw 
std::runtime_error("PrintPair@PrintPair: bad total");
        }
};

#endif 

TotalPair.hpp

Code PHP :
#ifndef TOTAL_PAIR_HPP
#define TOTAL_PAIR_HPP

template<class T1, class T2>
class 
TotalPair
{
    public:
        
T2 operator()(T2 xstd::pair<T1T2> const &y)
        {
            
// Return accumulated pair
            
return y.second;
        }
};

#endif 
+1 (0) -1 (0) Répondre
23-09-2011, 03h41
Message : #2
CyberSee Hors ligne
Admin fondateur de N-PN
*******



Messages : 1,721
Sujets : 287
Points: 157
Inscription : Jan 2012
[C++] Frequency Analysis
Bravo Fr3ak! Je vais compiler sa demain et voir ce que sa dit. Merci de ta contribution ;-) Rep+20!
+1 (0) -1 (0) Répondre
24-09-2011, 14h17 (Modification du message : 24-09-2011, 17h14 par Fr3ak.)
Message : #3
Fr3ak Hors ligne
Banni



Messages : 25
Sujets : 4
Points: 1
Inscription : Sep 2011
[C++] Frequency Analysis
Mise à jour

- Code commenté
- Pour chaque fonction, tous les arguments sont vérifiés et lancent une exception en cas d'erreur
- Utilisation de std::istream au lieu de std::ifstream pour pouvoir analyser directement plus de flux entrants (std::cin, std::istringstream...)
- Utilisation d'un foncteur pour le comptage d'occurrences total
- Utilisation d'un foncteur pour l'affichage des résultats
- Ajout d'un pseudo-Makefile en bash pour compiler le projet (les deux dernières lignes sont optionnelles et nécessistent sstrip + upx)
+1 (0) -1 (0) Répondre


Atteindre :


Utilisateur(s) parcourant ce sujet : 1 visiteur(s)
N-PN
Accueil | Challenges | Tutoriels | Téléchargements | Forum | Retourner en haut