Programming Puzzle

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jatinder

    Programming Puzzle

    I found these questions on a web site and wish to share with all of u
    out there,Can SomeOne Solve these Porgramming puzzles.


    Programming Puzzles

    Some companies certainly ask for these things. Specially Microsoft.
    Here are my favorite puzzles. Don't send me emails asking for the
    solutions.

    Q1 Write a "Hello World" program in 'C' without using a semicolon.
    Q2 Write a C++ program without using any loop (if, for, while etc) to
    print numbers from 1 to 100 and 100 to 1;
    Q3 C/C++ : Exchange two numbers without using a temporary variable.
    Q4 C/C++ : Find if the given number is a power of 2.
    Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
    Q6 C/C++ : Write a function in different ways that will return f(7) =
    4 and f(4) = 7
    Q7 Remove duplicates in array
    Q8 Finding if there is any loop inside linked list.
    Q9 Remove duplicates in an no key access database without using an
    array
    Q10 Write a program whose printed output is an exact copy of the
    source. Needless to say, merely echoing the actual source file is not
    allowed.
    Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
    each player selects a number and adds it to the total. Once a number
    is used, it must be removed from the pool. The winner is the person
    whose number makes the total equal 31 exactly.
    Q12 Swap two numbers without using a third variable.
    Given an array (group) of numbers write all the possible sub groups of
    this group.
    Q14 Convert (integer) number in binary without loops.

    Q3,12 are similar , Q7 is simple & I know there answer For the Rest
    please Help


    Wiating for reply.
  • Joona I Palaste

    #2
    Re: Programming Puzzle

    Jatinder <jsfromynr@sanc harnet.in> scribbled the following
    on comp.lang.c:[color=blue]
    > I found these questions on a web site and wish to share with all of u
    > out there,Can SomeOne Solve these Porgramming puzzles.[/color]
    [color=blue]
    > Programming Puzzles[/color]
    [color=blue]
    > Some companies certainly ask for these things. Specially Microsoft.
    > Here are my favorite puzzles. Don't send me emails asking for the
    > solutions.[/color]
    [color=blue]
    > Q1 Write a "Hello World" program in 'C' without using a semicolon.
    > Q2 Write a C++ program without using any loop (if, for, while etc) to
    > print numbers from 1 to 100 and 100 to 1;
    > Q3 C/C++ : Exchange two numbers without using a temporary variable.[/color]

    Done to death here on comp.lang.c.
    [color=blue]
    > Q4 C/C++ : Find if the given number is a power of 2.[/color]

    Easy with some bitwise arithmetic.
    [color=blue]
    > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.[/color]

    Easy peasy. Repeated addition will do the trick.
    [color=blue]
    > Q6 C/C++ : Write a function in different ways that will return f(7) =
    > 4 and f(4) = 7[/color]

    int f(int x) {
    return x==4 ? 7 : x==7 ? 4 : 0;
    }
    [color=blue]
    > Q7 Remove duplicates in array[/color]

    You can't remove anything from an array. You can only modify the
    values of its elements.
    [color=blue]
    > Q8 Finding if there is any loop inside linked list.[/color]

    Should be covered in any basic data structures course.
    [color=blue]
    > Q9 Remove duplicates in an no key access database without using an
    > array[/color]

    Impossible without access into a no key access database.
    [color=blue]
    > Q10 Write a program whose printed output is an exact copy of the
    > source. Needless to say, merely echoing the actual source file is not
    > allowed.[/color]

    Google for "quine".
    [color=blue]
    > Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
    > each player selects a number and adds it to the total. Once a number
    > is used, it must be removed from the pool. The winner is the person
    > whose number makes the total equal 31 exactly.[/color]

    This one is actually a full-blown game.
    [color=blue]
    > Q12 Swap two numbers without using a third variable.[/color]

    And how is this any different from Q3?
    [color=blue]
    > Given an array (group) of numbers write all the possible sub groups of
    > this group.[/color]

    Search for the definition of a "power set". The algorithm shoudln't be
    too hard to figure out.
    [color=blue]
    > Q14 Convert (integer) number in binary without loops.[/color]

    Already done here on comp.lang.c.

    --
    /-- Joona Palaste (palaste@cc.hel sinki.fi) ------------- Finland --------\
    \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
    "This isn't right. This isn't even wrong."
    - Wolfgang Pauli

    Comment

    • Christian Bau

      #3
      Re: Programming Puzzle

      In article <22b2a6b6.04062 61016.510e693b@ posting.google. com>,
      jsfromynr@sanch arnet.in (Jatinder) wrote:
      [color=blue]
      > I found these questions on a web site and wish to share with all of u
      > out there,Can SomeOne Solve these Porgramming puzzles.
      >
      >
      > Programming Puzzles
      >
      > Some companies certainly ask for these things. Specially Microsoft.
      > Here are my favorite puzzles. Don't send me emails asking for the
      > solutions.
      >
      > Q1 Write a "Hello World" program in 'C' without using a semicolon.
      > Q2 Write a C++ program without using any loop (if, for, while etc) to
      > print numbers from 1 to 100 and 100 to 1;
      > Q3 C/C++ : Exchange two numbers without using a temporary variable.
      > Q4 C/C++ : Find if the given number is a power of 2.
      > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
      > Q6 C/C++ : Write a function in different ways that will return f(7) =
      > 4 and f(4) = 7
      > Q7 Remove duplicates in array
      > Q8 Finding if there is any loop inside linked list.
      > Q9 Remove duplicates in an no key access database without using an
      > array
      > Q10 Write a program whose printed output is an exact copy of the
      > source. Needless to say, merely echoing the actual source file is not
      > allowed.
      > Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
      > each player selects a number and adds it to the total. Once a number
      > is used, it must be removed from the pool. The winner is the person
      > whose number makes the total equal 31 exactly.
      > Q12 Swap two numbers without using a third variable.
      > Given an array (group) of numbers write all the possible sub groups of
      > this group.
      > Q14 Convert (integer) number in binary without loops.
      >
      > Q3,12 are similar , Q7 is simple & I know there answer For the Rest
      > please Help[/color]

      Assuming that these questions are from an interview for a programming
      job, I must say that most of them are incredibly useless at finding a
      good programmer. Take Q3: The correct answer is: Why would anyone want
      to do that? Take Q10: You know the answer or you don't. If your name is
      Gödel or Turing, you might find a solution on your own, but otherwise
      this just tests some very obscure knowledge. I guess these questions are
      only used to check your reaction to a stressful situation (which is also
      an incredibly useless way at finding a good programmer).

      If I was given this list of questions, I would tell them that most of
      them are pointless and then examine Q11, because it is the only
      interesting one. Maybe a different response if you are desperate for a
      job.

      Comment

      • Siemel Naran

        #4
        Re: Programming Puzzle

        "Joona I Palaste" <palaste@cc.hel sinki.fi> wrote in message news:cbkf50$a76[color=blue]
        > Jatinder <jsfromynr@sanc harnet.in> scribbled the following[/color]
        [color=blue][color=green]
        > > Q1 Write a "Hello World" program in 'C' without using a semicolon.
        > > Q2 Write a C++ program without using any loop (if, for, while etc) to
        > > print numbers from 1 to 100 and 100 to 1;
        > > Q3 C/C++ : Exchange two numbers without using a temporary variable.[/color]
        >
        > Done to death here on comp.lang.c.[/color]

        Not familiar with the first two. Q1, how? Is #define SEMICOLON ; valid?
        Q2, is recursion a valid answer? Or even just writing the numbers
        explicitly printf("1\n2"), etc? For Q3 one can use ^= 3 times, though I
        wonder if this is faster than the usual one with a temp variable and 3
        assignments on various platforms.
        [color=blue][color=green]
        > > Q4 C/C++ : Find if the given number is a power of 2.[/color]
        >
        > Easy with some bitwise arithmetic.[/color]

        x & (x-1) evaluates to zero if the number is an exact power of 2.
        [color=blue][color=green]
        > > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.[/color]
        >
        > Easy peasy. Repeated addition will do the trick.
        >[color=green]
        > > Q6 C/C++ : Write a function in different ways that will return f(7) =
        > > 4 and f(4) = 7[/color]
        >
        > int f(int x) {
        > return x==4 ? 7 : x==7 ? 4 : 0;
        > }[/color]

        Another is realize 4 = %100 and 7 = %111 in binary, so leave the leftmost
        bit on, and flip the other 2. Thus: return x ^ %11, or return x ^ 3.
        [color=blue][color=green]
        > > Q7 Remove duplicates in array[/color]
        >
        > You can't remove anything from an array. You can only modify the
        > values of its elements.[/color]

        Fine, then how to replace the duplicates with NULL or the like, or move the
        elements one down so that { 1, 2, 1, 1, 4, 3 } becomes { 1, 2, 4, 3,
        anything, anything }?
        [color=blue][color=green]
        > > Q8 Finding if there is any loop inside linked list.[/color]
        >
        > Should be covered in any basic data structures course.
        >[color=green]
        > > Q9 Remove duplicates in an no key access database without using an
        > > array[/color]
        >
        > Impossible without access into a no key access database.[/color]

        What is Q9 about?
        [color=blue][color=green]
        > > Q10 Write a program whose printed output is an exact copy of the
        > > source. Needless to say, merely echoing the actual source file is not
        > > allowed.[/color]
        >
        > Google for "quine".[/color]

        Bizarre stuff!
        [color=blue][color=green]
        > > Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
        > > each player selects a number and adds it to the total. Once a number
        > > is used, it must be removed from the pool. The winner is the person
        > > whose number makes the total equal 31 exactly.[/color]
        >
        > This one is actually a full-blown game.
        >[color=green]
        > > Q12 Swap two numbers without using a third variable.[/color]
        >
        > And how is this any different from Q3?
        >[color=green]
        > > Given an array (group) of numbers write all the possible sub groups of
        > > this group.[/color]
        >
        > Search for the definition of a "power set". The algorithm shoudln't be
        > too hard to figure out.[/color]

        Someone posted something like this in the C++ newsgroup. If you have 3
        numbers 1, 2, 3 then make a number of 3 bits %000. Then just add 1 until
        you max out. So you get %000, %001, %010, %011, %100, %101, %110, %111. If
        the bit is 0 it means that number is not in the group and if the bit it 1 it
        means the number is in the group, so %001 is the group "1", and %011 is the
        group "1,2", and %101 is the group "1,3". In C++ you could maybe use
        std::bitset.

        But I think you could do it using recursion too. So f(3,1) prints the
        combinations "3,..." and f(3,0) prints combinations without the 3. The part
        in ... is the combinations with 2 numbers, so f(2,1) prints "2,..." and
        f(2,0) prints "...". The second ... is the combinations with 1 numbers,
        just "1" and "".
        [color=blue][color=green]
        > > Q14 Convert (integer) number in binary without loops.[/color]
        >
        > Already done here on comp.lang.c.[/color]

        How, if not recursion? Maybe even lookup tables, which I used to implement
        a fast lgdown(x) function which gives log to base 2 of x.


        Comment

        • Allan Bruce

          #5
          Re: Programming Puzzle


          "Siemel Naran" <SiemelNaran@RE MOVE.att.net> wrote in message
          news:bgnDc.3221 3$OB3.24647@bgt nsc05-news.ops.worldn et.att.net...[color=blue]
          > "Joona I Palaste" <palaste@cc.hel sinki.fi> wrote in message[/color]
          news:cbkf50$a76[color=blue][color=green]
          > > Jatinder <jsfromynr@sanc harnet.in> scribbled the following[/color]
          >[color=green][color=darkred]
          > > > Q1 Write a "Hello World" program in 'C' without using a semicolon.
          > > > Q2 Write a C++ program without using any loop (if, for, while etc) to
          > > > print numbers from 1 to 100 and 100 to 1;
          > > > Q3 C/C++ : Exchange two numbers without using a temporary variable.[/color]
          > >
          > > Done to death here on comp.lang.c.[/color]
          >
          > Not familiar with the first two. Q1, how? Is #define SEMICOLON ; valid?[/color]

          no, but consider this

          int main (void)
          {
          if (printf("Hello World"))
          {}

          if (exit(EXIT_SUCC ESS))
          {}
          }

          Allan


          Comment

          • Dale Henderson

            #6
            Re: Programming Puzzle

            >>>>> "Jatinder" == Jatinder <jsfromynr@sanc harnet.in> writes:

            Jatinder> I found these questions on a web site and wish to share
            Jatinder> with all of u out there,Can SomeOne Solve these
            Jatinder> Porgramming puzzles.


            Jatinder> Programming Puzzles

            Jatinder> Some companies certainly ask for these things. Specially
            Jatinder> Microsoft. Here are my favorite puzzles. Don't send me
            Jatinder> emails asking for the solutions.

            Jatinder> Q1 Write a "Hello World" program in 'C' without using a
            Jatinder> semicolon.

            Jatinder> Q2 Write a C++ program without using any loop (if, for,
            Jatinder> while etc) to print numbers from 1 to 100 and 100 to 1;

            void countup(int i){
            printf("%d\n",i );
            (void) ((i<100)?countu p(i+1):i);
            }
            countup(1);

            countdown is left as an excercise ;)

            This is C. I'm reading this in comp.lang.c. C++ is offtopic

            Jatinder> Q3 C/C++ : Exchange two numbers without using a
            Jatinder> temporary variable.

            This is a FAQ. There is no good way. (20.15c)

            Jatinder> Q4 C/C++ : Find if the given number is a power of 2.

            I'd like to know the answer to this one myself.

            Jatinder> Q5 C/C++ : Multiply x by 7 without using multiplication
            Jatinder> (*) operator.

            x<<3-x;
            this only works if x is unsigned.

            Jatinder> Q6 C/C++ : Write a function in different ways that will
            Jatinder> return f(7) = 4 and f(4) = 7

            int f(int i){
            return i^3;
            }

            Jatinder> Q7 Remove duplicates in array

            Jatinder> Q8 Finding if there is any loop inside linked list.

            This is similar to Q7. Your looking for duplicate pointer values.

            Jatinder> Q9 Remove duplicates in an no key access database
            Jatinder> without using an array

            Jatinder> Q10 Write a program whose printed output is an exact
            Jatinder> copy of the source. Needless to say, merely echoing the
            Jatinder> actual source file is not allowed.

            This is a FAQ. 20.34

            Jatinder> Q11 From a 'pool' of numbers (four '1's, four '2's
            Jatinder> .... four '6's), each player selects a number and adds
            Jatinder> it to the total. Once a number is used, it must be
            Jatinder> removed from the pool. The winner is the person whose
            Jatinder> number makes the total equal 31 exactly.

            Jatinder> Q12 Swap two numbers without using a third variable.
            See Q3

            Jatinder> Given an array (group) of numbers write all the possible
            Jatinder> sub groups of this group.

            Jatinder> Q14 Convert (integer) number in binary without loops.

            Jatinder> Q3,12 are similar , Q7 is simple & I know there answer
            Jatinder> For the Rest please Help

            I'd say Q3 and Q12 are identical.

            Jatinder> Wiating for reply.

            --
            Dale Henderson

            "Imaginary universes are so much more beautiful than this stupidly-
            constructed 'real' one..." -- G. H. Hardy

            Comment

            • CBFalconer

              #7
              Re: Programming Puzzle

              Allan Bruce wrote:[color=blue]
              >[/color]
              .... snip ...[color=blue]
              >
              > no, but consider this
              >
              > int main (void)
              > {
              > if (printf("Hello World"))
              > {}
              > if (exit(EXIT_SUCC ESS))
              > {}
              > }[/color]

              Illegal. No #include for prototype of variadic function, nor
              EXIT_SUCCESS value, and exit is a void function. The compiler
              should barf.

              I am trying to construct something that revolves around:

              if (printf("Hello ") - printf("World\n ")) {...}

              which statement could cause either "Hello World" or "WorldHello ".

              --
              Chuck F (cbfalconer@yah oo.com) (cbfalconer@wor ldnet.att.net)
              Available for consulting/temporary embedded and systems.
              <http://cbfalconer.home .att.net> USE worldnet address!


              Comment

              • Mabden

                #8
                Re: Programming Puzzle

                "Christian Bau" <christian.bau@ cbau.freeserve. co.uk> wrote in message
                news:christian. bau-1DB1E2.19382526 062004@slb-newsm1.svr.pol. co.uk...[color=blue]
                > In article <22b2a6b6.04062 61016.510e693b@ posting.google. com>,
                > jsfromynr@sanch arnet.in (Jatinder) wrote:
                >[color=green]
                > >
                > > Programming Puzzles
                > >
                > > Some companies certainly ask for these things. Specially Microsoft.
                > > Here are my favorite puzzles. Don't send me emails asking for the
                > > solutions.
                > >
                > > Q1 Write a "Hello World" program in 'C' without using a semicolon.
                > > Q2 Write a C++ program without using any loop (if, for, while etc) to
                > > print numbers from 1 to 100 and 100 to 1;
                > > Q3 C/C++ : Exchange two numbers without using a temporary variable.[/color][/color]

                [snip]
                [color=blue]
                >
                > If I was given this list of questions, I would tell them that most of
                > them are pointless and then examine Q11, because it is the only
                > interesting one. Maybe a different response if you are desperate for a
                > job.[/color]

                Maybe you would get the job for walking out...


                Comment

                • Siemel Naran

                  #9
                  Re: Programming Puzzle

                  "Mabden" <mabden@sbc_glo bal.net> wrote in message news:B5uDc.6258
                  [color=blue]
                  > Maybe you would get the job for walking out...[/color]

                  That might be too out of the box :).


                  Comment

                  • Jerry Coffin

                    #10
                    Re: Programming Puzzle

                    jsfromynr@sanch arnet.in (Jatinder) wrote in message news:<22b2a6b6. 0406261016.510e 693b@posting.go ogle.com>...

                    [ ... ]
                    [color=blue]
                    > Q1 Write a "Hello World" program in 'C' without using a semicolon.[/color]

                    One obvious method (open to a number of variations) is:

                    #include <stdio.h>

                    int main() {
                    if ( printf("Hello world"))
                    {}
                    }
                    [color=blue]
                    > Q2 Write a C++ program without using any loop (if, for, while etc) to
                    > print numbers from 1 to 100 and 100 to 1;[/color]

                    Almost anything you'd normally do with iteration can also be done with
                    tail recursion.
                    [color=blue]
                    > Q3 C/C++ : Exchange two numbers without using a temporary variable.[/color]

                    This has come up about 4 weeks into every new semester for years, with
                    a slightly lighter treatment on a quarterly basis.
                    [color=blue]
                    > Q4 C/C++ : Find if the given number is a power of 2.[/color]

                    There are many ways. Pick N as a power of 2, and compare it to N-1
                    and see if something doesn't occur to you.
                    [color=blue]
                    > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.[/color]

                    One is to just add x together 7 times. Those of us who remember
                    writing multiplication routines for old processors that didn't have
                    multiply instructions can easily reduce that to (x<<2)|(x<<1)|x .
                    Those who've studied Booth's algorithm might try (x<<3)-x, though
                    without extra bits for the intermediate value, this can overflow.
                    [color=blue]
                    > Q6 C/C++ : Write a function in different ways that will return f(7) =
                    > 4 and f(4) = 7[/color]

                    Obvious:
                    int f(int x) {
                    if ( x == 7)
                    return 4;
                    if ( x == 4)
                    return 7;
                    }
                    Roughly as obvious is to use switch/case intsead.

                    Using arrays, you can do things like:

                    int f(int x) {
                    int rets[] = { 4, 7};
                    return rets[x>>2];
                    }

                    Or if you want to ensure defined results for inputs other than 4 or 7:

                    int f(int x) {
                    int rets[] = {4,7};
                    return rets[(x>>2)&1];
                    }

                    If you want to get clever with boolean values, you could try:

                    int f(int x) {
                    return (x==7*4)+(x==4* 7);
                    }

                    or:

                    int f(int x) {
                    rturn (x==7*4)|(x==4* 7);
                    }

                    If you prefer strictly bit-wise manipulation, you might prefer:

                    int f(int x) {
                    return x ^ 3;
                    }

                    I'm sure there are more variations as well.
                    [color=blue]
                    > Q7 Remove duplicates in array[/color]

                    You can't really "remove" an element from an array, so this is poorly
                    defined. If it was a C++ vector (for example) std::sort and
                    std::unique would render it trivial, as would inserting the elements
                    into an std::set, and then copying them back out. Doing it quickly
                    while retaining the original order is a little more challenging.
                    [color=blue]
                    > Q8 Finding if there is any loop inside linked list.[/color]

                    One obvious way would be to create a set of pointers to nodes. Walk
                    the list, inserting each node's address into the set. Quit when you
                    reach a node with next == NULL (there's no loop) or a node whose
                    address is already in the set (there's a loop).

                    There's an alternative that saves memory, but basically destroys the
                    list if it does contain a loop: as you walk the list, modify each
                    'next' pointer to point at the previous node. Eventually, you'll
                    reach either a node with next==NULL, in which case there's no loop, or
                    else you'll get back to the original head of the list (in which case
                    there's a loop, and you've wreaked havoc on your list). If the list
                    doesn't contain a loop, you can re-walk it, again reversing each
                    pointer, to restore the original list.

                    Better yet, just ensure the list is constructed sanely, and you'll
                    know the answer up-front.
                    [color=blue]
                    > Q10 Write a program whose printed output is an exact copy of the
                    > source. Needless to say, merely echoing the actual source file is not
                    > allowed.[/color]

                    Much like Q3, but comes up a little further into the semster/quarter.
                    [color=blue]
                    > Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
                    > each player selects a number and adds it to the total. Once a number
                    > is used, it must be removed from the pool. The winner is the person
                    > whose number makes the total equal 31 exactly.[/color]

                    If I'm figuring this correctly, it's a pretty boring game. If I go
                    first, I pick '1' on my first two moves, and you can't win. If I go
                    second, I pick '2' on my first three moves, and you can't win.

                    Tic-tac-toe quickly gets boring because neither player can win unless
                    his opponent makes a mistake. This is even worse, because the same is
                    true, BUT a player doesn't even have to look at what his opponent has
                    done to avoid a mistake. The only challenge is ensuring that you take
                    advantage when he does make a mistake, and (again, assuming I'm
                    figuring things correctly) that should be quite trivial.
                    [color=blue]
                    > Given an array (group) of numbers write all the possible sub groups of
                    > this group.[/color]

                    Recursion is probably your friend on this one as well.

                    [color=blue]
                    > Q14 Convert (integer) number in binary without loops.[/color]

                    As mentioned wrt Q2, almost any iteration is trivially expressed as
                    tail recursion. The wording doesn't make it clear whether this is
                    supposed to be a conversion FROM binary or TO binary, but either is
                    pretty easy to do recursively.

                    --
                    Later,
                    Jerry.

                    The universe is a figment of its own imagination.

                    Comment

                    • Siemel Naran

                      #11
                      Re: Programming Puzzle

                      "Jerry Coffin" <jcoffin@taeus. com> wrote in message
                      news:b2e4b04.04 06262349.465369 ca@posting.goog le.com...
                      [color=blue]
                      > Almost anything you'd normally do with iteration can also be done with
                      > tail recursion.[/color]

                      What is "tail" recursion? Are there other types of recursion?

                      Any the question says not to use loops. But to me, recursion is a loop,
                      just expressed differently.
                      [color=blue][color=green]
                      > > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.[/color]
                      >
                      > One is to just add x together 7 times. Those of us who remember
                      > writing multiplication routines for old processors that didn't have
                      > multiply instructions can easily reduce that to (x<<2)|(x<<1)|x .
                      > Those who've studied Booth's algorithm might try (x<<3)-x, though
                      > without extra bits for the intermediate value, this can overflow.[/color]

                      Are these methods faster than x*7 on modern processors?
                      [color=blue][color=green]
                      > > Q6 C/C++ : Write a function in different ways that will return f(7) =
                      > > 4 and f(4) = 7[/color][/color]
                      [color=blue]
                      > If you want to get clever with boolean values, you could try:
                      >
                      > int f(int x) {
                      > return (x==7*4)+(x==4* 7);
                      > }[/color]

                      Huh?
                      [color=blue]
                      > I'm sure there are more variations as well.[/color]

                      Probably something with mod or %.
                      [color=blue][color=green]
                      > > Q7 Remove duplicates in array[/color]
                      >
                      > You can't really "remove" an element from an array, so this is poorly
                      > defined. If it was a C++ vector (for example) std::sort and
                      > std::unique would render it trivial, as would inserting the elements
                      > into an std::set, and then copying them back out. Doing it quickly
                      > while retaining the original order is a little more challenging.[/color]

                      The sort method is O(N*lg(N)) + O(N) if we use comparison sort. But doing
                      it in place without changing the order seems to be an O(N^2) algorithm, with
                      the outer loop i running from [0, N) and the inner loop j running from [0,
                      i). (Seems most people run the inner loop from [i+1, N) and then they run
                      into problems of how to detect if you've not seen the element already.)
                      [color=blue][color=green]
                      > > Q8 Finding if there is any loop inside linked list.[/color]
                      >
                      > One obvious way would be to create a set of pointers to nodes. Walk
                      > the list, inserting each node's address into the set. Quit when you
                      > reach a node with next == NULL (there's no loop) or a node whose
                      > address is already in the set (there's a loop).
                      >
                      > There's an alternative that saves memory, but basically destroys the
                      > list if it does contain a loop: as you walk the list, modify each
                      > 'next' pointer to point at the previous node. Eventually, you'll
                      > reach either a node with next==NULL, in which case there's no loop, or
                      > else you'll get back to the original head of the list (in which case
                      > there's a loop, and you've wreaked havoc on your list). If the list
                      > doesn't contain a loop, you can re-walk it, again reversing each
                      > pointer, to restore the original list.
                      >
                      > Better yet, just ensure the list is constructed sanely, and you'll
                      > know the answer up-front.[/color]

                      There's another. Have two iterators, first one pointing to first element,
                      the second pointing to the second. The second one is the fast iterator and
                      you increment it twice in each iteration. The first iterator is the slow
                      iterator and you increment it once in each iteration. If the list is not
                      circular the fast iterator will hit NULL at some point. If the list is
                      circular the fast iterator will equal to the slow iterator at some point.


                      Comment

                      • Joona I Palaste

                        #12
                        Re: Programming Puzzle

                        Siemel Naran <SiemelNaran@re move.att.net> scribbled the following
                        on comp.lang.c:[color=blue]
                        > "Jerry Coffin" <jcoffin@taeus. com> wrote in message
                        > news:b2e4b04.04 06262349.465369 ca@posting.goog le.com...[color=green]
                        >> Almost anything you'd normally do with iteration can also be done with
                        >> tail recursion.[/color][/color]
                        [color=blue]
                        > What is "tail" recursion? Are there other types of recursion?[/color]

                        Tail recursion is first doing the computation, then recursing. Head
                        recursion is the other way around.
                        [color=blue]
                        > Any the question says not to use loops. But to me, recursion is a loop,
                        > just expressed differently.[/color]

                        They're clearly different concepts. At least in C, recursion has a
                        separate local scope for all levels, while looping reuses the same
                        local scope for all iterations.
                        [color=blue][color=green][color=darkred]
                        >> > Q6 C/C++ : Write a function in different ways that will return f(7) =
                        >> > 4 and f(4) = 7[/color][/color][/color]
                        [color=blue][color=green]
                        >> If you want to get clever with boolean values, you could try:
                        >>
                        >> int f(int x) {
                        >> return (x==7*4)+(x==4* 7);
                        >> }[/color][/color]
                        [color=blue]
                        > Huh?[/color]

                        In C, the == operator returns 1 if the operands match or 0 if they
                        don't. Go from there.

                        --
                        /-- Joona Palaste (palaste@cc.hel sinki.fi) ------------- Finland --------\
                        \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
                        "The day Microsoft makes something that doesn't suck is probably the day they
                        start making vacuum cleaners."
                        - Ernst Jan Plugge

                        Comment

                        • Irrwahn Grausewitz

                          #13
                          Re: Programming Puzzle

                          "Siemel Naran" <SiemelNaran@RE MOVE.att.net> wrote:[color=blue]
                          >"Jerry Coffin" <jcoffin@taeus. com> wrote in message
                          >news:b2e4b04.0 406262349.46536 9ca@posting.goo gle.com...[/color]
                          <snip>[color=blue][color=green][color=darkred]
                          >> > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.[/color][/color][/color]
                          <snip>[color=blue][color=green]
                          >> If you want to get clever with boolean values, you could try:
                          >>
                          >> int f(int x) {
                          >> return (x==7*4)+(x==4* 7);
                          >> }[/color]
                          >
                          >Huh?[/color]

                          I'm pretty sure Jerry meant to write:

                          return (x==7)*4 + (x==4)*7;

                          Regards
                          --
                          Irrwahn Grausewitz (irrwahn33@free net.de)
                          welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
                          clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
                          clc OT guide : http://benpfaff.org/writings/clc/off-topic.html

                          Comment

                          • Irrwahn Grausewitz

                            #14
                            Re: Programming Puzzle

                            Joona I Palaste <palaste@cc.hel sinki.fi> wrote:[color=blue]
                            >Siemel Naran <SiemelNaran@re move.att.net> scribbled the following
                            >on comp.lang.c:[color=green]
                            >> "Jerry Coffin" <jcoffin@taeus. com> wrote in message
                            >> news:b2e4b04.04 06262349.465369 ca@posting.goog le.com...[/color][/color]
                            [color=blue][color=green][color=darkred]
                            >>> > Q6 C/C++ : Write a function in different ways that will return f(7) =
                            >>> > 4 and f(4) = 7[/color][/color]
                            >[color=green][color=darkred]
                            >>> If you want to get clever with boolean values, you could try:
                            >>>
                            >>> int f(int x) {
                            >>> return (x==7*4)+(x==4* 7);
                            >>> }[/color][/color]
                            >[color=green]
                            >> Huh?[/color]
                            >
                            >In C, the == operator returns 1 if the operands match or 0 if they
                            >don't. Go from there.[/color]

                            Now f returns 2 if x equals 28, or 0 otherwise. Great solution. ;-)

                            Regards
                            --
                            Irrwahn Grausewitz (irrwahn33@free net.de)
                            welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
                            clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
                            clc OT guide : http://benpfaff.org/writings/clc/off-topic.html

                            Comment

                            • Joona I Palaste

                              #15
                              Re: Programming Puzzle

                              Irrwahn Grausewitz <irrwahn33@free net.de> scribbled the following
                              on comp.lang.c:[color=blue]
                              > "Siemel Naran" <SiemelNaran@RE MOVE.att.net> wrote:[color=green]
                              >>"Jerry Coffin" <jcoffin@taeus. com> wrote in message
                              >>news:b2e4b04. 0406262349.4653 69ca@posting.go ogle.com...[/color]
                              > <snip>[color=green][color=darkred]
                              >>> > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.[/color][/color]
                              > <snip>[color=green][color=darkred]
                              >>> If you want to get clever with boolean values, you could try:
                              >>>
                              >>> int f(int x) {
                              >>> return (x==7*4)+(x==4* 7);
                              >>> }[/color]
                              >>
                              >>Huh?[/color][/color]
                              [color=blue]
                              > I'm pretty sure Jerry meant to write:[/color]
                              [color=blue]
                              > return (x==7)*4 + (x==4)*7;[/color]

                              Dang! I didn't spot that in my original reply. Jerry's original code is
                              equivalent to return (x==28)+(x==28) , which will return 2 if x==28 but
                              0 if not.

                              --
                              /-- Joona Palaste (palaste@cc.hel sinki.fi) ------------- Finland --------\
                              \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
                              "You can pick your friends, you can pick your nose, but you can't pick your
                              relatives."
                              - MAD Magazine

                              Comment

                              Working...