Brian Downs


Software Engineer, Open Source Advocate, Outdoor Enthusiast


The Hardest Basics

One afternoon last week my former colleague bl4ckcontact sent a link that blew my mind. So as a test of my own ability and also as a reference for others, I’ve put the following list of code samples together showing how to accommodate the requirements of the preceding link. Please feel free to send me examples of how to do this in any language I don’t have listed.

After doing the first challenge and finding it not overly challenging, I got to thinking and figured I’d put together code examples for a number of tasks that might be asked of you during a coding interview. I will clear my throat further by saying that I’ve only had limited experience in coding interviews but I’ll reference many who have for legitimacy of the content.

Challenge 1

(Taken directly from the link above)

Print 100 to 1.

That’s it.

That was the question.

The Catch?

You need to start with “for(int i=0;” and continue from there - you cannot write anything before “for(int i=0;” and you can’t use two loops.

[Update: This is supposed to be a code snippet which already exists inside a function, so you can safely assume that inclusion of headers and declaration of the functions etc. is already done for you and you don’t need to worry about that.]

Each of the following examples can also be done using recursion and depending, it might make more sense.

Go

for i, j := 0, 100; i < j && j >= 1; i++ {
	fmt.Printf("%d\n", j-i)
}

Python

for i in range(100, 0, -1):
	print i

# Comprehension (this requires "from __future__ import print_function")
[print(n) for n in range(100, 0, -1)]

OCaml

The challenge says to use a loop but that’s unnecessary in OCaml.

let rec count_down n =
    Printf.printf "%d\n" n;
    if n <= 1 then n
	else count_down (n-1);;

Shell

for i in {100..1}; do echo $i; done

Challenge 2

Reverse an array.

Go

// s := []string{"a", "b", "c"}
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
	s[i], s[j] = s[j], s[i]
}

Python

[1, 2, 3][::-1]

Challenge 3