Given a 7 digit telephone number, print out all the possible sequences of letters that can represent
the given telephone number. Note that in a standard 12 key pad, 0 and 1 do not have any letters associated
with them. They are to be treated as such, i.e. a 0/1 in the telephone number will be retained in the final
word as well. You may use the following mapping between numbers and characters:
Credits: This challenge appeared in the Facebook Hacker Cup 2011.
A double-square number is an integer X which can be expressed as the sum
of two perfect squares. For example, 10 is a double-square because
10 = 3^2 + 1^2. Your task in this problem is, given X, determine the
number of ways in which it can be written as the sum of two squares.
For example, 10 can only be written as 3^2 + 1^2
(we don't count 1^2 + 3^2 as being different).
On the other hand, 25 can be written as 5^2 + 0^2 or as 4^2 + 3^2.
NOTE: Do NOT attempt a brute force approach. It will not work.
The following constraints hold:
0 <= X <= 2147483647
1 <= N <= 100
Input sample:
Your program should accept as its first argument a path to a filename.
You should first read an integer N, the number of test cases.
The next N lines will contain N values of X.
5
10
25
3
0
1
Output sample:
E.g.
1
2
0
1
1
Email Validation
Challenge Description:
You are given several strings that may/may not be valid emails.
You should write a regular expression that determines if the email
id is a valid email id or not. You may assume all characters are
from the english language.
Input sample:
Your program should accept as its first argument a filename.
This file will contain several text strings, one per line.
Ignore all empty lines. E.g.
foo@bar.com
this is not an email id
admin#codeeval.com
good123@bad.com
Output sample:
Print out 'true' (all lowercase) if the string is a valid email.
Else print out 'false' (all lowercase). E.g.
true
false
false
true
String List
Challenge Description:
Credits: Challenge contributed by Max Demian.
You are given a number N and a string S. Print all of the possible ways to write a string of length N from the
characters in string S, comma delimited in alphabetical order.
Input sample:
The first argument will be the path to the input filename containing the test data.
Each line in this file is a separate test case. Each line is in the format: N,S i.e.
a positive integer, followed by a string (comma separated). E.g.
1,aa
2,ab
3,pop
Output sample:
Print all of the possible ways to write a string of length N from the characters in string S comma
delimited in alphabetical order, with no duplicates. E.g.
a
aa,ab,ba,bb
ooo,oop,opo,opp,poo,pop,ppo,ppp
Number Pairs
Challenge Description:
You are given a sorted array of positive integers and a number 'X'.
Print out all pairs of numbers whose sum is equal to X.
Print out only unique pairs and the pairs should be in ascending order
Input sample:
Your program should accept as its first argument a filename.
This file will contain a comma separated list of sorted numbers and then the sum 'X',
separated by semicolon. Ignore all empty lines. If no pair exists, print the string NULL e.g.
1,2,3,4,6;5
2,4,5,6,9,11,15;20
1,2,3,4;50
Output sample:
Print out the pairs of numbers that equal to the sum X.
The pairs should themselves be printed in sorted order i.e the first
number of each pair should be in ascending order. E.g.
1,4;2,3
5,15;9,11
NULL
Reverse and Add
Challenge Description:
Credits: Programming Challenges by Steven S. Skiena and
Miguel A. Revilla
The problem is as follows: choose a number, reverse its digits and
add it to the original. If the sum is not a palindrome (which means,
it is not the same number from left to right and right to left), repeat
this procedure.
In this particular case the palindrome 9339 appeared after the
4th addition. This method leads to palindromes in a few step for
almost all of the integers. But there are interesting exceptions.
196 is the first number for which no palindrome has been found.
It is not proven though, that there is no such a palindrome.
Input sample:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain
an integer n < 10,000. Assume each test case will always have an answer
and that it is computable with less than 100 iterations (additions).
Output sample:
For each line of input, generate a line of output which is the number
of iterations (additions) to compute the palindrome and the
resulting palindrome. (they should be on one line and separated
by a single space character).
For example:
4 9339
Jolly Jumpers
Challenge Description:
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the differences
between successive elements take on all possible values 1 through n - 1. eg.
1 4 2 3
is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively.
The definition implies that any sequence of a single integer is a jolly jumper. Write a program to determine
whether each of a number of sequences is a jolly jumper.
Input sample:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain an integer n < 3000 followed by n integers
representing the sequence. The integers are space delimited.
For example:
4 1 4 2 3
3 7 7 8
9 8 9 7 10 6 12 17 24 38
Output sample:
For each line of input generate a line of output saying 'Jolly' or 'Not jolly'.
For example:
Jolly
Not jolly
Not jolly
Trailing String
Challenge Description:
There are two strings: A and B. Print 1 if string B occurs at the end of string
A. Otherwise, print 0.
Input sample:
The first argument is a path to the input filename containing two comma-delimited strings, one per line.
Ignore all empty lines in the input file.
For example:
Hello World,World
Hello CodeEval,CodeEval
San Francisco,San Jose
Output sample:
Print 1 if the second string occurs at the end of the first string. Otherwise, print 0.
For example:
1
1
0
Decimal To Binary
Challenge Description:
You are given a decimal (base 10) number, print its binary representation.
Input sample:
Your program should accept as its first argument a path to a filename containing decimal numbers greater or equal to 0, one per line.
Ignore all empty lines.
For example:
2
10
67
Output sample:
Print the binary representation, one per line.
For example:
10
1010
1000011
Sum of integers
Challenge Description:
Write a program to determine the largest sum of contiguous integers in a list.
Input sample:
The first argument is a path to a filename containing a comma-separated list of integers, one per line.
For example:
-10,2,3,-2,0,5,-15
2,3,-2,-1,10
Output sample:
Print to stdout the largest sum. In other words, of all the possible contiguous subarrays for a given array,
find the one with the largest sum, and print that sum.
For example:
8
12
Number of Ones
Challenge Description:
Write a program which determines the number of 1 bits in the internal representation of a given integer.
Input sample:
The first argument is a path to a file. The file contains integers, one per line.
For example:
10
22
56
Output sample:
Print to stdout the number of ones in the binary form of each number.
For example:
2
3
3
Endianness
Challenge Description:
Write a program which prints the endianness of the system.
Input sample:
There is no input for this program.
Output sample:
Print to stdout the endianness, wheather it is LittleEndian or BigEndian.
For example:
BigEndian
Remove Characters
Challenge Description:
Write a program which removes specific characters from a string.
Input sample:
The first argument is a path to a file. The file contains the source strings and the characters that need to be
scrubbed. Each source string and characters you need to scrub are delimited by comma.
For example:
how are you, abc
hello world, def
Output sample:
Print to stdout the scrubbed strings, one per line. Ensure that there are no trailing empty spaces on each line
you print.
For example:
how re you
hllo worl
Lowest Common Ancestor
Challenge Description:
Write a program to determine the lowest common ancestor of two nodes in a binary search tree. You may hardcode the
following binary search tree in your program:
The first argument is a path to a file that contains two values. These values represent two nodes within the tree,
one per line. E.g.:
8 52
3 29
Output sample:
Print to stdout the lowest common ancestor, one per line. Lowest means the lowest depth in the tree,
not the lowest value. E.g.:
30
8
Mth to last element
Challenge Description:
Write a program which determines the M^{th} to the last element in a list.
Input sample:
The first argument is a path to a file. The file contains the series of space delimited characters followed by
an integer. The integer represents an index in the list (1-based), one per line.
For example:
a b c d 4
e f g h 2
Output sample:
Print to stdout the M^{th} element from the end of the list, one per line. If the index is larger than
the number of elements in the list, ignore that input.
For example:
a
g
Stack Implementation
Challenge Description:
Write a program which implements a stack interface for integers. The interface should have ‘push’ and ‘pop’
functions. Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer.
Input sample:
Your program should accept a file as its first argument. The file contains a series of space delimited integers, one per line.
For example:
1 2 3 4
10 -2 3 4
Output sample:
Print to stdout every alternate space delimited integer, one per line.
For example:
4 2
4 -2
Pangrams
Challenge Description:
The sentence 'A quick brown fox jumps over the lazy dog' contains every single letter in the alphabet.
Such sentences are called pangrams. You are to write a program, which takes a sentence, and returns all the
letters it is missing (which prevent it from being a pangram). You should ignore the case of the letters in
sentence, and your return should be all lower case letters, in alphabetical order. You should also ignore all
non US-ASCII characters.In case the input sentence is already a pangram, print out the string NULL
Input sample:
Your program should accept as its first argument a path to a filename. This file will contain several text strings,
one per line. E.g.
A quick brown fox jumps over the lazy dog
A slow yellow fox crawls under the proactive dog
Output sample:
Print out all the letters each string is missing in lowercase, alphabetical order . E.g.
NULL
bjkmqz
Ugly Numbers
Challenge Description:
Credits: This challenge has appeared in a google competition before.
Once upon a time in a strange situation, people called a number ugly
if it was divisible by any of the one-digit primes (2, 3, 5 or 7).
Thus, 14 is ugly, but 13 is fine. 39 is ugly, but 121 is not.
Note that 0 is ugly. Also note that negative numbers can also be ugly:
-14 and -39 are examples of such numbers.
One day on your free time, you are gazing at a string of digits,
something like:
123456
You are amused by how many possibilities there are if you are allowed
to insert plus or minus signs between the digits. For example you
can make:
1 + 234 - 5 + 6 = 236
which is ugly. Or
123 + 4 - 56 = 71
which is not ugly.
It is easy to count the number of different ways you can play with the
digits: Between each two adjacent digits you may choose put a plus sign,
a minus sign, or nothing. Therefore, if you start with D digits there
are 3^(D-1) expressions you can make. Note that it is fine to have
leading zeros for a number. If the string is '01023', then '01023',
'0+1-02+3' and '01-023' are legal expressions.
Your task is simple: Among the 3^(D-1) expressions, count how many of
them evaluate to an ugly number.
Input sample:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will be a single
line containing a non-empty string of decimal digits. The string in
each test case will be non-empty and will contain only characters '0'
through '9'. Each string is no more than 13 characters long. E.g.
1
9
011
12345
Output sample:
Print out the number of expressions that evaluate to an ugly number for
each test case, each one on a new line. E.g.
0
1
6
64
First Non-Repeated Character
Challenge Description:
Write a program which finds the first non-repeated character in a string.
Input sample:
The first argument is a path to a file. The file contains strings.
For example:
yellow
tooth
Output sample:
Print to stdout the first non-repeated character, one per line.
For example:
y
h
Repeated Substring
Challenge Description:
You are to find the longest repeated substring in a given text. Repeated substrings may not overlap.
If more than one substring is repeated with the same length, print the first one you find.(starting from the
beginning of the text).
NOTE: The substrings can't be all spaces.
Input sample:
Your program should accept as its first argument a path to a filename.
The input file contains several lines. Each line is one test case. Each line contains a test string. E.g.
banana
am so uniqe
Output sample:
For each set of input produce a single line of output which is the longest repeated substring.
If there is none, print out the string NONE. E.g.
an
NONE
Closest Pair
Challenge Description:
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
You will be given the x/y co-ordinates of several locations.
You will be laying out 1 cable between two of these locations.
In order to minimise the cost, your task is to find the shortest distance between a pair of locations,
so that pair can be chosen for the cable installation.
Input sample:
Your program should accept as its first argument a path to a filename.
The input file contains several sets of input. Each set of input starts with an integer N (0<=N<=10000),
which denotes the number of points in this set.
The next N line contains the coordinates of N two-dimensional points.
The first of the two numbers denotes the X-coordinate and the latter denotes the Y-coordinate.
The input is terminated by a set whose N=0. This set should not be processed.
The value of the coordinates will be less than 40000 and non-negative. eg.
5
0 2
6 67
43 71
39 107
189 140
0
Output sample:
For each set of input produce a single line of output containing a floating point number
(with four digits after the decimal point) which denotes the distance between the closest two points.
If there is no such two points in the input whose distance is less than 10000, print the line INFINITY. eg.
36.2215
String Permutations
Challenge Description:
Write a program which prints all the permutations of a string in alphabetical order. We consider that digits < upper
case letters < lower case letters. The sorting should be performed in ascending order.
Input sample:
Your program should accept a file as its first argument. The file contains input strings, one per line.
For example:
hat
abc
Zu6
Output sample:
Print to stdout the permutations of the string separated by comma, in alphabetical order.
Given a sequence, write a program to detect cycles within it.
Input sample:
Your program should accept as its first argument a path to a filename
containing a sequence of numbers (space delimited). The file can have multiple such lines. E.g
Print to stdout the first cycle you find in each sequence. Ensure that there are no trailing empty
spaces on each line you print. E.g.
6 3 1
49
1 2 3
The cycle detection problem is explained more widely on wiki
Constrains:
The elements of the sequence are integers in range [0, 99]
The length of the sequence is in range [0, 50]
Longest Lines
Challenge Description:
Write a program which reads a file and prints to stdout the specified number of the longest lines that are sorted
based on their length in descending order.
Input sample:
Your program should accept a path to a file as its first argument. The file contains multiple lines. The first line
indicates the number of lines you should output, the other lines are of different length and are presented randomly.
You may assume that the input file is formatted correctly and the number in the first line is a valid positive
integer.
For example:
2
Hello World
CodeEval
Quick Fox
A
San Francisco
Output sample:
Print out the longest lines limited by specified number and sorted by their length in descending order.
For example:
San Francisco
Hello World
Happy Numbers
Challenge Description:
A happy number is defined by the following process. Starting with any
positive integer, replace the number by the sum of the squares of its
digits, and repeat the process until the number equals 1 (where it
will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers, while
those that do not end in 1 are unhappy numbers.
Input sample:
The first argument is the pathname to a file which contains test data,
one test case per line. Each line contains a positive integer. E.g.
1
7
22
Output sample:
If the number is a happy number, print out 1. If not, print out 0. E.g
1
1
0
For the curious, here's why 7 is a happy number: 7->49->97->130->10->1.
Here's why 22 is NOT a happy number:
22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...
Rightmost Char
Challenge Description:
You are given a string 'S' and a character 't'. Print out the position of
the rightmost occurrence of 't' (case matters) in 'S' or -1 if there is
none. The position to be printed out is zero based.
Input sample:
The first argument will ba a path to a filename, containing a string and a character, comma
delimited, one per line. Ignore all empty lines in the input file. E.g.
Hello World,r
Hello CodeEval,E
Output sample:
Print out the zero based position of the character 't' in string 'S',
one per line. Do NOT print out empty lines between your output.
E.g.
8
10
Set Intersection
Challenge Description:
You are given two sorted list of numbers (ascending order). The lists
themselves are comma delimited and the two lists are semicolon
delimited. Print out the intersection of these two sets.
Input sample:
File containing two lists of ascending order sorted integers, comma
delimited, one per line. E.g.
Print out the ascending order sorted intersection of the two lists,
one per line. Print empty new line in case the lists have
no intersection. E.g.
4
8,9
Multiples of a Number
Challenge Description:
Given numbers x and n, where n is a power of 2, print out the smallest
multiple of n which is greater than or equal to x.
Do not use division or modulo operator.
Input sample:
The first argument will be a path to a filename containing a comma separated list
of two integers, one list per line. E.g.
13,8
17,16
Output sample:
Print to stdout, the smallest multiple of n which is greater than
or equal to x, one per line. E.g.
16
32
Unique Elements
Challenge Description:
You are given a sorted list of numbers with duplicates.
Print out the sorted list with duplicates removed.
Input sample:
File containing a list of sorted integers, comma delimited, one per line.
E.g.
1,1,1,2,2,3,3,4,4
2,3,4,5,5
Output sample:
Print out the sorted list with duplicates removed, one per line.
E.g.
1,2,3,4
2,3,4,5
File Size
Challenge Description:
Print the size of a file in bytes.
Input:
The first argument to your program has the path to the file you need to check the size of.
Output sample:
Print the size of the file in bytes.
E.g.
55
Bit Positions
Challenge Description:
Given a number n and two integers p1,p2 determine if the bits in
position p1 and p2 are the same or not. Positions p1 and p2 are 1 based.
Input sample:
The first argument will be a path to a filename containing a comma separated list
of 3 integers, one list per line. E.g.
86,2,3
125,1,2
Output sample:
Print to stdout, 'true'(lowercase) if the bits are the same,
else 'false'(lowercase). E.g.
true
false
Multiplication Tables
Challenge Description:
Print out the grade school multiplication table upto 12*12.
Input sample:
There is no input for this program.
Output sample:
Print out the table in a matrix like fashion, each number formatted
to a width of 4 (The numbers are right-aligned and strip out
leading/trailing spaces on each line). The first 3 line will look like:
Print the odd numbers from 1 to 99, one number per line.
Sum of Integers from File
Challenge Description:
Print out the sum of integers read from a file.
Input sample:
The first argument to the program will be a path to a filename containing
a positive integer, one per line. E.g.
5
12
Output sample:
Print out the sum of all the integers read from the file. E.g.
17
Lowercase
Challenge Description:
Given a string write a program to convert it into lowercase.
Input sample:
The first argument will be a path to a filename containing sentences, one per line.
You can assume all characters are from the english language. E.g.
HELLO CODEEVAL
This is some text
Output sample:
Print to stdout, the lowercase version of the sentence,
each on a new line. E.g.
hello codeeval
this is some text
Sum of Digits
Challenge Description:
Given a positive integer, find the sum of its constituent digits.
Input sample:
The first argument will be a path to a filename containing positive integers,
one per line. E.g.
23
496
Output sample:
Print to stdout, the sum of the numbers that make up the integer,
one per line. E.g.
5
19
Fibonacci Series
Challenge Description:
The Fibonacci series is defined as: F(0) = 0; F(1) = 1;
F(n) = F(n–1) + F(n–2) when n>1. Given an integer n≥0,
print out the F(n).
Input sample:
The first argument will be a path to a filename containing integer numbers,
one per line. E.g.
5
12
Output sample:
Print to stdout, the fibonacci number, F(n). E.g.
5
144
String Substitution
Challenge Description:
Credits: This challenge was contributed by Sam McCoy
Given a string S, and a list of strings of positive length,
F1,R1,F2,R2,...,FN,RN, proceed to find in order the occurrences
(left-to-right) of Fi in S and replace them with Ri. All strings are
over alphabet { 0, 1 }. Searching should consider only contiguous pieces
of S that have not been subject to replacements on prior iterations.
An iteration of the algorithm should not write over any
previous replacement by the algorithm.
Input sample:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain
a string, then a semicolon and then a list of comma separated strings. E.g.
10011011001;0110,1001,1001,0,10,11
Output sample:
For each line of input, print out the string after substitutions have
been made.eg.
11100110
For the curious, here are the transitions for the above example:
10011011001 => 10100111001 [replacing 0110 with 1001] =>
10100110 [replacing 1001 with 0] =>
11100110 [replacing 10 with 11]. So the answer is 11100110
Message Decoding
Challenge Description:
Credits: This challenge has appeared in a past ACM competition.
Some message encoding schemes require that an encoded message be sent in two parts. The first part,
called the header, contains the characters of the message. The second part contains a pattern that
represents the message.You must write a program that can decode messages under such a scheme.
The heart of the encoding scheme for your program is a sequence of "key" strings of 0's and 1's as follows:
0,00,01,10,000,001,010,011,100,101,110,0000,0001,. . .,1011,1110,00000, . . .
The first key in the sequence is of length 1, the next 3 are of length 2, the next 7 of length 3, the next 15
of length 4, etc. If two adjacent keys have the same length, the second can be obtained from the first by adding 1
(base 2). Notice that there are no keys in the sequence that consist only of 1's.
The keys are mapped to the characters in the header in order. That is, the first key (0) is mapped to the first
character in the header, the second key (00) to the second character in the header, the kth key is mapped to the
kth character in the header. For example, suppose the header is:
AB#TANCnrtXc
Then 0 is mapped to A, 00 to B, 01 to #, 10 to T, 000 to A, ..., 110 to X, and 0000 to c.
The encoded message contains only 0's and 1's and possibly carriage returns, which are to be ignored.
The message is divided into segments. The first 3 digits of a segment give the binary representation of the
length of the keys in the segment. For example, if the first 3 digits are 010, then the remainder of the segment
consists of keys of length 2 (00, 01, or 10). The end of the segment is a string of 1's which is the same length
as the length of the keys in the segment. So a segment of keys of length 2 is terminated by 11. The entire encoded
message is terminated by 000 (which would signify a segment in which the keys have length 0). The message is
decoded by translating the keys in the segments one-at-a-time into the header characters to which they have
been mapped.
Input sample:
The input file contains several data sets. Each data set consists of a header and a message.
These will all be on one line. The length of the header is limited only by the fact that key strings have a maximum
length of 7 (111 in binary). If there are multiple copies of a character in a header, then several keys will map to
that character. The encoded message contains only 0's and 1's, and it is a legitimate encoding according to the
described scheme. That is, the message segments begin with the 3-digit length sequence and end with the appropriate
sequence of 1's. The keys in any given segment are all of the same length, and they all correspond to characters in
the header. The message is terminated by 000.
Your program should accept the first argument as the filename and read the contents of this file as the test data,
according to the conditions above. E.g.
$#**\0100000101101100011100101000
Output sample:
For each data set, your program must write its decoded message on a separate line.
There should not be blank lines between messages. E.g.
##*\$
Array Absurdity
Challenge Description:
Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2,
inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears
exactly twice. Find the duplicated entry. (For bonus points, ensure your solution has constant space and
time proportional to N)
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case.
Ignore all empty lines. Each line begins with a positive integer(N) i.e. the size of the array, then a semicolon
followed by a comma separated list of positive numbers ranging from 0 to N-2, inclusive. i.e eg.
Print out the duplicated entry, each one on a new line eg
0
4
Reverse words
Challenge Description:
Write a program which reverses the words in an input sentence.
Input sample:
The first argument is a file that contains multiple sentences, one per line. Empty lines are also possible.
For example:
Hello World
Hello CodeEval
Output sample:
Print to stdout each sentence with the reversed words in it, one per line. Empty lines in the input should
be ignored. Ensure that there are no trailing empty spaces in each line you print.
For example:
World Hello
CodeEval Hello
Palindromic Ranges
Challenge Description:
A positive integer is a palindrome if its decimal representation (without leading zeros) is a palindromic string
(a string that reads the same forwards and backwards). For example, the numbers 5, 77, 363, 4884, 11111, 12121
and 349943 are palindromes.
A range of integers is interesting if it contains an even number of palindromes. The range [L, R], with L <= R,
is defined as the sequence of integers from L to R (inclusive): (L, L+1, L+2, ..., R-1, R).
L and R are the range's first and last numbers.
The range [L1,R1] is a subrange of [L,R] if L <= L1 <= R1 <= R. Your job is to determine how
many interesting subranges of [L,R] there are.
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case.
Each test case will contain two positive integers, L and R (in that order), separated by a space. eg.
1 2
1 7
87 88
Output sample:
For each line of input, print out the number of interesting subranges of [L,R] eg.
1
12
1
For the curious: In the third example, the subranges are: [87](0 palindromes),
[87,88](1 palindrome),[88](1 palindrome). Hence the number of interesting palindromic ranges is 1
Prefix expressions
Challenge Description:
You are given a prefix expression. Write a program which evaluates it.
Input sample:
Your program should accept a file as its first argument. The file contains one prefix expression per line.
For example:
* + 2 3 4
Your program should read this file and insert it into any data structure you like. Traverse this data structure
and evaluate the prefix expression. Each token is delimited by a whitespace. You may assume that sum ‘+’,
multiplication ‘*’ and division ‘/’ are the only valid operators appearing in the test data.
Output sample:
Print to stdout the output of the prefix expression, one per line.
For example:
20
Constraints:
The evaluation result will always be an integer ≥ 0.
The number of the test cases is ≤ 40.
Self Describing Numbers
Challenge Description:
A number is a self-describing number when (assuming digit positions
are labeled 0 to N-1), the digit in each position is equal to the
number of times that that digit appears in the number.
Input sample:
The first argument is the pathname to a file which contains test data,
one test case per line. Each line contains a positive integer.
E.g.
2020
22
1210
Output sample:
If the number is a self-describing number, print out 1. If not, print
out 0. E.g.
1
0
1
For the curious, here's how 2020 is a self-describing number:
Position '0' has value 2 and there is two 0 in the number.
Position '1' has value 0 because there are not 1's in the number.
Position '2' has value 2 and there is two 2.
And the position '3' has value 0 and there are zero 3's.
Sum of Primes
Challenge Description:
Write a program which determines the sum of the first 1000 prime numbers.
Input sample:
There is no input for this program.
Output sample:
Print to stdout the sum of the first 1000 prime numbers.
3682913
Prime Palindrome
Challenge Description:
Write a program which determines the largest prime palindrome less than 1000.
Input sample:
There is no input for this program.
Output sample:
Print to stdout the largest prime palindrome less than 1000.
929
Fizz Buzz
Challenge Description:
Players generally sit in a circle. The first player says the number “1”, and each player says next number in turn.
However, any number divisible by X (for example, three) is replaced by the word fizz, and any divisible
by Y (for example, five) by the word buzz. Numbers divisible by both become fizz buzz. A player
who hesitates, or makes a mistake is eliminated from the game.
Write a program that prints out the final series of numbers where those divisible by X, Y and both are replaced
by “F” for fizz, “B” for buzz and “FB” for fizz buzz.
Input sample:
Your program should accept a file as its first argument. The file contains multiple separated lines; each line
contains 3 numbers that are space delimited. The first number is the first divider (X), the second number is
the second divider (Y), and the third number is how far you should count (N). You may assume that the input file
is formatted correctly and the numbers are valid positive integers.
For example:
3 5 10
2 7 15
Output sample:
Print out the series 1 through N replacing numbers divisible by X with “F”, numbers divisible by Y with “B”
and numbers divisible by both with “FB”. Since the input file contains multiple sets of values, your output
should print out one line per set. Ensure that there are no trailing empty spaces in each line you print.
1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15
(ns codeeval.double-squares
(:use [clojure.contrib.duck-streams :only (read-lines)]
[clojure.contrib.math :only (exact-integer-sqrt)]))
(defn parse-line [line]
(Integer/parseInt line))
(def squares
(map #(* % %) (iterate inc 0)))
(defn square? [n]
(let [[_ r] (exact-integer-sqrt n)]
(== 0 r)))
(defn count-double-squares [n]
"The number of ways n can be written as the sum of two squares"
(let [square-upper-bound (/ n 2)]
(->> squares
(take-while #(<= % square-upper-bound))
(map #(- n %))
(filter square?)
count)))
(doall
(->> (first *command-line-args*)
read-lines
rest
(map parse-line)
(map count-double-squares)
(map println)))
(ns codeeval.email-regex
(:use [clojure.contrib.duck-streams :only (read-lines)]))
;; In the real world, this would be woefully inadequate. It's good
;; enough for this exercise, though.
(defn valid-email? [string]
(boolean (re-matches #"\w+@(\w+\.)*\w+" string)))
(doall
(->> (first *command-line-args*)
read-lines
(filter (complement empty?))
(map valid-email?)
(map println)))
(ns codeeval.number-of-ones
(:use [clojure.contrib.duck-streams :only (read-lines)]))
(defn parse-line [line]
(Integer/parseInt line))
(defn count-set-bits [n]
"Count the number of bits in n that are 1 (i.e. 'set')."
(loop [n n
count 0]
(cond (== n 0)
count
(< 0 (bit-and n 1))
(recur (bit-shift-right n 1)
(inc count))
:else
(recur (bit-shift-right n 1)
count))))
(doall
(->> (first *command-line-args*)
read-lines
(map parse-line)
(map count-set-bits)
(map println)))
/* Can't do this one in Clojure; the JVM is always big-endian. Heck,
everybody and their brother uses Intel chips these days, and both
i386 and x86_64 are little-endian, so just guessing LittleEndian is
very likely to pass validation. :) */
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char **argv) {
if (1 == htonl(1))
printf("BigEndian\n");
else
printf("LittleEndian\n");
return 0;
}
(ns codeeval.ugly-numbers
(:use [clojure.contrib.duck-streams :only (read-lines)]
[clojure.contrib.combinatorics :only (cartesian-product)]))
(def operators [:+ :- :concat])
(defn to-digits [number-string]
(map #(Integer/parseInt (str %)) number-string))
(defn ugly? [x]
"True if x is ugly (i.e. divisible by 2, 3, 5, or 7), false otherwise"
(boolean (some #(== 0 (mod x %)) [2 3 5 7])))
(defn postfix-process-token [stack token]
(cond (= :+ token)
(conj (drop 2 stack) (+ (second stack) (first stack)))
(= :- token)
(conj (drop 2 stack) (- (second stack) (first stack)))
(= :concat token)
(conj (drop 2 stack) (+ (* 10 (second stack)) (first stack)))
:else
(conj stack token)))
(defn postfix-evaluate [coll]
"Evaluate a postfix expression (in the form of a sequence).
Does no error checking, so if your stack has a bunch of stuff on it
when you're done, you just get the top instead of an error"
(->> coll
(reduce postfix-process-token (list))
first))
(defn possible-values [nums]
(->> operators
repeat
(take (dec (count nums)))
(apply cartesian-product)
;; NB: To produce the equivalent infix expression, simply
;; interleaving the operators and the numbers won't do
;; it. However, interleave-the-operators is a bijection, and
;; we're considering the whole set of possible expressions, so
;; all the possible values still show up, and so the count
;; works out.
(map #(concat nums %))
(map postfix-evaluate)))
(defn count-uglies [n]
(->> n
to-digits
possible-values
(filter ugly?)
count))
(doall
(->> (first *command-line-args*)
read-lines
(map count-uglies)
(map println)))
(ns codeeval.lowercase
(:use [clojure.contrib.duck-streams :only (read-lines)]))
;; what's the point of this challenge (and I use the term loosely)? Is
;; it to do my own lowercasing? In a Unicode world, that sounds like a
;; ridiculous amount of work.
(doall
(->> (first *command-line-args*)
read-lines
(map #(.toLowerCase %))
(map println)))
(ns codeeval.sum-prime)
;; The following is not the sieve of Eratosthenes. It performs
;; asymptotically worse than trial division(!). However, since we're only
;; finding primes under 1000, it'll do.
(def primes
(concat [2 3 5]
(lazy-seq
(filter (fn [candidate] (not-any? #(== 0 (mod candidate %)) primes))
(iterate inc 7)))))
(->> primes
(take 1000)
(reduce +)
print)
(ns codeeval.prime-palindrome)
;; The following is not the sieve of Eratosthenes. It performs
;; asymptotically worse than trial division(!). However, since we're only
;; finding primes under 1000, it'll do.
(def primes
(concat [2 3 5]
(lazy-seq
(filter (fn [candidate] (not-any? #(== 0 (mod candidate %)) primes))
(iterate inc 7)))))
(defn palindrome? [x]
(= (str x)
(apply str (reverse (str x)))))
(->> primes
(take-while #(< % 1000))
(filter palindrome?)
last
print)