Can (a ==1 && a== 2 && a==3) ever evaluate to true?
stackoverflow.com
stackoverflow.com
My answer was that it's impossible. They said nothing is impossible. It happened 2 weeks back, but I'm still trying to find the answer.
The interviewer should have gone into much more depth instead of (presumably) marking that question as failed and moving on. This was a perfect opportunity to find out more about the interviewee's knowledge of Javascript instead of whether they immediately knew the answer to a trick question.
The interviewer could have asked about the difference between "==" and "===" operators, which any experienced Javascript developer should know at least a little about.
Then they could have asked if the interviewee knows how "==" converts types before comparing them, and find out if they know that it uses .toString() and .valueOf().
Then the interviewer could have asked about if those functions can be overridden, and how that can be done.
At this point, the interviewee's eyes may have lit up and they may have been able to solve the original question.
This approach would have given the interviewer information about the interviewee's knowledge of: "==" vs "===" operators, .toString() and .valueOf() functions, function overriding, and object variables. Instead the only knowledge that the interviewer learned was whether the interviewee had seen a similar problem before or was able to immediately recognize the answer.
Sure, the interviewer could have spent some more time to lead the interview in a more productive manner, but at the same time I'm left wondering: what does the interviewer get from answers to those questions? Do the answers say anything meaningful about the candidate's ability to write code (other than a weak-ish probably-can-code/not-a-coder signal)? What about ability to test? Design? Function as a team member? IMHO, the question wastes a lot of time building up to an aha moment, while only getting a glimpse of the candidate's ability to memorize various bits of trivia that are easy to google.
These questions are useful if you are looking for an experienced X programmer who can immediately start being productive in an X code base. While the original problem is definitely a trick question, I don't believe that any of the individual pieces of knowledge required are merely "bits of trivia" for an experienced Javascript developer.
It's the interviewer's responsibility to know what areas of knowledge are required for a role, and how important it is that a candidate is familiar with them. Memorizing the intricacies of "==" vs "===" may not be important, but I'd expect an experienced Javascript developer to know something about it.
What about ability to test? Design? Function as a team member?
Those skills are much harder to test for so most companies ignore them during the interview process and instead focus on attributes which can be tested for, and accept that the process is not 100% reliable.
1) The candidate demonstrates a lack of intellectual curiosity (and maybe even common sense) when they say “that’s impossible!” and move on.
2) The candidate attempted to pass off their (inaccurate) assessment as fact without even a shred of self-doubt. Colleagues like this are infuriating to work with.
If we are trying to measure some kind of mental ability as a predictor to work performance, one might question whether interviewer ability to extract such deeper insights from these questions is actually more effective than a g test.
I would probably not give this question in an interview, but if I did, I'd care a lot more about how the interviewee reacted to it than about getting the right answer. The people I want to work with are people who respond to weird questions with curiosity, not with guesses and a lack of followup. For a question that presumably would only take a few minutes to ask, it's decent enough. A bad question would be one that by design gives no information (or worse, gives misleading information), and this question does better than that.
Am I guaranteed to learn about their curiosity? No. In particular, candidates who are very nervous are more likely to clam up than start teasing out the details of the question. That's unfortunate, but hopefully this isn't your only interview question so there are still other opportunities for the candidate to show their stuff.
Asking only this question, without using the various other avenues one could explore from there, like you suggested, makes me actually question the competency of the interviewer. That is of course the competency in finding suitable applicants for the role they want to fill, assuming they're not looking only for people writing quirky 5-liners all day long which exploit some weird language behaviour.
int a = 1;
void *brute(void *vargp){
while(1) {
a = 1; a = 2; a = 3;
}
}
int main(){
pthread_t tid;
pthread_create(&tid, NULL, brute, NULL);
while(1){
if( a == 1 && a == 2 && a == 3 ){
printf("woo\n");
return;
}else{
printf("fail\n");
}
}
} class Equal {
public:
template <typename T>
bool operator==(const T& eq) { return true; };
All kinds of equality are possible. class a {};
multi sub infix:<==> (a $a, $b) {
True
}
if a == 1 && a == 2 && a == 3 {
say "true!"
}
If you wanted to make an actual iterator out of `a`, you could do: multi sub infix:<==> (a $a, $b) {
++(state $) == $b
}
In that case, `a` would equal 1, 2, and 3 in that order. 5 is right out. my \a = any(1, 2, 3);
if ( a == 1 && a == 2 && a == 3 ) {
say "OMG quantum superposition!!!";
}
For those wondering what's going on: https://docs.perl6.org/type/Junction.html :-) class A {
public static bool operator ==(A a, int b) => true;
public static bool operator !=(A a, int b) => false;
}
var a = new A();
if (a == 1 && a == 2 && a == 3) Console.WriteLine("This works"); private int _a;
public int a { get { _a++; return _a;}} a = Object.new; def a.==(b); true; end
now a == b returns true for all b.return true
The equivalent of "return true" is so powerful (or, alternatively, is so parsimonious in its use of power, depending on your perspective), you can even make it work in Haskell, where these mutation tricks don't work, because you can declare a newtype with a custom declaration of == that is just "true".
a == a
is true, while a + 1 == a + 1
evaluates to false.(edit: precision)
Integer b = a+1;
Integer c = a+1;
b==c
Which by default returns true for a=126 but false for a=127. A bad situation for sure, but thankfully pretty much every static analysis tool will spot that. int aa = 0;
#define a (++aa)
if(a == 1 && a == 2 && a == 3) {
printf("pff");
}That said, I feel that in practice I have to worry more about this strange hidden behaviour in C++ and Python than in C and JavaScript. And even Python is not so bad if you stick to the standard libraries.
In Python 3:
>>> import ctypes
>>> ctypes.memmove(id(5)+24, id(23)+24, 8)
>>> 2
2
>>> 3
3
>>> 2 + 3
23
Or, similarly for Python 2 >>> import ctypes
>>> ctypes.cast(id(4),ctypes.POINTER(ctypes.c_int))[4]=5
>>> 2
2
>>> 2 + 2
5 (let ((b 0))
(symbol-macrolet ((a (incf b)))
(and (= a 1) (= a 2) (= a 3))))
For those not familiar with them, symbol macros let a symbol be expanded to an arbitrary expression, kinda like a clean version of the C preprocessor.However, it is possible for that statement to evaluate to true with threads if you manipulate the a at the right times.
This feels like handing some prospective code monkey an example from the Underhanded C contest without warning them first. Very few people are going to pass that test.
Agree that this isn't a reasonable "normal" programming mistake to run into, but I think the question may be used for seeing how candidates approach a problem that they don't know how to solve.
I doubt the interviewers are looking for someone to get this question 100%, and more likely looking for how candidates would deal with a problem they haven't been confronted with before that seems unsolvable. Does the candidate just say it's impossible or a trick? Or do they double down and try to think of what could possibly cause this and offer up some possibilities?
And you are right, it can easily lead to mistakes; if you use logical operators by mistake when building a query, you will probably get 'True' instead of a query object.
| Ummm...hmm... no...?
> Wrong. Nothing is impossible. Next question. You are unable to use JSON.parse(JSON.stringify(x)), how do you clone x?
| Hmm, I'm actually not sure... its certainly possible...
> Appreciate your honesty, the correct answer is: you don't. Thank you for your time, we'll be in touch.
var i = 0;
window.__defineGetter__("a", function() { i++; return i; });
if(a === 1 && a === 2 && a === 3) {
"Wtf";
} let i = 0, a = {valueOf: () => ++i};
if (a == 1 && a == 2 && a == 3) {
console.log("all equal");
}
Object.defineProperty (modern version of __define[GS]etter__): let i = 0;
Object.defineProperty(self, "a", {get: () => ++i});
if (a == 1 && a == 2 && a == 3) {
console.log("all equal");
} var i = 0;
window.__defineSetter__("x", function(value) { i = value; });
window.__defineGetter__("x", function() {
// LCG, a = 4, c = 1, m = 9;
i = (4 * i + 1) % 9;
return i;
});
x = 3;
if(x === 4 && x === 8 && x === 6) {
"wtf!";
}IMO this interview question is not horrible, especially if the answer(s) given are taken as a larger context of evaluating someone. If the candidate the interviewer responded "no, can't evaluate to true", then a good follow up might be "in fact it can! can you think of why/how?"
It tests both debugging skill (not taking innocuous code for granted) and defensive programming (writing robust code that won't be affected by environment).
The obvious example of the latter on Javascript is being aware of how closures and scope work and avoiding global namespacing. If you're even vaguely aware that the kind of trickery in the SO question is a possibility you're much more likely to practice safe coding in that context.
Not really. You'll give the impression this quality of code is part of production code and send them running for the hills.
That said I wouldn't really consider this a good interview question.
1) said right there in the comment, but not why or how it was clever or what it really did
You were making out that a candidate would "run for the hills" based on a wild extrapolation about the company's production code - I was responding to that point, which is quite independent of the quality of the question.
I have nothing else to go on unless you have public repos. I personally don't think it's a wild extrapolation based on the code quality compared to interviews I've gotten and I quickly reject companies that don't put forth fair tests. At worst, I'm wrong about the code quality, but I'm still selecting based on bad interview questions, which I'm perfectly fine with and I think more people should do if only to generate some kind of rejection signal to get interviewers to stop asking mundane questions like this.
It's not like companies don't also reject candidates for equally small bullshit or extrapolating conclusions about candidates based on the interview anyway.
Interviews (technical or otherwise) are an opportunity for both parties to ask questions and discuss what each is looking for. In that sense, interview questions should ideally elicit discussion. This gives the interviewer an opportunity to assess how the candidate approaches problems and gives the candidate an opportunity to explore their perspective on those problems (again, in discussion -- dialogue)
I don't think the questions need to be "representative" as you say. The primary purpose is not too represent the company, it's to allow the candidate to best represent themselves. I'd actually say distilled problems may do this more effectively and efficiently than ones "lifted" from prod.
Also, in terms of putting "effort" into interview questions, lifting from prod seems much lazier tbh.
> I have nothing else to go on unless you have public repos
I've generally just asked, which has in my experience been received as a normal request.
I'm not sure what this tests if it was on a white board.
In terms of whiteboard/paper questions, the fact this touches on the mindset/approach to debugging makes it far better than a lot of other whiteboard/paper questions I've seen.
Your breakdown being a good example of such discussion.
Please never ask this on any interview loop, thanks.
It "works" because we've been trained to laude pointless BS as if it were somehow valuable. The interviewers themselves had to answer some BS questions, therefore they perpetuate it. Candidates don't reject the questions because there's no quicker way to fail an interview than to balk at an unfair question.
Ask yourself: Now that you know the answer, are you a better programmer? Truly?
If becoming a better programmer were that simple, anyone off the street could do it.
Random outcomes FTW.
But again I concede that this is totally unfair. Not everyone can immediately think out of the box at a moment's notice, especially during an interview which can be quite stressful. I certainly wouldn't place a lot of weight on those kind of questions; if the candidate surprised me with a novel answer, that would be the icing on the cake.
Yup. This is sometimes a skill you want to test for - I have had a job where I would occasionally get paged at 3 AM to diagnose and fix novel problems in parts of infrastructure that I hadn't previously interacted with, for a high-frequency trading company where every minute of downtime had a financial impact. If you're hiring for that sort of thing, asking people if they can figure out stupid problems under time pressure and in a high-stress situation is exactly what you want to select for.
If you're hiring someone to sit at their desk, write code, and go home after 8 hours, where "time-sensitive" problems have their response time is measured in days and not minutes and where there's plenty of time to Google for similar situations or try to reproduce the problem in a test environment, responding to weird questions on short notice with someone staring at you until you figure it out is a much less relevant skill. And I think most tech jobs fall in this category. Ideally, give them interview problems where they can go home, get some sleep, drink some tea, and figure out the answer in the morning. I've done a bunch of hero work on O(minute) timeframes, but my actual quality work has always taken days of thinking about the problem quietly.
This conditional evaluates to `true`, but how?
If you first ask, 'Is this possible?', then most of us, who have long forgotten terrible coding standards, would say no, out of hand. I would have thought the interviewer was testing to see if I was an idiot.
I find once I resolve myself to knowing that the bug is possible, then I can find and fix it.
This is a typical example of what is wrong and annoying with job interview questions. In a way it doesn't really matter if the line could possibly evaluate to true, it shouldn't be written in the first place. What in the world tells your NO answer about your skill to do the job you are applying for? That you're not smart enough? Come on, I'd be really pissed off with shit like this.
I often find these toy examples or trick questions (also in the context of C++ inheritance, for example) very instructive.
i=0,a={valueOf:_=>++i}
- Omitting the variable statements in non-strict mode creates global (function scoped) variables- The comma operator evaluates its operands left to right and returns the rightmost operand, the result of which is irrelevant in this case
- The arrow function allows us to omit parenthesis around the function parameters, so any single character variable name works (in this case _)
- The arrow function syntax also allows us to omit the curly braces, and will automatically return the body of the function.
- Automatic Semicolon Injection allows us to omit the trailing ;
var a_ = a.toString();
if (a_ === "1" && a_ === "2" && a_ === "3") {
...
or really just if(false) {
...
would it be in violation?See https://v8project.blogspot.com/2017/09/disabling-escape-anal... for a related bug.
This algorithm does not describe an optional caching step to speed up/short-circuit the procedure, and so the optimization you describe would lead to non-spec-compliant behaviour.
I doubt they have that code in production, but even then, devs that are enamored with hacks like this and knowing pedantic answers to trick questions, chances are, their coding style will reflect just how "clever" they think they are.
This is the TXR Lisp interactive listener of TXR 188.
Quit with :quit or Ctrl-D on empty line. Ctrl-X ? for cheatsheet.
1> (defstruct incster nil
(val 0)
(:method equal (me) (inc me.val)))
#<struct-type incster>
2> (let ((a (new incster)))
(and (equal a 1) (equal a 2) (equal a 3)))
t
:)Equality substitution: http://www.nongnu.org/txr/txr-manpage.html#N-00790C76
Number.prototype.toString = () => '';
let a = '';
Although I always forget which side gets coerced (this would assume the right-hand side does). I like the side-effect approach, though — seems more nuanced and probably what they were looking for. if (state.step == DFA.INITIALIZED && state.step == DFA.RUNNING) {
...
}Doesn't mean you won't find those hacks in a million code bases used in production, though, and a professional knowledge of "yeah.. okay that's possible, but come on" isn't a bad thing to have.
I eventually nuked it and replaced it with the obvious for loop, which given as I also got to nuke the implementation of the class in question, meant a significant net reduction in line count, one less file in the repo, and one less wart in the code for new developers to stumble over.
function test (a) {
try {
return !!(typeof a === 'undefined' && a(1) && a[2])
} catch (e) {
return false
}
}
It is possible to get it to return true.Feel free to add a link with your answer later on, just in case you came up with something different.
Everyone suggested methods of changing the value of 'a', but what if the == operator is changed to something that returns true for these comparisons?
In general, I'm not sure how to feel: 75% not ok, and 25% ok with this type of question? As much as I despise these types of interview questions and this type of interviewing process, reading about them after the fact is always enlightening.
The fact that there are 5 or 6 completely different ways to accomplish this is boggling!
Like, set 'a' to contain a string like '0123456789' and then overload '==' to just mean "check if this number is in the string" then it works.
The expression uses the && operator, which is properly sequenced so no undefined behavior occurs in that case.
Though you might think that it's an incredibly bad idea, in fact the C standard library allows the getc and getchar functions to be defined as macros, and in fact they historically have been. Thus something like getc(stream) << 8 + getc(stream) stuffs multiple side effects into the same expression without a sequence point (not to mention neglecting to check the return values for EOF).
Each getc call wants to inspect and increment some buffer pointer, like
#define getc(s) ((s)->in < (s)->in_filled \
? (s)->buf[(s)->in++] \
: __real_getc(s))
We're not okay on account of the ?: sequencing, because the expression (A?B:C)+(X?Y:Z) doesn't sequence A relative to Z; there no sequence point between them. The two branches of the + can evaluate in parallel/interleaved fashion.a + a on the other hand would be undefined.
however, unless i'm mistaken,
a && b && c
is 3 distinct sequence points, in which case, the behaviour is in fact well-defined.a) limited in time, because you do research in your free time.
b) getting negative, or even worse, no or ignorant feedback by the other party.
c) getting tired, because you preach the same stuff over and over again.
I think is really hard to do responsible disclosure and maintain a calm attitude during the whole process. There is this awesome talk about responsible disclosure by David Kriesel who found bugs in Xerox's compression algorithms:
https://media.ccc.de/v/froscon2015-1524-lies_damned_lies_and...
I will grant that he found a problem where DBI and CGI was used together carelessly.
I think I remember him saying that perl comes with DBI, even though it has never done so. Also CGI has recently been taken out of the core distribution. (Most people have been recommending to not use it since around the year 2000.)
now that you know the answer try to come up with a solution.
Other examples are the classic "What's your greatest strength?" and "What's your greatest weakness?"
These are all recipes for brain freeze. If you ask me a question like that I'll probably think of something, but then I'll ask myself, "But was that really the best/worst/trickiest? Maybe there was another bug that was even trickier, or another strength/weakness of mine that's greater/worse than the one that just came to mind."
You can avoid that somewhat by leaving out the request to name the most extreme case: "Can you tell me about an interesting bug you fixed?" Then I could just pick one and start talking about it. Perhaps even better, ask about an embarrassing bug. Those may be the easiest to remember.
Maybe it would be that election results map that started turning states red when CNN was turning them blue? And how the bug snuck in even with three people reviewing the code change? And we could talk about what went wrong and how code reviews don't guarantee correct code. All kinds of possibilities for interesting discussion there.
Nah, no way. I work with some great engineers and they do not do "tricks" in their code. You write clean code that works within known conventions and patterns, so that it has long term maintainability. If you need "tricks" like this, then you're probably neck deep is some trash code looking for hail-marys to save you from yourself by causing side effects that you desire in the short term.
[0] https://www.slideshare.net/olvemaudal/deep-c/9-What_will_hap...
"Anything is possible? Then show me your perpetual motion devices perhaps? Do you compare equality to three different values often in production? Do you ask this question to all candidates, or just the Indians? Are these like the 'Jewish Problems' they used to ask at Moscow State University entrance exams?"
When I read interview experiences like these, it explains a lot about Silicon Valley's diversity problems to me.
(Or if you're saying that HN is where I'd find the "javascript" tag, I'm somehow not seeing that in my browser.)