Skip to content

Instantly share code, notes, and snippets.

@agam
Created November 20, 2013 02:56
Show Gist options
  • Select an option

  • Save agam/7556916 to your computer and use it in GitHub Desktop.

Select an option

Save agam/7556916 to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
using namespace std;
void cin_discard_newline() {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
uint16_t fletcher_checksum(const string& word) {
uint8_t count0 = 0, count1 = 0;
for (int i = 0; i < word.size(); ++i) {
unsigned char c = word[i];
count0 = (count0 + c) % 255;
count1 = (count1 + count0) % 255;
}
return (count1 << 8) | count0;
}
int main() {
// Read in number of lines
int num_lines;
cin >> num_lines;
cin_discard_newline();
cout << hex;
vector<string> lines;
for (int i = 0; i < num_lines; ++i) {
string line;
getline(cin, line);
lines.push_back(line);
}
for (int i = 0; i < num_lines; ++i) {
cout << i + 1 << " " << fletcher_checksum(lines[i]) << endl;
}
}
/*
* http://www.reddit.com/r/dailyprogrammer/comments/1qwkdz/111113_challenge_141_easy_checksums/
*
* Formal Inputs & Outputs
* Input Description
* On standard console input, you will first be given an integer N which ranges
* inclusively from 1 to 256. After this line, you will receive N-lines of ASCII
* text. This text will only contain regular printable characters, and will all
* be on a single line of input.
* Output Description
* For each line of input, print the index (starting from 1) and the 16-bit
* Fletcher's checksum as a 4-digit hexadecimal number.
* Sample Inputs & Outputs
* Sample Input
* 3
* Fletcher
* Sally sells seashells by the seashore.
* Les chaussettes de l'archi-duchesse, sont-elles seches ou archi-seches ?
* Sample Output
* 1 D330
* 2 D23E
* 3 404D
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment