logic interview questions
Top logic frequently asked interview questions
I'm working on a higher-order theorem prover, of which unification seems to be the most difficult subproblem.
If Huet's algorithm is still considered state-of-the-art, does anyone have any links to explanations of it that are written to be understood by a programmer rather than a mathematician?
Or even any examples of where it works and the usual first-order algorithm doesn't?
Source: (StackOverflow)
I have recently stumbled upon the game 2048. You merge similar tiles by moving them in any of the four directions to make "bigger" tiles. After each move, a new tile appears at random empty position with value of either 2
or 4
. The game terminates when all the boxes are filled and there are no moves that can merge tiles, or you create a tile with a value of 2048
.
One, I need to follow a well-defined strategy to reach the goal. So, I thought of writing a program for it.
My current algorithm:
while (!game_over) {
for each possible move:
count_no_of_merges_for_2-tiles and 4-tiles
choose the move with large number of merges
}
What I am doing is at any point, I will try to merge the tiles with values 2
and 4
, that is, I try to have 2
and 4
tiles, as minimum as possible. If I try it this way, all other tiles were automatically getting merged and the strategy seems good.
But, when I actually use this algorithm, I only get around 4000 points before the game terminates. Maximum points AFAIK is slightly more than 20,000 points which is way larger than my current score. Is there a better algorithm than the above?
Source: (StackOverflow)
How do you get the logical xor of two variables in Python?
For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
The ^
operator seems to be bitwise, and not defined on all objects:
>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
Source: (StackOverflow)
Edit: this puzzle is also known as "Einstein's Riddle"
The Who owns the Zebra is an example of a classic set of puzzles and I bet that most people on Stack Overflow can solve it with pen and paper. But what would a programmatic solution look like?
Based on the clues listed below...
- There are five houses.
- Each house has its own unique color.
- All house owners are of different nationalities.
- They all have different pets.
- They all drink different drinks.
- They all smoke different cigarettes.
- The English man lives in the red house.
- The Swede has a dog.
- The Dane drinks tea.
- The green house is on the left side of the white house.
- They drink coffee in the green house.
- The man who smokes Pall Mall has birds.
- In the yellow house they smoke Dunhill.
- In the middle house they drink milk.
- The Norwegian lives in the first house.
- The man who smokes Blend lives in the house next to the house with cats.
- In the house next to the house where they have a horse, they smoke Dunhill.
- The man who smokes Blue Master drinks beer.
- The German smokes Prince.
- The Norwegian lives next to the blue house.
- They drink water in the house next to the house where they smoke Blend.
...who owns the Zebra?
Source: (StackOverflow)
PHP is famous for its type-juggling. I must admit it puzzles me, and I'm having a hard time to find out basic logical/fundamental things in comparisons.
For example: If $a > $b
is true and $b > $c
is true, must it mean that $a > $c
is always true too?
Following basic logic, I would say yes however I'm that puzzled I do not really trust PHP in this. Maybe someone can provide an example where this is not the case?
Also I'm wondering with the strict lesser-than and strict greater-than operators (as their meaning is described as strictly which I only knew in the past from the equality comparisons) if it makes any difference if left and right operands are swapped with strictly unequal values:
# Precondition:
if ($a === $b) {
throw new Exception(
'Both are strictly equal - can not compare strictly for greater or smaller'
);
}
($a > $b) !== ($b > $a)
For most of all type comparison combinations these greater / lesser comparison operators are not documented, so reading the manual was not really helpful in this case.
Source: (StackOverflow)
I'm looking for some "inference rules" (similar to set operation rules or logic rules) which I can use to reduce a SQL query in complexity or size. Does there exist something like that? Any papers, any tools? Any equivalencies that you found on your own? It's somehow similar to query optimization, but not in terms of performance.
To state it different: Having a (complex) query with JOINs, SUBSELECTs, UNIONs is it possible (or not) to reduce it to a simpler, equivalent SQL statement, which is producing the same result, by using some transformation rules?
So, I'm looking for equivalent transformations of SQL statements like the fact that most SUBSELECTs can be rewritten as a JOIN.
Source: (StackOverflow)
This question already has an answer here:
I was asked this in an interview. Given a list of integers, How can we find the biggest interval that has all its members in the given list?
E.g. given list 1,3,5,7,4,6,10 then answer would be [3, 7]. Because it has all the elements between 3 and 7.
I tried to answer but I wasn't convincing. The approach I took was to first sort the list and then check it for the biggest interval. But I was asked to do so in O(n)
.
Source: (StackOverflow)
Say you are trying to read this property
var town = Staff.HomeAddress.Postcode.Town;
Somewhere along the chain a null could exist.
What would be the best way of reading Town?
I have been experimenting with a couple of extension methods...
public static T2 IfNotNull<T1, T2>(this T1 t, Func<T1, T2> fn) where T1 : class
{
return t != null ? fn(t) : default(T2);
}
var town = staff.HomeAddress.IfNotNull(x => x.Postcode.IfNotNull(y=> y.Town));
or
public static T2 TryGet<T1, T2>(this T1 t, Func<T1, T2> fn) where T1 : class
{
if (t != null)
{
try
{
return fn(t);
}
catch{ }
}
return default(T2);
}
var town = staff.TryGet(x=> x.HomeAddress.Postcode.Town);
Obviously these are just abstracting away the logic and making the code (a little) more readable.
But is there a better/ more efficient way?
EDIT:
In my particular case the objects are being returned from a WCF service and I have no control over the architecture of those objects.
EDIT 2:
There is also this method:
public static class Nullify
{
public static TR Get<TF, TR>(TF t, Func<TF, TR> f) where TF : class
{
return t != null ? f(t) : default(TR);
}
public static TR Get<T1, T2, TR>(T1 p1, Func<T1, T2> p2, Func<T2, TR> p3)
where T1 : class
where T2 : class
{
return Get(Get(p1, p2), p3);
}
/// <summary>
/// Simplifies null checking as for the pseudocode
/// var r = Pharmacy?.GuildMembership?.State?.Name
/// can be written as
/// var r = Nullify( Pharmacy, p => p.GuildMembership, g => g.State, s => s.Name );
/// </summary>
public static TR Get<T1, T2, T3, TR>(T1 p1, Func<T1, T2> p2, Func<T2, T3> p3, Func<T3, TR> p4)
where T1 : class
where T2 : class
where T3 : class
{
return Get(Get(Get(p1, p2), p3), p4);
}
}
from this article http://qualityofdata.com/2011/01/27/nullsafe-dereference-operator-in-c/
Source: (StackOverflow)
I have a simple if statement as such:
if ($('html').hasClass('m320')) {
// do stuff
}
This works as expected. However, I want to add more classes to the if statement
to check if any of the classes are present in the <html>
tag. I need it so it's not all of them but just the presence of at least one class but it can be more.
My use case is that I have classes (e.g. m320
, m768
) added for various viewport widths so I only want to execute certain Jquery if it's a specific width (class).
Here is what i have tried so far:
1.
if ($('html').hasClass('m320', 'm768')) {
// do stuff
}
2.
if ($('html').hasClass('m320')) || ($('html').hasClass('m768')) {
// do stuff
}
3.
if ($('html').hasClass(['m320', 'm768'])) {
// do stuff
}
None of these seem to work though. Not sure what I am doing wrong but most likely my syntax or structure.
Source: (StackOverflow)
I've made a nice form, and a big complicated 'add' function for handling it. It starts like this...
def add(req):
if req.method == 'POST':
form = ArticleForm(req.POST)
if form.is_valid():
article = form.save(commit=False)
article.author = req.user
# more processing ...
Now I don't really want to duplicate all that functionality in the edit()
method, so I figured edit
could use the exact same template, and maybe just add an id
field to the form so the add
function knew what it was editing. But there's a couple problems with this
- Where would I set
article.id
in the add
func? It would have to be after form.save
because that's where the article gets created, but it would never even reach that, because the form is invalid due to unique constraints (unless the user edited everything). I can just remove the is_valid
check, but then form.save
fails instead.
- If the form actually is invalid, the field I dynamically added in the edit function isn't preserved.
So how do I deal with this?
Source: (StackOverflow)
I was reading the function definition of bind, but I can't 100% understand the code as written:
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
Specifically, I don't get the purpose of fNOP
, and I don't understand why fBound
's prototype needs to be set. I am also hung up at the fToBind.apply
part (I can't figure out what this represents in this context).
Can someone can explain what is going on here?
Source: (StackOverflow)
I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected.
The code is as follows:
class Node(object):
def __init__(self, children = []):
self.children = children
The problem is that every instance of Node class shares the same children
attribute, if the attribute is not given explicitly, such as:
>>> n0 = Node()
>>> n1 = Node()
>>> id(n1.children)
Out[0]: 25000176
>>> id(n0.children)
Out[0]: 25000176
I don't understand the logic of this design decision? Why did Python designers decide that default arguments are to be evaluated at definition time? This seems very counter-intuitive to me.
Source: (StackOverflow)
I'm quite new to jQuery, and I've written a simple function to check the strength of a password for each keypress.
The idea is that every time a user enters a character, the contents is evaluated to test the strengh of the password they have entered... I'm sure everyone has seen these before.
Anyhow, the logic I have used is that no password begins with a value of 1. When a lower-case character is used, the score increments to 2. When a digit is used the score increments by 1 again, same for when an uppercase character is used and when the password becomes 5 or more characters long.
What is returned is the strength of the password so far as a value from 1 to 5 every time a key is pressed.
So, about my question. The way that I've done it doesn't seem very jQuery like... almost like I may as well have just done straight javascript. Also I was wondering about my logic. Have I done anything done or overlooked something? Any suggestions from smarter people than myself?
Any suggestions or advice would be appreciated.
$(document).ready(function(){
$("#pass_strength").keyup(function() {
var strength = 1;
/*length 5 characters or more*/
if(this.value.length >= 5) {
strength++;
}
/*contains lowercase characters*/
if(this.value.match(/[a-z]+/)) {
strength++;
}
/*contains digits*/
if(this.value.match(/[0-9]+/)) {
strength++;
}
/*contains uppercase characters*/
if(this.value.match(/[A-Z]+/)) {
strength++;
}
alert(strength);
});
});
Source: (StackOverflow)
Could someone explain why there is 27
different Bool->Bool
values, from which 11
can be definied in Haskell?
Source: (StackOverflow)