Even or Odd without using a conditional statement (?)



  •  Not sure why ever you'd want to do it, but you can: http://programminggeeks.com/even-odd/

    I guess if you'd want to use the result in code, you'd have to do String compares? I'm not sure...

    The comments are nice as well. Silly IT students.



  • This is a great way to leverage try-catch: "a try catch block has been used to find whether the given number is even or odd. Here if the given no. is even, an exception occurs and the control goes into the catch block"



  • I like the guy that wants the author to "do d same without using modulus operator" and e-mail him the answer.

    "It's a top secret trick that only I shall learn!"



  • Bug report: isOdd(-7) returning false.


    Closed WONTFIX: Could not reproduce with 3, 1, or 7.



  • Nowhere near enterprisey enough! Everyone knows that OO is a 100% replacement for conditional structures.

    using System;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    

    namespace info.MiffTheFox.EvenOddComputer
    {
    public static class EvenOddComputer
    {
    public static IEvenOddResult Compute(long number)
    {
    long number2 = number & 1;
    return EvenOddResultFactory.CreateEvenOddResult(number2);
    }

        public static IEvenOddResult Compute(int number) { return Compute(Convert.ToInt64(number)); }
        public static IEvenOddResult Compute(short number) { return Compute(Convert.ToInt64(number)); }
        public static IEvenOddResult Compute(sbyte number) { return Compute(Convert.ToInt64(number)); }
        public static IEvenOddResult Compute(ulong number) { return Compute(Convert.ToInt64(number)); }
        public static IEvenOddResult Compute(uint number) { return Compute(Convert.ToInt64(number)); }
        public static IEvenOddResult Compute(ushort number) { return Compute(Convert.ToInt64(number)); }
        public static IEvenOddResult Compute(byte number) { return Compute(Convert.ToInt64(number)); }
    }
    
    public static class EvenOddResultFactory
    {
        public static IEvenOddResult CreateEvenOddResult(long result)
        {
            string[] cultureCode = CultureInfo.CurrentCulture.Name.Split('-');
            cultureCode = (from codePart in cultureCode select codePart.ToLowerInvariant()).ToArray();
    
            try
            {
                Type resultType = Assembly.GetExecutingAssembly().GetType("info.MiffTheFox.EvenOddComputer.EvenOddResult" + result + cultureCode[0] + cultureCode[1], true, true);
                return (IEvenOddResult)resultType.GetConstructor(new Type[0]).Invoke(new object[0]);
            }
            catch (Exception)
            {
                throw new EvenOddComputationException("The result was invalid, or the current culture was not supported.");
            }
            
        }
    }
    
    public interface IEvenOddResult
    {
        string Result { get; }
    }
    
    public abstract class EvenOddResult0 : IEvenOddResult
    {
        public abstract string Result { get; }
    }
    public abstract class EvenOddResult1 : IEvenOddResult
    {
        public abstract string Result { get; }
    }
    public class EvenOddResult0EnUs : EvenOddResult0
    {
        public override string Result
        {
            get { return "Even"; }
        }
    }
    public class EvenOddResult1EnUs : EvenOddResult1
    {
        public override string Result
        {
            get { return "Odd"; }
        }
    }
    
    public class EvenOddComputationException : ApplicationException
    {
        public EvenOddComputationException(string message) : base(message)
        {
        }
    }
    

    }



  •  The best method uses three computers.  The user sits near computer A, whose monitor is offset to the user's left.  Computer B sits about 10 feet directly in front of the user, and the monitor is large and clearly visible.  Computer C sits 10 feet farther still & has a monitor that is larger than computer B's, such that they appear the same relative size from the user's location.  Computer B's monitor wholly obscures Computer C's monitor, being directly in front of it from the user's point of view.

     

    Computer B has a program running that simply prints "Even" to the screen in a large font.  Computer C has a similar program that prints "Odd" to its screen.  Before the user enters a value, (s)he only sees "Even" since Computer C's screen is hidden.

     

    Computer A prompts the user for a number.  It writes the least significant bit to an output port, which causes the ignition of a squib and the detonation of the ten pounds of Semtex that are beneath Computer B.  So an even number triggers no explosion and the user reads "Even" off of Computer B's screen.  An odd number triggers the explosion, and should the user survive, they will read "Odd" off of Computer C's screen.



  • @Cat said:

     The best method uses three computers.  The user sits near computer A, whose monitor is offset to the user's left.  Computer B sits about 10 feet directly in front of the user, and the monitor is large and clearly visible.  Computer C sits 10 feet farther still & has a monitor that is larger than computer B's, such that they appear the same relative size from the user's location.  Computer B's monitor wholly obscures Computer C's monitor, being directly in front of it from the user's point of view.

     

    Computer B has a program running that simply prints "Even" to the screen in a large font.  Computer C has a similar program that prints "Odd" to its screen.  Before the user enters a value, (s)he only sees "Even" since Computer C's screen is hidden.

     

    Computer A prompts the user for a number.  It writes the least significant bit to an output port, which causes the ignition of a squib and the detonation of the ten pounds of Semtex that are beneath Computer B.  So an even number triggers no explosion and the user reads "Even" off of Computer B's screen.  An odd number triggers the explosion, and should the user survive, they will read "Odd" off of Computer C's screen.

    Semtex? What are you, Romanian or something?


  • Discourse touched me in a no-no place

    @pbean said:

    Not sure why ever you'd want to do it,[...]
    In the past, it's been the basis of job interview questions in a certain Asian country. The fact that a company involved with programming would ask you this sort of thing gives more information about the company than the answer ever could about the applicant.



  • @pbean said:

     Not sure why ever you'd want to do it, but you can: http://programminggeeks.com/even-odd/

    I guess if you'd want to use the result in code, you'd have to do String compares? I'm not sure...

    The comments are nice as well. Silly IT students.

    Ewwwwwww, even as a learning exercise this is a total WTF. No one should ever be taught that this stuff is ok. It should be used as an example of bad practice.

    Even the thought of using exceptions to control non exceptional program flow has made me feel dirty all over. I'm going to grab a shower.



  •  char s[5];

    int o = n & 1;

    int e = !o;

    s[0] =  o * 'o' + e * 'e';

    s[1] = o * 'd' + e * 'v';

    s[2] = o * 'd' + e * 'e';

    s[3] = e * 'n';

     s[4] = 0;

    printf(s);

     

    There -  I think that is even more wtf worthy.

     


  • Discourse touched me in a no-no place

    TRWTF is the page-top image banner: http://programminggeeks.com/wp-content/uploads/2010/01/logo.png

     Programmig geeks?  And it's been there for 2.5 years?  Nice!



  • Some pseudo-C code. I don't know if this would actually work...

    long long result = 1852143205LL;
    result = result - (n&1) * 1845563894LL;
    printf((char*) &result);



  • @superjer said:

    I like the guy that wants the author to "do d same without using modulus operator" and e-mail him the answer.

    "It's a top secret trick that only I shall learn!"

    try{
    int temp=1/(n&129);
    System.out.println("Odd");
    } catch(Exception e) {
    System.out.println("Even");
    }

    That ought to pass naive test cases (is & the correct operator in Java?). Should I email him?


  • Trolleybus Mechanic

     If performance is important, you put this in a lookup table. That way you don't have to recalculate it all on the fly!

    If accuracy is important, then you don't measure the number. Everyone knows that odd numbers take longer to calculate than even numbers. So you do a calculation on both X and X-1. If it takes longer to do the calulation on X, then the number is odd. If it takes less time, then it is even.

    And you can't trust those datetime libraries. You measure the latency of the electrons across the wire. It's the only way to be sure.



  • There's one web site that's going on my block list.

    Also, note the text in the graphic didn't even spell 'programming' correctly?

    Why on earth is it so damned important to do simple things in a hard way? Why is it important to check for even/oddness without using a conditional?

    You kids these days, get off my lawn!

    boolean isOdd(int x) {
      return x & 1 == 1;
    }
    

    boolean isEven(int x) {
    return x % 2 == 0;
    }

    Hell, if you're using C/C++ make a pre-processor macro out of it!

    Simple things ... do them simply.



  • I'll see your bit-twiddling and raise you bit-segfaulting:

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>

    void odd(void)
    {
      puts("odd");
    }

    void even(void)
    {
      puts("even");
    }

    int main(int argc, char *argv[])
    {
      int n = atoi(argv[1]);
      uintptr_t c = 0;
     
      c +=  (n&1)*((uintptr_t)odd);
      c += !(n&1)*((uintptr_t)even);
      (*((void(*)(void)(c)))();
      return 0;
    }

    Note: Most if not all modern compilers will hate this. Also not all compilers include stdint.h.

    I don't have a C compiler here at work, so this might not actually work at all, or it might fuck up your computer royally. Provided as-is, no warranty, etc.



  • @zelmak said:

    boolean isOdd(int x) { return x & 1 == 1; }

    boolean isEven(int x) {
    return x % 2 == 0;
    }

     

    Why did you use modulo for isEven() when x & 1 == 0 would have worked?

    Or is that the joke?

    Or doesn't that work in the language you're using?



  • @curtmack said:

    I'll see your bit-twiddling and raise you bit-segfaulting:

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>

    void odd(void)
    {
      puts("odd");
    }

    void even(void)
    {
      puts("even");
    }

    int main(int argc, char argv[)
    {
      int n = atoi(argv[1]);
      uintptr_t c = 0;
     
      c +=  (n&1)
    ((uintptr_t)odd);
      c += !(n&1)((uintptr_t)even);
      (
    ((void(*)(void)(c)))();
      return 0;
    }

    Note: Most if not all modern compilers will hate this. Also not all compilers include stdint.h.

    I don't have a C compiler here at work, so this might not actually work at all, or it might fuck up your computer royally. Provided as-is, no warranty, etc.

    Works in Turbo C 2.01 with only minor changes:


    #include <stdio.h>
    #include <stdlib.h>

    void near odd(void) {
    puts("odd");
    }

    void near even(void) {
    puts("even");
    }

    int main(int argc, char *argv[]) {
    int n = atoi(argv[1]);
    unsigned int c = 0;

    c += (n&1)*((unsigned int)odd);
    c += !(n&1)*((unsigned int)even);
    ((void(*)(void))c)();
    return 0;
    

    }

    Compile with -mt.

    I also tried doing it with a switch statement, but the resulting assembler code uses je rather than pointer arithmetic or directly manipulating the instruction pointer. Lame. I'm sure there's a fun way to do it by installing interrupt vectors.



  • @dhromed said:

    Why did you use modulo for isEven() when x & 1 == 0 would have worked?

    Or is that the joke?

    Or doesn't that work in the language you're using?

    x & (1 == 1)  → x has its lowest bit set
    x & (1 == 0)  → always false


  • @DoctaJonez said:

    @pbean said:

     Not sure why ever you'd want to do it, but you can: http://programminggeeks.com/even-odd/

    I guess if you'd want to use the result in code, you'd have to do String compares? I'm not sure...

    The comments are nice as well. Silly IT students.

    Ewwwwwww, even as a learning exercise this is a total WTF. No one should ever be taught that this stuff is ok. It should be used as an example of bad practice.

    Even the thought of using exceptions to control non exceptional program flow has made me feel dirty all over. I'm going to grab a shower.

    If something is a bad practice and it works then it's not a bad practice.



  • @Ben L. said:

    @dhromed said:
    Why did you use modulo for isEven() when x & 1 == 0 would have worked?

     

    Or is that the joke?

    Or doesn't that work in the language you're using?

    x & (1 == 1)  → x has its lowest bit set
    x & (1 == 0)  → always false

    This. == having a higher precedence than & in C and its derivatives is TRWTF.

     


  • Trolleybus Mechanic

    @Speakerphone Dude said:

    If something is a bad practice and it works then it's not a bad practice.
     

    I can run your electrical cables through your plumbling. The pipes already go through the entire house anyways, and it's easy to snake the cables through. I'll just drill through the pipes, and run the cables out, and seal it up with waterproof epoxy when I'm done.

    It works, but is sure as fuck is a bad practice.



  • @lurch said:

     char s[5];

    int o = n & 1;

    int e = !o;

    s[0] =  o * 'o' + e * 'e';

    s[1] = o * 'd' + e * 'v';

    s[2] = o * 'd' + e * 'e';

    s[3] = e * 'n';

     s[4] = 0;

    printf(s);

     

    There -  I think that is even more wtf worthy.

     

    Wow, it even runs in constant time -- it's cryptographically secure!



  • @dhromed said:

    @zelmak said:

    boolean isOdd(int x) { return x & 1 == 1; } boolean isEven(int x) { return x % 2 == 0; }
     

    Why did you use modulo for isEven() when x & 1 == 0 would have worked?

    Or is that the joke?

    Or doesn't that work in the language you're using?

    The unspoken suggestion was that if you didn't have access to bit-twiddling, you could still implement with a modulo operation. There are multiple, yet simple, ways to skin cat.

    (Personally, I would only implement one, not both, and use !odd for even checks -- or, obviously, vice versa.)

    @others said:

    [i]blah blah operator precedence blah blah[/i]
     

    I always get bit by the == operator precedence. Thanks for the reminder.

     



  • @zelmak said:

    @others said:

    blah blah operator precedence blah blah
     

    I always get bit by the == operator precedence. Thanks for the reminder.

     

    I suggest everyone use languages where boolean is a distinct type from integer and where you can't compare booleans to non-booleans directly.



  • Implicit comparisons with null are really handy though. As in if (myObject) myObject.postTdwtf(); rather than the Java-like if (myObject != null) ...

    If only it were possible to change Java's language spec.... siiiigh...



  • That IS terrible. Everybody knows the best solution is:

    #include <stdio.h>
    #include <string.h>
    
    void oddEven(unsigned int n, const char *result)
    {
    	if(n == 0) {
    		printf("%s\n", result);
    		return;
    	}
    
    	oddEven(--n, strcmp(result, "even") == 0 ? "odd" : "even");
    }
    
    ...
    oddEven(n, "even");
    


  • @Evo said:

    That IS terrible. Everybody knows the best solution is:

    #include <stdio.h>
    #include <string.h>
    

    void oddEven(unsigned int n, const char *result)
    {
    if(n == 0) {
    printf("%s\n", result);
    return;
    }

    oddEven(--n, strcmp(result, "even") == 0 ? "odd" : "even");
    

    }

    ...
    oddEven(n, "even");

     Completely unacceptable. This takes O(2^n) time on the number of bits. We can do better:

    void betterOddEven(unsigned int n, const char *result)
    {
    unsigned short int i;
    if(n == 0) {
    printf("%s\n", result);
    return;
    }

    for (i = 0 ; ; i&lt;&lt;=1) {
    	if (i &gt; n) {
    		betterOddEven(n-(i&gt;&gt;1), (i&gt;&gt;1 == 1 ? (strcmp(result, "even") == 0 ? "odd" : "even") : result));
    		return;
    	}
    }
    

    }

    ...
    betterOddEven(n, "even");

    Now it's O(n^2) on the number of bits. Porblem sovled!



  • @Lorne Kates said:

    @Speakerphone Dude said:

    If something is a bad practice and it works then it's not a bad practice.
     

    I can run your electrical cables through your plumbling. The pipes already go through the entire house anyways, and it's easy to snake the cables through. I'll just drill through the pipes, and run the cables out, and seal it up with waterproof epoxy when I'm done.

    It works, but is sure as fuck is a bad practice.

    This is how it's done on submarines. You should call the navy and let them know it's a bad practice.



  • @Speakerphone Dude said:

    This is how it's done on submarines. You should call the navy and let them know it's a bad practice.

    I will accept this bold statement from a known troll as absolutely true, despite my experience to the contrary.



  • In the spirit of TDWTF (I'll use python for simplicity):

    def isOdd(n):

       isOddMap = { 0: False, 1: True, 2: False, 3: True, 4: False, ...}

       return isOddMap[n



  • A non-stupid way (?)

    const char *oddOrEven(int i)
    {
        static const char * const eo[] = {"even", "odd"};
        return eo[i & 1];
    }

    Or as a macro:

    #define ODDOREVEN(X) (((X) & 1)?"odd":"even")



  • @Sir Twist said:

    A non-stupid way (?)

    Or as a macro:

    #define ODDOREVEN(X) (((X) & 1)CONDITIONAL OPERATOR"odd":"even")


    PTOFY



  • @Ben L. said:

    PTOFY

    OK, call the function the “no conditional operator way” and the macro the “real, actual way you would do it with no stupid restrictions” way.

     Edit: Pedantic dickweed answer: “the requirements said no conditional statement. ‘?:’ is an operator.



  •  @Sir Twist said:

     Edit: Pedantic dickweed answer: “the requirements said no conditional statement. ‘?:’ is an operator.

    A conditional operator. Which, when put into a statement, turns that statement into a conditional statement.

     


  • BINNED

    Here's a WTF Haskell version:

    isOdd = (!!) $ cycle [ False, True ] 


  • @Xyro said:

    @Speakerphone Dude said:
    This is how it's done on submarines. You should call the navy and let them know it's a bad practice.

    I will accept this bold statement from a known troll as absolutely true, despite my experience to the contrary.

    You have experience with trolls or with submarines? Or with not accepting bold statements? This is confusing.

    By the way I dispute the implied accusation that I am a troll as well as your legitimacy in declaring who is or is not a "known troll".


  • Discourse touched me in a no-no place

    @Xyro said:

    @Speakerphone Dude said:
    This is how it's done on submarines. You should call the navy and let them know it's a bad practice.
    I will accept this bold statement from a known troll as absolutely true, despite my experience to the contrary.
    Obvious troll-idiot is obvious, as the meme goes. The fact that a simple google search disproves its assertion of the benifits of running electricity through pipes conducting water seems to elude it.



  • @Lorne Kates said:

     If performance is important, you put this in a lookup table. That way you don't have to recalculate it all on the fly!

    If accuracy is important, then you don't measure the number. Everyone knows that odd numbers take longer to calculate than even numbers. So you do a calculation on both X and X-1. If it takes longer to do the calulation on X, then the number is odd. If it takes less time, then it is even.

    And you can't trust those datetime libraries. You measure the latency of the electrons across the wire. It's the only way to be sure.

    Here is a demo that using a try-catch is indeed faster than a IF:



  • @Speakerphone Dude said:

    @Lorne Kates said:

     If performance is important, you put this in a lookup table. That way you don't have to recalculate it all on the fly!

    If accuracy is important, then you don't measure the number. Everyone knows that odd numbers take longer to calculate than even numbers. So you do a calculation on both X and X-1. If it takes longer to do the calulation on X, then the number is odd. If it takes less time, then it is even.

    And you can't trust those datetime libraries. You measure the latency of the electrons across the wire. It's the only way to be sure.

    Here is a demo that using a try-catch is indeed faster than a IF:

    QE-fucking-D



  • @PJH said:

    @Xyro said:
    @Speakerphone Dude said:
    This is how it's done on submarines. You should call the navy and let them know it's a bad practice.
    I will accept this bold statement from a known troll as absolutely true, despite my experience to the contrary.
    Obvious troll-idiot is obvious, as the meme goes. The fact that a simple google search disproves its assertion of the benifits of running electricity through pipes conducting water seems to elude it.

    You could look for the TS9090-310E/SL720-AA-MAN-030 document, section 6, requirement h. Or find anyone with experience at the NAVSEA 04XQ. But of course it's easier to call someone a troll and/or an idiot because you are not computer-savvy enough to use google properly.



  • Does this count?

    check(X, even) :- 0 is mod(X, 2), !.
    check(_, odd).
     
    ?- check(2, Y), print(Y), nl.
    ?- check(3, Y), print(Y), nl.



  • how's this?


    #include <string>
    #include <vector>
    using namespace std;


    string OddEven(int x)

        vector<string> possibilities;
        int correctChoice

        possibilities.push_back("Even");
        possibilities.push_back("Odd");

        for (int i = 0; i <= x; i++){
            correctChoice = i % possibilities.size();   
        }   

        return possibilities[correctChoice];
    }


  • Discourse touched me in a no-no place

    @Admiral Snackbar said:

    how's this?
    Fails, since it doesn't adhere to the requirements set...
    @Admiral Snackbar said:
        for (int i = 0; i <= x; i++){
    You're using a conditional statement there.



  • String compares? That is not sense. The best way to to even/odd without conditional is just to do something like (x&1) in a C code



  • @zzo38 said:

    String compares? That is not sense. The best way to to even/odd without conditional is just to do something like (x&1) in a C code
    You must be new he– oh wait



  • I think you're just being pedantic, since that's a conditional loop, not a conditional statement, but you could easily replace

    for (int i = 0; i <= x; i++){
    correctChoice = i % possibilities.size();
    }  

    with

    correctChoice = x % possibilities.size();

    The only probem there is that if the process gets interrupted, you can't just pick up where you left off - you have to start all over.



  • @Speakerphone Dude said:

    You could look for the TS9090-310E/SL720-AA-MAN-030 document, section 6, requirement h. Or find anyone with experience at the NAVSEA 04XQ. But of course it's easier to call someone a troll and/or an idiot because you are not computer-savvy enough to use google properly.

    Neither this, nor the 310F which superseded it contain section 6...



  • @bannedfromcoding said:

    @Speakerphone Dude said:
    You could look for the TS9090-310E/SL720-AA-MAN-030 document, section 6, requirement h. Or find anyone with experience at the NAVSEA 04XQ. But of course it's easier to call someone a troll and/or an idiot because you are not computer-savvy enough to use google properly.

    Neither this, nor the 310F which superseded it contain section 6...

    I see, you googled the document name and had a quick glance at the table of contents of the pdf you got in the first few results. Outstanding research, you should send your resume to the IPCC.

    Meanwhile, if my understanding of your process is correct, you are looking at the checklist document (MOA template), not the detailed specifications. Which means that the information you are looking for is probably in the appendix under one of the checklists but it won't contain more than just validating that it's done.


  • Discourse touched me in a no-no place

    @Admiral Snackbar said:

    I think you're just being pedantic, since that's a conditional loop, not a conditional statement,
    Look, if you're even bothering to entertain the notion that the subject of this thread is even worth any time spent on it, you cannot simply pick and choose whether or not you think a conditional is a conditional or not simply by how you're using that conditional.


Log in to reply