Skip to content

Instantly share code, notes, and snippets.

@whimo
Created March 15, 2018 07:41
Show Gist options
  • Select an option

  • Save whimo/c497650003cf7815c7a69dee7f26e07c to your computer and use it in GitHub Desktop.

Select an option

Save whimo/c497650003cf7815c7a69dee7f26e07c to your computer and use it in GitHub Desktop.
Frequency analysis
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
struct elem
{
elem (char c): c (c), count (0), link (nullptr) {};
char c;
unsigned int count;
elem* link;
};
int main ()
{
std::string filename;
std::cin >> filename;
std::ifstream fin (filename);
if (!fin.good ()) return -1;
elem* first = new elem (fin.get ());
first -> count = 1;
while (fin.good ())
{
char ch = fin.get ();
elem* current = first;
for (current = first; current -> c != ch; current = current -> link)
{
if (current -> link == nullptr)
{
elem* next = new elem (ch);
current -> link = next;
}
}
current -> count += 1;
}
for (elem* cnt = first; cnt != nullptr; cnt = cnt -> link)
{
for (elem* current = first; current -> link != nullptr; current = current -> link)
{
if (current -> count < current -> link -> count)
{
char temp_c = current -> c;
unsigned int temp_count = current -> count;
current -> c = current -> link -> c;
current -> count = current -> link -> count;
current -> link -> c = temp_c;
current -> link -> count = temp_count;
}
}
}
for (elem* current = first; current != nullptr; current = current -> link)
std::cout << current -> c << '\t' << (int) (current -> c) << '\t' << current -> count << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment