Questions tagged [logic]
Logic refers to the ultimate flow of your code and how you arrive your desired solution. Questions should relate to finding a coding solution (or improving existing coding logic) to a given problem. Please use with an appropriate language tag, a thorough description of your logic, and the relevant code you're working on. General logic questions are off-topic. If you simply need a code review, consider https://codereview.stackexchange.com
logic
9,421
questions
2070
votes
14
answers
1.0m
views
What is the optimal algorithm for the game 2048?
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 ...
295
votes
6
answers
23k
views
Are || and ! operators sufficient to make every possible logical expression?
The logical expression ( a && b ) (both a and b have boolean values) can be written like !(!a || !b), for example. Doesn't this mean that && is "unneccesary"? Does this mean that all ...
129
votes
15
answers
29k
views
Solving "Who owns the Zebra" programmatically?
Edit: this puzzle is also known as "Einstein's Riddle"
The Who owns the Zebra (you can try the online version here) is an example of a classic set of puzzles and I bet that most people on Stack ...
120
votes
3
answers
16k
views
Type-juggling and (strict) greater/lesser-than comparisons in PHP
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 > ...
112
votes
2
answers
674k
views
Simple 'if' or logic statement in Python [closed]
How would you write the following in Python?
if key < 1 or key > 34:
I've tried every way I can think of and am finding it very frustrating.
106
votes
4
answers
7k
views
Why does this if statement, with an assignment and equality check, evaluate to false?
How does a Java if statement work when it has an assignment and an equality check OR-d together??
public static void test() {
boolean test1 = true;
if (test1 = false || test1 == false) {
...
94
votes
5
answers
31k
views
Why does javascript accept commas in if statements?
I stumbled across some javascript syntax that seemed like it should produce a parse error of some kind but doesn't:
if (true, true) {console.log('splendid')} else {console.log('horrid')} // splendid
...
92
votes
9
answers
9k
views
Is ((a + (b & 255)) & 255) the same as ((a + b) & 255)?
I was browsing some C++ code, and found something like this:
(a + (b & 255)) & 255
The double AND annoyed me, so I thought of:
(a + b) & 255
(a and b are 32-bit unsigned integers)
I ...
89
votes
10
answers
117k
views
JQuery .hasClass for multiple values in an if statement
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 ...
87
votes
2
answers
5k
views
What is the combinatory logic equivalent of intuitionistic type theory?
I recently completed a university course which featured Haskell and Agda (a dependent typed functional programming language), and was wondering if it was possible to replace lambda calculus in these ...
84
votes
7
answers
8k
views
Why if (n & -n) == n then n is a power of 2?
Line 294 of java.util.Random source says
if ((n & -n) == n) // i.e., n is a power of 2
// rest of the code
Why is this?
74
votes
6
answers
85k
views
In Java, what are the boolean "order of operations"?
Let's take a simple example of an object Cat. I want to be sure the "not null" cat is either orange or grey.
if(cat != null && cat.getColor() == "orange" || cat.getColor() == "grey") {
//do ...
74
votes
9
answers
21k
views
General rules for simplifying SQL statements
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, ...
73
votes
6
answers
31k
views
Which Logic Operator Takes Precedence
So, I'm looking into writing a slightly more complex operation with logic operators in an if-else statement. I know I can do parentheses, and I know it's the better way of doing this, but I've gotten ...
68
votes
15
answers
51k
views
Looking for simple rules-engine library in .NET [closed]
Does anyone know of a good .NET library rules library (ideally open-source)? I need something that can do nested logic expressions, e.g., (A AND B) AND (B OR C OR D). I need to do comparisons of ...
67
votes
13
answers
91k
views
Multi-variable switch statement in C#
I would like use a switch statement which takes several variables and looks like this:
switch (intVal1, strVal2, boolVal3)
{
case 1, "hello", false:
break;
case 2, "world&...
65
votes
10
answers
106k
views
Most efficient/elegant way to clip a number?
Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lower and upper?
Of course, ...
61
votes
3
answers
10k
views
Curry-Howard isomorphism
I've searched around the Internet, and I can't find any explanations of CHI which don't rapidly degenerate into a lecture on logic theory which is drastically over my head. (These people talk as if "...
60
votes
4
answers
6k
views
Higher-order unification
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 ...
59
votes
11
answers
7k
views
Why does IQueryable.All() return true on an empty collection?
So I ran into a situation today where some production code was failing precisely because a method performed exactly as documented in MSDN. Shame on me for not reading the documentation. However, I'm ...
52
votes
25
answers
92k
views
Fastest way of finding the middle value of a triple?
Given is an array of three numeric values and I'd like to know the middle value of the three.
The question is, what is the fastest way of finding the middle of the three?
My approach is this kind of ...
52
votes
4
answers
31k
views
Mustache - How to detect array is not empty?
I want to implement the following logic with Mustache:
{{#if users.length > 0}}
<ul>
{{#users}}
<li>{{.}}</li>
{{/users}}
</ul>
{{/if}}
...
50
votes
4
answers
25k
views
Jasmine expect logic (expect A OR B)
I need to set the test to succeed if one of the two expectations is met:
expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number));
expect(mySpy.mostRecentCall.args[0]).toEqual(false);
I ...
48
votes
2
answers
58k
views
Django edit form based on add form?
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....
46
votes
5
answers
21k
views
Median of 5 sorted arrays
I am trying to find the solution for median of 5 sorted arrays. This was an interview questions.
The solution I could think of was merge the 5 arrays and then find the median [O(l+m+n+o+p)].
I ...
45
votes
8
answers
69k
views
C++ interview preparation [closed]
I have a Phone interview coming up next with with a company which works in financial software industry. The interview is mainly going to be in C++ and problem solving and logic. Please tell me the ...
44
votes
2
answers
3k
views
Why is '' > 0 True in Python 2?
In Python 2.x:
>>> '' > 0
True
Why is that?
44
votes
9
answers
8k
views
Why are default arguments evaluated at definition time? [duplicate]
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 ...
44
votes
9
answers
28k
views
Booleans have two possible values. Are there types that have three possible values? [duplicate]
Possible Duplicate:
What's the best way to implement an 'enum' in Python?
I’m writing a function that, ideally, I’d like to return one of three states: “yes”, “no”, and “don’t know”.
...
43
votes
11
answers
15k
views
What is fuzzy logic?
I'm working with a couple of AI algorithms at school and I find people use the words Fuzzy Logic to explain any situation that they can solve with a couple of cases. When I go back to the books I just ...
42
votes
10
answers
9k
views
Find the biggest interval that has all its members in list in O(n) [duplicate]
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]....
41
votes
10
answers
26k
views
XOR of three values
What is the simplest way to do a three-way exclusive OR?
In other words, I have three values, and I want a statement that evaluates to true IFF only one of the three values is true.
So far, this is ...
41
votes
3
answers
3k
views
How does Djinn work?
OK, so I realise that I will probably regret this for the rest of my life, but... How does Djinn actually work?
The documentation says that it uses an algorithm which is "an extension of LJ" and ...
41
votes
18
answers
50k
views
How do I determine if *exactly* one boolean is true, without type conversion?
Given an arbitrary list of booleans, what is the most elegant way of determining that exactly one of them is true?
The most obvious hack is type conversion: converting them to 0 for false and 1 for ...
40
votes
7
answers
425k
views
AND/OR in Python? [duplicate]
I know that the and and or expressions exist in python, but is there any and/or expression? Or some way to combine them in order to produce the same effect as a and/or expression?
my code looks ...
39
votes
3
answers
58k
views
Fastest way to get sign in Java?
I'd like to get the sign of a float value as an int value of -1 or 1.
Avoiding conditionals is always a good idea in reducing computational cost. For instance, one way I can think of would be to use ...
39
votes
2
answers
133k
views
oracle sql date not later than today
I need to display some data if it's a
- new data
- updated data
let's say, I will be basing these data from a publishdate column and updated column where publishdate and updateddate are both ...
39
votes
2
answers
19k
views
Visual Studio Project/Item Template Parameter Logic
Since I have only seen a few posts on the topic but no in-depth explanation of the logic for parameters in templates for Visual Studio, I figured I'd post this here.
Following the MSDN article you ...
37
votes
8
answers
6k
views
Reason for "all" and "any" result on empty lists
In Python, the built-in functions all and any return True and False respectively for empty iterables. I realise that if it were the other way around, this question could still be asked. But I'd like ...
36
votes
3
answers
243k
views
ReferenceError: Invalid left-hand side in assignment
my code for a rock paper scissors game (called toss) is as follows:
var toss = function (one,two) {
if(one = "rock" && two = "rock") {
console.log("Tie! Try again!");
}
// ...
36
votes
15
answers
63k
views
jQuery password strength checker
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 ...
35
votes
8
answers
21k
views
What are the best uses of Logic Programming?
By Logic Programming I mean the a sub-paradigm of declarative programming languages. Don't confuse this question with "What problems can you solve with if-then-else?"
A language like Prolog is very ...
34
votes
8
answers
280k
views
Is it common for 0 to mean ‘true’ and 1 to mean ‘false’ in a C API?
I came across an is_equals() function in a C API at work that returned 1 for non-equal SQL tables (false) and 0 for equal ones (true). I only realized it after running test cases on my code, one for ...
33
votes
3
answers
10k
views
Universal and Existential Quantifiers of First-Order Logic
I am taking a Scala programming course. At one point the instructor said:
Functions blah and bladdy are the universal and existential
quantifiers of first-order logic.
Could someone translate "...
31
votes
17
answers
6k
views
How can I simplify this set of if statements? (Or, what's making it feel so awkward?)
My colleague showed me this piece of code, and we both wondered why we couldn't seem to remove duplicated code.
private List<Foo> parseResponse(Response<ByteString> response) {
if (...
31
votes
4
answers
41k
views
Ruby if .. elsIf .. else on a single line?
With the ruby ternary operator we can write the following logic for a simple if else construct:
a = true ? 'a' : 'b' #=> "a"
But what if I wanted to write this as if foo 'a' elsif bar 'b' else '...
31
votes
2
answers
48k
views
Is there an AND option on the rules condition in .gitlab-ci.yml?
I want to create some nested conditions: i need this pipeline to work when it is a merge or merge request and with certain name start "feature". So, is there an AND condition in the 'only' ...
30
votes
5
answers
19k
views
Predicate vs Functions in First order logic
I have been so confused lately regarding difference between predicate and function in first order logic.
My understanding so far is,
Predicate is to show a comparison or showing a relation between ...
30
votes
11
answers
1k
views
Elegant way of reading a child property of an object
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 ...
30
votes
4
answers
8k
views
What does `true = false` mean in Coq?
[I am not sure this is appropriate for stack overflow, but there are many other Coq questions here so perhaps someone can help.]
I am working through the following from http://www.cis.upenn.edu/~...