ba1b.c3 (1273B) - raw


      1 module ba1b;
      2 
      3 import std::io;
      4 import std::io::file;
      5 import std::collections;
      6 
      7 import util;
      8 
      9 fn int main(String[] args) {
     10 	if (args.len != 2) {
     11 		io::eprintn("Please supply path to data file");
     12 		return 1;
     13 	}
     14 	File f = file::open(args[1], "rb")!!;
     15 	String text = io::treadline(&f)!!;
     16 	String k_str = io::treadline(&f)!!;
     17 	int k = k_str.to_integer(int)!!;
     18 	foreach(word: frequent_words(text, k)) {
     19 		io::printf("%s ", word);
     20 	}
     21 	io::printn();
     22 	return 0;
     23 }
     24 
     25 fn String[] frequent_words(String text, int k, Allocator alloc= allocator::heap()) {
     26 	@pool() {
     27 		FrequencyTable freq_map = util::frequency_table(text, k, allocator::temp());
     28 
     29 		int[] counts = freq_map.tvalues();
     30 		int max = 0;
     31 		freq_map.@each(; String _k, int count) {
     32 			if (count > max) max = count;
     33 		};
     34 
     35 		List{String} res;
     36 		res.tinit();
     37 		freq_map.@each(; String key, int v) {
     38 			if (v == max) {
     39 				res.push(key.copy(alloc));
     40 			}
     41 		};
     42 		return res.to_array(alloc);
     43 	};
     44 }
     45 
     46 fn void test_frequent_words() @test {
     47 	String[] words = frequent_words("ACGTTGCATGTCGCATGATGCATGAGAGCT", 4, tmem);
     48 	assert(words.len == 2);
     49 	assert(words.contains("CATG"));
     50 	assert(words.contains("GCAT"));
     51 }
     52 fn bool String[].contains(ss, String target) {
     53 	foreach (s : ss) {
     54 		if (s == target) {
     55 			return true;
     56 		}
     57 	}
     58 	return false;
     59 }