Block Game
December 2016 Bronze - Problem 2: blocks
Algorithm
For each board, we find the maximum number of times that each letter is used and add them to the total.
Python
def run(pairs):
# For every pair of words, we find the maximum frequency of each letter.
maxFrequencies = [0]*26 # Each item is one letter
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for pair in pairs:
for i in range(26):
letter = alphabet[i]
maxFrequencies[i] += max(pair[0].count(letter),pair[1].count(letter))
return maxFrequencies
def main():
with open('blocks.in','r') as fIn:
pairs = list(map(lambda i:i.split(),fIn.read().split('\n')[1:-1]))
print(pairs)
maxFrequencies = run(pairs)
with open('blocks.out','w') as fOut:
fOut.write('\n'.join(map(str,maxFrequencies))+'\n')
main()
C++
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
void run(vector<vector<string>> & pairs, vector<int> & maxFreq){
string alphabet("abcdefghijklmnopqrstuvwxyz");
vector<string> pair;
for (int j=0; j<pairs.size(); ++j){
pair = pairs[j];
for (int i=0; i<26; ++i){
char letter = alphabet.at(i);
maxFreq[i] += max(
count(pair[0].begin(),pair[0].end(),letter),
count(pair[1].begin(),pair[1].end(),letter)
);
}
}
}
int main(){
vector<vector<string>> pairs;
ifstream fIn;
fIn.open("blocks.in");
int n;
string pair0; string pair1;
fIn >> n;
for (int i=0; i<n; ++i){
fIn >> pair0;
fIn >> pair1;
vector<string> pair;
pair.push_back(pair0);
pair.push_back(pair1);
pairs.push_back(pair);
}
vector<int> maxFreq(26,0);
run(pairs, maxFreq);
ofstream fOut;
fOut.open("blocks.out");
for (int i:maxFreq){
fOut << i << endl;
}
fIn.close();
fOut.close();
return 0;
}