42

For example, if I have a function that is guaranteed to receive either 5 or 7 as an argument, I want the function to return 5 if received 7 and 7 if received 5 without using any conditions.

I was asked this in an interview and was pretty stumped, thanks.

davegri
  • 2,206
  • 2
  • 26
  • 45
  • 4
    While I think this is a good interview problem, as it gauges the interviewees ability to quick solve simple problems, I don't think this is a great question for this site - it is both trivial and useless. I'm voting to close as 'too localized'. – BlueRaja - Danny Pflughoeft Feb 25 '13 at 09:37
  • I just realized it's only a rephrased "swap without temp" question http://stackoverflow.com/questions/804706/swap-two-variables-without-using-a-temp-variable?lq=1 – Martheen Feb 25 '13 at 10:00
  • 1
    It should have been posted on http://codegolf.stackexchange.com/ – B Faley Feb 25 '13 at 10:45
  • 1
    `Stumped` is the correct answer, as they want to employ someone who writes code that is plain and obvious-to-the-reader, rather than peppering it with im-smarter-than-you snares at every return. – John Mee Feb 25 '13 at 13:05

7 Answers7

96

Simple arithmetic:

return 7 - input + 5;

(which can be simplified as return 12 - input;)

Let's say the input is 7:

return 7 - 7 + 5 --> return 5

Or if the input is 5:

return 7 - 5 + 5 --> return 7

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
73

You can use any simple commutative calculation that can be reversed:

  • addition: f(x)=7+5-x
  • xor: f(x)=7^5^x
  • multiplication: f(x)=7*5/x
Pshemo
  • 122,468
  • 25
  • 185
  • 269
34
public int f(int x) {
    return x ^ 2;
}

In binary:

7 = 111
5 = 101
2 = 010

XOR (^ in java) flips the 2 bit on if it's off and off if it's on.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Skip Head
  • 7,580
  • 1
  • 30
  • 34
15

How about:

public int q(int in)
{
    static final int[] ret = {0, 0, 0, 0, 0, 7, 0, 5};
    return ret[in];
}
キキジキ
  • 1,443
  • 1
  • 25
  • 44
10

If I had been the one interviewing and you solved it only for numeric input, my next question would have been, "How would you solve this problem for non-numeric input?" because I wouldn't be looking for mathematical cleverness. Instead, how about this?

List<String> options = new ArrayList<>(Arrays.asList("bob", "fred"));
options.remove("bob");
System.out.println(options.get(0));

That can obviously be easily adapted to any type, including Object, so long as the equality of the objects works out correctly, and as a bonus, it can be expressed much more concisely in other languages, such as Groovy:

println((["bob", "fred"] - "bob").first())

The output, in either case, is obviously "fred". If I were the one interviewing, this is the answer I'd be looking for.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • 8
    I'm pretty sure remove() uses a condition, but I'm not sure if that would be considered breaking the rules or not – davegri Feb 24 '13 at 21:20
  • At least the Groovy version is breaking the rules, since at least in all programming languages I know of, `it != "bob"` is a condition. – Simon Forsberg Feb 24 '13 at 21:36
  • @Simon: True. I was thinking of "conditional" rather than "condition". But I didn't put what I meant to there, anyway. Fixed it. – Ryan Stewart Feb 24 '13 at 21:48
  • @user2105338: That's not what the question says. It says "without using conditions". There are no conditions in my code (except for the original Groovy snippet, which I corrected). – Ryan Stewart Feb 24 '13 at 21:49
  • 2
    I like the answer, but my interpretation of "without using any conditions" does not allow usage of a method that uses conditions. – Simon Forsberg Feb 24 '13 at 22:05
  • 1
    @user2105338: Basically, solving the problem this way shows that you can solve problems by manipulating common data structures, which is a useful thing to have in a developer. What does it show if you come up with a mathematical trick that only solves the problem for numbers? – Ryan Stewart Feb 24 '13 at 22:06
  • @Simon: To me, "without using any conditions" translates to "in a functional style", aka: "I want to see if your mind is stuck in a single paradigm." Isn't that a more useful thing to know about a job candidate than how his math skills are? – Ryan Stewart Feb 24 '13 at 22:09
  • using math is a way to avoid thinking in the "single paradigm" (that is: avoid the traditional if-else in this case). I believe there are many programmers (like the OP himself) that does not think about using math in a situation like this. Although they are probably even less that think of a solution like yours :) – Simon Forsberg Feb 24 '13 at 22:17
  • 1
    @Simon: "Math" isn't a [Programming Paradigm](http://en.wikipedia.org/wiki/Programming_paradigm). I'm talking about functional vs. imperative. The phrasing sounds exactly like that kind of question. – Ryan Stewart Feb 24 '13 at 23:44
  • Ok, I see your point. I also noticed you got a downvote. Even though I don't think this was what the interviewer was looking for, I do think it is a helpful and informational answer and will give you an upvote for it. – Simon Forsberg Feb 25 '13 at 01:03
  • @Simon: Downvotes are part of life around here :) It doesn't bother me much, except that there was no accompanying comment. I'm not trying to be difficult. I learn from this place, so I try to contribute back alternate (and sometimes controversial!) points of view that will make people think :) Thanks! – Ryan Stewart Feb 25 '13 at 01:30
  • @RyanStewart I don't think the question was solely about mathematical cleverness. It's probably a question to see if the candidate knows about bitwise operation which is quite complex that beginners tend to avoid (even the experienced ones!) but if learned correctly can give you elegant solutions. It is also a good indicator of a candidate's analytical skills. Now, using objects as inputs will defeat that purpose. – Adrian M Feb 25 '13 at 10:19
8
public int xyz(int x) {
    return 35 / x;
}
SREEJITH
  • 816
  • 1
  • 8
  • 19
7

How does the xor one work? [for case f(x) = 7^5^x ]

XOR (^) is Exclusive OR and works this way

a|b|a^b
-------
0|0| 0
0|1| 1
1|0| 1
1|1| 0

So XOR (^) can be used to change bits of some number. For example when we want to change last two bits of any number (like xxxx10 to xxxx01) we can do it with numbrer ^ 3 since 3 is binary 00011.

Here are few facts about XOR

  1. XOR is symmetric -> a^b = b^a

  2. XOR is associative -> (a^b)^c = a^(b^c)

  3. a^a = 0 (ones in a will be replaced with zeros and zeros will be not changed)

    example for a = 157 (binary 010011101)

      010011101
    ^ 010011101
    -----------
      000000000
    
  4. 0^a = a (ones in a can only change zeros so they will change them to ones)

      000000000
    ^ 010011101
    -----------
      010011101
    

so using facts (1) and (2) 7^5^x == x^7^5 == x^5^7

Lets try to check how x^7^5 will work for x=7.

(x^7)^5 = (7^7)^5 = 0^5 = 5

And same happens for x=5

(x^5)^7 = (5^5)^7 = 0^7 = 7
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269