The Interview: The Front Nine

18

5

The Interview: The Front Nine

This is the first of a series of challenges inspired by programming job interview questions.

You walk into the office where your potential future boss sits. "Come on in and sit down", he says. You nervously sit down, making sure your snappy yet professional attire is free of wrinkles. He asks you many questions, about your education, previous work experiences, and so on. You answer them mostly honestly, adding a little embellishment here and there to make yourself sound better. He leans forward and begins to speak again.

"Have you ever heard of code golfing?" Why, yes, you love to golf code, and do it frequently in your free time. "Great. The last part of the interview is a technical examination. You will be tasked with writing code to solve a series of problems..." He hands you a sheet of paper. You quickly glance over it. Easy peasy. Now why did he ask about code golfing?

"You will be graded based on the total size of your solutions to these problems. If you can score lower than all the other candidates, the job is yours." Oh. "Like golf, there are 18 problems, broken up into two sets of 9. Feel free to use any language you like to solve them; we have compilers and interpreters for every language you've heard of, and certainly a few that you haven't. Good luck!"

The Tasks

Task 1: Multiplication Table

Given a number n as input, output a multiplication table for positive integers in the range [1, n]. n will be in the range [1, 12]. All numbers should be left-aligned in the table. Use the character x for the top-left corner.

Examples:

n=4
x   1   2   3   4
1   1   2   3   4
2   2   4   6   8
3   3   6   9   12
4   4   8   12  16

n=10
x   1   2   3   4   5   6   7   8   9   10
1   1   2   3   4   5   6   7   8   9   10
2   2   4   6   8   10  12  14  16  18  20
3   3   6   9   12  15  18  21  24  27  30
4   4   8   12  16  20  24  28  32  36  40
5   5   10  15  20  25  30  35  40  45  50
6   6   12  18  24  30  36  42  48  54  60
7   7   14  21  28  35  42  49  56  63  70
8   8   16  24  32  40  48  56  64  72  80
9   9   18  27  36  45  54  63  72  81  90
10  10  20  30  40  50  60  70  80  90  100

Task 2: Ordinal RMS

Given a string of ASCII characters, output the root-mean-square average of their ASCII ordinals. The string will never contain a NULL byte (ordinal 0).

Examples:

Input: The Interview: The Front Nine
Output: 95.08290393488019

Input: `1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./
Output: 91.38101204135423

Task 3: Projectile Motion

Given the initial velocity and angle with the horizon of a projectile fired from ground level, output the horizontal distance it will travel before landing. The initial velocity will be given in meters per second, the angle will be given in degrees, and the distance shall in meters. Assume Earth gravity (g=9.81 m/s/s), and ignore relativistic effects. For the sake of this problem, you may assume the Earth is flat (you will not need to consider the curvature of the Earth when making your calculations). The given angle will be in the range [0, 90]. Your answer should be accurate to at least two decimal places (rounding is allowed).

Examples:

velocity=50, angle=45
Result: 254.84 (rounded)

velocity=10, angle=60
Result: 8.82798576742547

Task 4: etaoin shrdlu

Given a string of non-null printable ASCII characters (ordinals in the range [32,127]), output the string, with its characters sorted by their frequencies in descending order. In the case of a tie, order by ASCII ordinal, ascending.

Examples:

Input: "Hello, World!"
Output: "llloo !,HWder"

Input: "Programming Puzzles and Code Golf"
Output: "    oooPPaaddeeggllmmnnrrzzCGfisu"

Task 5: Fibonacci Index

Given a number, determine if it is a Fibonacci number, and if it is, output its index (starting from 1) in the sequence. If it is not a Fibonacci number, output 0. In the case of 1, which is in the sequence twice, output the earliest occurrence (index 1).

Examples:

Input: 1
Output: 1

Input: 144
Output: 12

Input: 4
Output: 0

Task 6: Anagrams

Given three strings of lowercase English letters ([a-z]), output a string that uses all the letters in the first string, begins with the second string, and ends with the third string. If such a string cannot be constructed, output an empty string. The input strings will always be at least one letter long. The "middle" of the output string (between the prefix and postfix string) may be empty, if the prefix and postfix strings together use all of the letters in the source string.

Examples:

Input: geobits bi es
Possible output: bigtoes

Input: mariatidaltug digital trauma
Output: digitaltrauma

Input: mego go lf
Output: (empty string)

Task 7: Filling In The Blanks

Given a list of strings and a fill character, output the result of padding all of the strings to the length of the longest string with the fill character, sorted in ascending order by the original lengths of the strings, preserving the original order in the case of a tie. You should be able to handle lists of any finite length, containing strings of any finite length, bounded only by memory constraints.

Examples:

Input: ["hello","world","this","is","a","test"], 'x'
Output: ["axxxx","isxxx","thisx","testx","hello","world"]

Input: ["I'm","a","lumberjack","and","I'm","okay"], '!'
Output: ["a!!!!!!!!!","I'm!!!!!!!","and!!!!!!!","I'm!!!!!!!","okay!!!!!!","lumberjack"]

Task 8: Making Change

Given a number in the range [0.01,0.99], output the number of each of the 4 standard US coins that should be used to represent this value such that the total number of coins is minimized. The input will always have exactly 2 places behind the decimal.

Coin value reference:

Penny: 0.01, Nickel: 0.05, Dime: 0.10, Quarter: 0.25

Examples:

Input: 0.75
Output: [0,0,0,3]

Input: 0.23
Output: 3 pennies, 0 nickels, 2 dimes, 0 quarters

Task 9: Merging Ranges

Given a finite list of 2-tuples containing integers that represent ranges, output the result of merging all overlapping or adjacent ranges. All ranges will be at least of length 1, and the starting value will always be less than the ending value. The order of the output does not matter.

Examples:

Input: (2,3), (4,5), (6,9), (0,7)
Output: (0,9)

Input: (-3,4), (2,5), (-10,-4)
Output (-10,-4), (-3,5)

Input: (2,3), (5,6), (6,8)
Output: (5,8), (2,3)

Rules

  • This is , so shortest answer (in bytes) wins.
  • Your score will be the sum of the byte counts for all of your solutions.
  • Standard loopholes are forbidden.
  • Input and output may be performed in whatever manner is considered standard for your language.
  • You may write full programs or functions for each challenge, and may interchange between the two across challenges.
  • You must use the same language for all the challenges. If version differences are significant enough for them to be usually considered separate entries in challenges, you must use the same version throughout. For example, if you use Python, you must use either Python 2 or Python 3 for all challenges.
  • You must solve all of the challenges. Answers that only solve some of the challenges will be considered non-competitive.
  • You may use language builtins or standard libraries.

Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 63014; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

Mego

Posted 2015-11-05T14:36:56.257

Reputation: 32 998

Are we allowed to output numbers in scientific notation in task 1? – FUZxxl – 2015-11-05T18:14:00.893

1although i would love to have such an interview i doubt if it ranks people well. eh, whatever. still fun – proud haskeller – 2015-11-05T19:42:46.860

Do we have to print results or can we return them from functions? If the latter is permissible, for task 1 can we return a matrix or similar? – Alex A. – 2015-11-05T19:56:22.347

Task 8 seems to have 2 output formats, can we just use the first one? – aditsu quit because SE is EVIL – 2015-11-05T19:59:30.733

@aditsu Those are two example output formats. You may use any format within reason. – Mego – 2015-11-05T21:01:09.960

@AlexA. You can return results from functions. I'm guessing your matrix question is about #1 - yes, that is acceptable. – Mego – 2015-11-05T21:01:56.313

This is an awesome challenge! – isaacg – 2015-11-05T21:33:24.890

How add imports to the byte count? Let's say 4 of the tasks need the same import (e.g import math), does it count 4 times? Or can I answer with a single source file with 9 functions for the 9 task with some imports at the beginning counting only once? Same for helper functions that can be used in several tasks. – nimi – 2015-11-05T23:19:12.887

Is crashing with an error and printing nothing to STDOUT considered "output the empty string" for task 6? – isaacg – 2015-11-06T07:53:47.323

In task 8, can counts be printed in the order quarters, dimes, nickels, pennies? – isaacg – 2015-11-06T08:00:36.320

@nimi The solutions to each of the challenges are considered separate - if you need to import something for multiple tasks, each task's answer must have the import. – Mego – 2015-11-06T15:36:36.267

@isaacg Re: crashing: No. As per our usual requirements, the only allowed output besides what is specified in the task is anything the compiler/interpreter outputs that cannot be suppressed and color codes. Re: task 8: Yes, but you should mention in your answer what the order is. – Mego – 2015-11-06T15:39:05.100

@Mego: All right. However, I think you're wasting a good golfing opportunity. This way it's just 9 standard tasks, no difference to 9 separate questions, no added value. If we can combine them into a single challenge there's much more room for golfing. Please reconsider this for the next part. – nimi – 2015-11-06T16:56:49.503

@nimi With the (admittedly few) multiple-holes challenges so far, the requirement has been that the individual answers should be independently-runnable. The point of this challenge was to enforce the one-language requirement - some of these tasks are short in a given language, but the others are much longer. I will keep your suggestion in mind for the Back Nine, though. – Mego – 2015-11-06T17:27:09.713

For task #1, since you said we can return a matrix, does that matrix need to include the x and ranges, or just the multiplication results? – mbomb007 – 2015-11-06T22:48:17.487

@mbomb007 You need the headers and the x. – Mego – 2015-11-07T19:31:41.400

1@pppery, this question is older than the link you provided, so I don't think that it applies to this question. – Night2 – 2019-10-19T01:49:26.567

I'm voting to close this question as off-topic because it's a multi-part challenge with insufficient interaction between the parts

– pppery – 2019-12-20T04:20:48.850

Answers

8

Pyth, 155 153 149 142 141 131 130 bytes

4 bytes thanks to @FryAmTheEggman

1, 5 and 4 bytes thanks to @Jakube

  1. 24 bytes: J+1SQp\xtjmsm.[`*dk\ 4JJ

Construct the multiplication table from the list [1, 1, 2, 3, ...], which is +1SQ, then print a x and remove its first character.

  1. 10 bytes: @.Om^Cd2z2

Straightforward.

  1. 18 bytes: c*.t.tyvw7Z*QQ9.81

Uses the formula sin(2 theta) * v^2/a, where theta is the angle, v is the initial velocity and a is 9.81

  1. 7 bytes: o_/zNSz

Straightforward.

  1. 15 bytes: hxeM.u,eNsNQU2Q

Generate fibonacci pairs, find the index of the input in them, add one.

  1. 14 bytes: IqSzSJj.-zsQQJ

Use bagwise subtraction to remove the prefix and suffix from the word, then put the remainder of the word in the middle. If the result of this is not a permutation of the input, don't print it.

  1. 8 bytes: C.tolNQz

Sort by length. Filled transpose. Transpose again.

  1. 18 bytes: Jsttz/L~%Jd[25T5 1

Output coin counts are in the order [quarters, dimes, nickels, pennies].

Remove first 2 characters of input and cast to int to get cents. Save to J. For each number d in the list [25, 10, 5, 1], post-assign J%d to J, then generate the value /Jd with the original value of J. Print.

  1. 16 bytes: C-M.p,JS{srMQhMJ

Turn the tuples into ranges, combine into one list, deduplicate and sort. Save this to J. Form J, hMJ and hMJ, J, where hMJ is J with every element increased by 1. Perform subtraction in both cases. The former is the lower ends of the ranges, the latter is the higher ends. Transpose them into pairs and print.

isaacg

Posted 2015-11-05T14:36:56.257

Reputation: 39 268

9

CJam, 162

  1. 25 bytesqi),0Xt_ff{*s4Se]}N*s0'xt
  2. 12 bytesq_:i:mh\,mq/ (© Dennis)
  3. 18 bytesq~P*90/ms\_**9.81/
  4. 12 bytesq$e`{0=~}$e~ (© Dennis)
  5. 16 bytes1_{_2$+}99*]qi#)
  6. 22 bytesqS/(1+1$s{1$#Lt}/)@@**
  7. 18 bytesq~{,}$_z,f{W$e]}p;
  8. 16 bytesq2>i25A5]:md]W%p
  9. 23 bytesq~${_0=2$1=>{+$3%}|}*]p

Dennis agreed to join forces :)

aditsu quit because SE is EVIL

Posted 2015-11-05T14:36:56.257

Reputation: 22 326

6

CJam, 223 bytes

Task 1, 35 bytes

ri_)_,0Xt2m*::*0'xt:s@s,2+f{Se]}/N*

Try it online.

Task 2, 12 bytes

q_:i:mh\,mq/

Try it online.

Task 3, 27 bytes

rd180/P*_mc\ms]rdf*~4.905/*

Try it online.

Task 4, 12 bytes

q$e`{0=~}$e~

Try it online.

Task 5, 17 bytes

XXri:R{_2$+}*]R#)

Try it online.

Task 6, 25 bytes

re!_rf#:!.*r:S;{N+SN+#)}=

Try it online.

Task 7, 19 bytes

{:C;{,}$_W=,f{Ce]}}

Try it online.

Task 8, 33 bytes

A4m*{:+}$r2>i:R;{[X5A25].*:+R=}=p

Try it online.

Task 9, 43 bytes

{{~1$-,f+}%:|$__,(%a\2ew{:-W<},+e_$2/2,f.+}

Try it online.

Dennis

Posted 2015-11-05T14:36:56.257

Reputation: 196 637

4

Haskell, 650 bytes

Task 1, 88 bytes:

f n="x   "++unlines(map(take 4.(++"   ").show=<<)$[1..n]:map(\a->a:map(a*)[1..n])[1..n])

Task 2, 76 bytes:

g s=sqrt(sum(map(fromIntegral.(^2).fromEnum)s)/sum(s>>[1]))

Task 3, 28 bytes

v?a=v*v/9.81*sin(2*a*pi/180)

Task 4, 60 bytes:

import Data.List
i x=concat$sortOn((0-).length)$group$sort x

Task 5, 64 bytes

j=(%zip[0..]z);x%((i,h):t)|x<h=0|x==h=i|1<2=x%t;z=scanl(+)0(1:z)

Task 6, 93 bytes

import Data.List
k a b c|q b a&&q c a=b++((a\\b)\\c)++c|1<2="";q=(.sort).isSubsequenceOf.sort

Task 7, 81 bytes

import Data.List
s!f=map(take(maximum$map r s).(++cycle[f]))(sortOn r s);r=length

Task 8, 73 bytes

m x=floor(x*100)#[25,10,5,1];x#[]=[];x#(h:t)|(d,m)<-divMod x h=(m#t)++[d]

Task 9, 87 bytes (a shameless copy of @MtnViewMark's answer from a similar challenge)

n i=foldr(&)[]i;p@(a,b)&(q@(c,d):r)|b<c=p:q&r|a>d=q:p&r|1<3=(min a c,max b d)&r;p&_=[p]

nimi

Posted 2015-11-05T14:36:56.257

Reputation: 34 639

2

Mathematica 10.3, 465 bytes

All of these are anonymous functions. Also, thanks to Martin for help golfing, since I'm a noob at Mathematica.

Task 1, 69 bytes

Grid@Join[{Join[{"x"},r=Range@#]},Flatten/@({r,Outer[1##&,r,r]}\[Transpose])]&

\[Transpose] is the 3 byte "transpose" symbol.

Task 2, 13 bytes

Mean[#^2]^.5&

or

√Mean[#^2]&

(√ is 3 bytes). The RootMeanSquare built-in isn't quite short enough...

Task 3, 18 bytes

Sin[2#2°]#/9.81#&

Task 4, 57 bytes

""<>SortBy[c=Characters@#,{-c~Count~#&,ToCharacterCode}]&

Task 5, 33 bytes

Tr@Position[Fibonacci@Range@#,#]&

or

Tr[Fibonacci@Range@#~Position~#]&

or

Tr[Fibonacci~Array~#~Position~#]&

Task 6, 178 bytes (currently has a bug)

({s,a,b}=Characters@{##};q=If[#2~SubsetQ~#,List@@(Plus@@#-Plus@@#2),{}]&;i=If[#!={},##]&;x=i[q[s,a],{}];y=If[x!={},i[q[x,b],{},Null],Null];Echo[If[y!=Null,""<>Join@{a,y,b},""]])&

Less golfed:

({s,a,b}=Characters@{##};
q=If[#2~SubsetQ~#,List@@(Plus@@#-Plus@@#2),{}]&;
i=If[#!={},##]&;
x=i[q[s,a],{}];
y=If[x!={},i[q[x,b],{},Null],Null];
Echo[If[y!=Null,""<>Join@{a,y,b},""]])&

String manipulation is horrid...

Task 7, 39 bytes

#~SortBy~StringLength~StringPadRight~#1

Task 8, 46 bytes

FrobeniusSolve[{1,5,10,25},100#]~MinimalBy~Tr&

or

{.1,.5,.10,.25}~FrobeniusSolve~#~MinimalBy~Tr&

Task 9, 12 bytes

Interval@##&

Intervals passed to the constructor are automatically union-ed. Beat that.

mbomb007

Posted 2015-11-05T14:36:56.257

Reputation: 21 944