Skip to content

Instantly share code, notes, and snippets.

@sdrew
Last active October 4, 2020 01:48
Show Gist options
  • Save sdrew/87040fa10c0590d263cde45c3bef39a3 to your computer and use it in GitHub Desktop.
Save sdrew/87040fa10c0590d263cde45c3bef39a3 to your computer and use it in GitHub Desktop.
FogCreek Application Problem - Support Engineer 2
Sort the characters in the following string:
abcdefghijklmnopqrstuvwxyz_
by the number of times the character appears in data.txt
Now take the sorted string, and drop all the characters after (and including) the _.
The remaining word is the answer.
Download including Swift Playground:
https://sdrew.me/uploads/FogCreek.zip
https://repl.it/@sdrew/FogCreek-Application-Problem-Elixir
https://repl.it/@sdrew/FogCreek-Application-Problem-Go
https://repl.it/@sdrew/FogCreek-Application-Problem-NodeJS
https://repl.it/@sdrew/FogCreek-Application-Problem-PHP
https://repl.it/@sdrew/FogCreek-Application-Problem-Ruby
https://repl.it/@sdrew/FogCreek-Application-Problem-Swift
ftns_znzsaeeau_wr_zqxsseitsaaaxcezxhvh_jevbjvrdpfsrul_tyqaqjwuokvdjhmuayzqfcnkqlpdwaemheqekvwtzvmmexwssveifagkxvotgdqcifsbkbmipqivazbrnpltwlgquvzvgjrmytvof_xvkhddtxkvrrhhsunn_cpybhlkvktkwiqpogbzuemtowaoshyxhukbfnrrtdnijtgindrcwkdvjywnyxbylyzpomoskdhfntfcvdlacupmptpaziqhpajqnxyxcmbaloxsthybnqsmd_uwuomtlj_b_iyyywmyvpj__lvcbiklrlapbrfnzivlhgupvrgarfcmmbpomjxekaybkpmwyozkcldxymbuwooyyspp_ikhj_de_pcb_tsesbe_cont__ovyowernxwqcybrsnwb_onopgmnfhezfofjpadinufpfprnnbbr_ufkcenovnpkhbzgiihqsonfxkp_pdrvmf_bauuu_ioaidomgkprbzzfkidxmhevtwfnavxbxiukcsnqhoarejjgfygxxyuvcefgtwzbfecnmlwjnnjxkmajhakvhuayizvcshgaywmifoynzzienttuuwmdd_iqymyqsriefickvzvikelvckeuuokfhaeseqmrm_cpkmdthu_mnbu_way_tlrjnkytoextsvlfe_wcgzgwvkoqvnwcmxjtyjfpdpsdodpjhyhnjuzdmwsmiv_carq_kzglyepepkiseamadwnzfutojjpmlafouorbptamlcjuodlthimmssmzjznaecbypaumdwuetbv_dpjdhdqhclmiswusbibptnvn_zyuutgdtcwchb_erwwmdy_xxpdvtxrwotnsaigpp_uiyixorledeylbivfbstdhzzweqimcbtnnbyyypwaiaeehungak_mdjrfoppvovrlyui_rlibyxvgusfpurnffxmnudppgchhjmivgi_p_evmflkwc_jstxwxtcclvqyposfxoxhhb_zyfyxivpyhnzqidrubzh_dlfrrghayokgyotimnszgczpusrffayyrzsfn_owqmundgsfrxbglqvtgcjmoywhbwnxlbdqkbgvrwpsvvilqgkufu_meururrobq_zrrsbmioozqftbviljplkzhtsw_pkcgfjmixjiethrxfdxws_zurjayvyugzrl_rqixknlcclxhaqdljuypryubbu_yfyrbwtsyjbviusdxmuaeujvxcrqfaopyijeix_mkzsithazmvklvablhxzacfoqlgauqgbpxhldcmkcekdfbwobmuneaaikr_ocntplwnrjoyucowcekhpvkzjoqv_qvhjtf__rnjypnirmerhaojnuq_jbsndjsastgxhizgjgazabxqydjnlnn__vmtvsqxmbbuyglwioavonfztxtwipcfmgejxiuslamjqqbhjkgwmf_tfg_hxarnrcxtvqgkndcofxtdixthixkqvbrnnzwesnwwjyeebkrfjckbud_wqkyuqaauatacnujtelf_djhzcxqspadscfccmanzuocv_avmatigvioxenmjlvqyzgcrftkpfeviuripvlbpdatckiiwdbugibuttwglriwcgpbfcmz_vrdjaihkuibmqfisqsanbhjsmgtiudljhsnywcepmydhqbzelaotsfcbhaccrctmzinsmxd_mjtkfvs_vjjeyiygshmxgzskszhljm_vmwrpizgvslzkq_ccskqhbdxhypojjasycyvxwigklhwrrugzsmlotgzsztxloenoexulsighjlictnpemgeqzke_snpucycr_nqmfasp_ngfkelagipmg_ftglzolcnsdnwqctaclvxoynrranmrazoijagkepsdmccyroqlhrz_bqpirmwgkkgtjqscdqdcualohhdpkdmaoym_gpxqsu_vqeaggopucauptebrjvddnoarfwosak_fpqspfepsuifdkxkemhsrachirpuzddugugjukqwzfdmmhuratcgtgfkhnndkxbnkda_wlfdrqkquosd_pvhyjwysamnrwt_apzocrjatfsrwqchupjwpcwwgrlogyalotwntnz_f_xlnhkacsia_ndedhuemacxgmkqwgxlqudyfteufxsrfjmy_zuvbnprogxhqrnozvvmtsizsn_schptotqovvmkkrfatsssuwhcevoinortrbagzj_ufgddpiufqyqmohshgshmntcrtgtfgkzvjwgxbhzcipmz_twsfcl_uagaleivwjs_ngez_ccgmfzurlyqbibxcpg
#! /usr/bin/env elixir
# https://repl.it/@sdrew/FogCreek-Application-Problem-Elixir
data = Path.expand("./data.txt")
|> File.read!
|> String.trim
[word | _] = String.graphemes(data)
|> Enum.group_by(&String.first/1)
|> Enum.map(fn ({k,v}) -> {k, length(v)} end)
|> Enum.sort(&(elem(&1, 1) > elem(&2, 1)))
|> Enum.map(fn ({k,_}) -> k end)
|> Enum.join("")
|> String.split("_")
IO.puts word
// https://repl.it/@sdrew/FogCreek-Application-Problem-Go
// Run with command: go run ./go.go
package main
import (
"fmt"
"io/ioutil"
"sort"
"strings"
)
type MapSort struct {
Key string
Value int
}
func main() {
data, err := ioutil.ReadFile("./data.txt")
if err != nil {
panic(err)
}
alphabet := "abcdefghijklmnopqrstuvwkyz_"
dict := make(map[string]int)
for _, char := range strings.Split(alphabet, "") {
dict[char] = 0
}
for _, char := range data {
strChar := string(char)
dict[strChar] = dict[strChar] + 1
}
sorted := make([]MapSort, 0)
for key, val := range dict {
sorted = append(sorted, MapSort{key, val})
}
sort.Slice(sorted, func(a, b int) bool {
return sorted[a].Value > sorted[b].Value
})
word := ""
for _, val := range sorted {
char := val.Key
if char == "_" {
break
}
word = strings.Join([]string{word, char}, "")
}
fmt.Println("Word:", word)
}
#! /usr/bin/env node
// https://repl.it/@sdrew/FogCreek-Application-Problem-NodeJS
const fs = require('fs');
var dict = {};
var data = fs.readFileSync('data.txt').toString('utf8').split('');
data.forEach(char => {
if (typeof dict[char] === 'undefined') { dict[char] = 0; }
dict[char]++;
});
dict = Object.entries(dict);
dict.sort((a, b) => {
var a1 = a[1];
var b1 = b[1];
if (a1 < b1) { return 1; }
if (a1 > b1) { return -1; }
return 0;
})
var sorted = dict.map(arr => arr[0]).join('');
var word = sorted.split('_')[0];
console.log(word);
// Minified single line to copy into the browser console at http://www.fogcreek.com/jobs/SupportEngineerLevel2
$('#secret-message').text().split('').forEach(function(char){if(typeof window.fogCreekSecret==='undefined'){window.fogCreekSecret={};}if(typeof window.fogCreekSecret[char]==='undefined'){window.fogCreekSecret[char]=0;}window.fogCreekSecret[char]++;});window.fogCreekSecret=Object.entries(window.fogCreekSecret);window.fogCreekSecret.sort(function(a,b){if(a[1]<b[1]){return 1;}if(a[1]>b[1]){return -1;}return 0;});alert(window.fogCreekSecret.map(function(arr){return arr[0];}).join('').split('_')[0]);
// Readable version
$('#secret-message').text().split('').forEach(function (char) {
if (typeof window.fogCreekSecret === 'undefined') { window.fogCreekSecret = {}; }
if (typeof window.fogCreekSecret[char] === 'undefined') { window.fogCreekSecret[char] = 0; }
window.fogCreekSecret[char]++;
});
window.fogCreekSecret = Object.entries(window.fogCreekSecret);
window.fogCreekSecret.sort(function (a,b) {
if (a[1] < b[1]) { return 1; }
if (a[1] > b[1]) { return -1; }
return 0;
});
alert(window.fogCreekSecret.map(function (arr) {
return arr[0];
}).join('').split('_')[0]);
// Compile using:
// clang -framework Foundation ./obj-c.m -o ./test && ./test
#import <Foundation/Foundation.h>
int main(int argc, char** argv) {
NSString *dataPath = [[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingPathComponent:@"data.txt"];
NSString *data = [NSString stringWithContentsOfFile:dataPath encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *dict = [@{} mutableCopy];
for (NSUInteger idx = 0; idx < [data length]; idx++) {
NSString *curr = [NSString stringWithFormat:@"%c", [data characterAtIndex:idx]];
NSUInteger val = [[dict objectForKey:curr] unsignedIntegerValue];
[dict setObject:@(val + 1) forKey:curr];
}
NSArray *keys = [[[dict keysSortedByValueUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
NSString *word = [[[keys componentsJoinedByString:@""] componentsSeparatedByString:@"_"] firstObject];
NSLog(@"%@", word);
}
#! /usr/bin/env php
<?php
// https://repl.it/@sdrew/FogCreek-Application-Problem-PHP
$dict = [];
foreach (str_split('abcdefghijklmnopqrstuvwxyz_') as $char) { $dict[$char] = 0; }
$data = file_get_contents(realpath(join(DIRECTORY_SEPARATOR, [__DIR__ , 'data.txt'])));
foreach (str_split($data) as $char) {
if (!array_key_exists($char, $dict)) { continue; }
$dict[$char]++;
}
arsort($dict);
$sorted = implode('', array_keys($dict));
$word = explode('_', $sorted)[0];
echo "{$word}\n";
#! /usr/bin/env ruby
# https://repl.it/@sdrew/FogCreek-Application-Problem-Ruby
dict = ('a'..'z').to_a.tap { |arr| arr << '_' }.inject({}) { |memo, char| memo[char] = 0; memo }
data = File.read(File.join(__dir__, "data.txt"))
# METHOD A
# data.each_char do |char|
# next if dict[char].nil?
#
# dict[char] += 1
# end
# METHOD B
dict.keys.each { |char| dict[char] = data.count(char) }
sorted = dict.to_a.sort { |a, b| b[1] <=> a[1] }.inject([]) { |memo, arr| memo << arr.first; memo }
word = sorted.join('').split('_').first
puts word
//: Playground - noun: a place where people can play
// https://repl.it/@sdrew/FogCreek-Application-Problem-Swift
import UIKit
let alphabet: Array<Character> = Array("abcdefghijklmnopqrstuvwxyz_")
var dict: Dictionary<Character, Int> = Dictionary(uniqueKeysWithValues: zip(alphabet, Array(repeatElement(0, count: alphabet.count))))
let dataPath: String? = Bundle.main.path(forResource: "data", ofType: "txt");
let data: String = try String.init(contentsOfFile: dataPath!)
for char: Character in Array(data) {
let prevVal: Int? = dict[char]
if (prevVal != nil) { dict[char] = 1 + prevVal! }
}
var sorted: Array<Character> = Array(dict.keys).sorted { (a, b) -> Bool in
return dict[a]! > dict[b]!
}
let word: String.SubSequence = String(sorted).split(separator: Character("_")).first!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment