Computer Science Canada

Test your skills (2005)

Author:  wtd [ Sat Jan 01, 2005 5:01 pm ]
Post subject:  Test your skills (2005)

I figure a new year calls for a new tradition. So, as I come up with questions, I'll post them here, and invite others to PM answers to me within the next week. 20 bits to anyone who can answer correctly. Smile

So, the first question is a Ruby question.

Why does the first print

code:
[2, 4, 6]


to the screen, and the second print

code:
[1, 2, 3]


The code:

code:
p [1, 2, 3].collect { |x| x * 2 }


code:
p [1, 2, 3].collect do |x| x * 2 end

Author:  MihaiG [ Sat Jan 01, 2005 5:26 pm ]
Post subject: 

can you post something for VB or turing?

Author:  wtd [ Sat Jan 01, 2005 6:18 pm ]
Post subject: 

Possibly, though I'll admit to not being fond of either of those languages.

Author:  Acid [ Sat Jan 01, 2005 7:00 pm ]
Post subject: 

Could you post some C++ too?

Not like I'll get the question anyway...

Author:  wtd [ Sat Jan 01, 2005 7:07 pm ]
Post subject:  C++ skills test (1/1/05 - 1/7/05)

I write the following program and compile it with a modern C++ compiler (GCC 3.3):

code:
#include <iostream.h>

main()
{
   cout << "Hello world!" << endl;
}


It compiles and runs, but I've made four mistakes. Name them. 5 bits for each mistake.

Author:  wtd [ Sat Jan 01, 2005 10:02 pm ]
Post subject: 

Private message, please, so multiple people can answer the question. Smile

I'll post answers at the end of the week.

Author:  Hikaru79 [ Sun Jan 02, 2005 1:42 am ]
Post subject: 

Hey, sweet idea, wtd Smile Hopefully this'll turn into a long-standing tradition at compsci.ca

Can anyone chip in with their own questions, or only the thread owner?

PS: You're very close to 1337 posts Wink I wanna take a screenshot when that happens!

Author:  wtd [ Sun Jan 02, 2005 10:00 pm ]
Post subject: 

Hikaru79 wrote:
Hey, sweet idea, wtd Smile Hopefully this'll turn into a long-standing tradition at compsci.ca

Can anyone chip in with their own questions, or only the thread owner?

PS: You're very close to 1337 posts Wink I wanna take a screenshot when that happens!


You can chip in, but if you're going to award bits, they have to be your bits. Smile

A general suggesion: questions should ask questions that don't get asked much. Like the C++ question, "this works, but what am I doing wrong?" or "not just does this work, but why does it work that way?"

Author:  wtd [ Mon Jan 03, 2005 3:53 pm ]
Post subject:  Haskell challenge (1/3/05 - 1/9/05)

Write a program which prompts for the user's name and accepts it on a single line, then greets the user in all caps. A sample run might look like:

code:
You are? Simon
HELLO SIMON!  SORRY FOR YELLING!!!


Reference material:

http://www.haskell.org
http://www.familygeek.com/haskell/tutorial.html

Author:  Andy [ Mon Jan 03, 2005 8:21 pm ]
Post subject: 

with what language? haskell only?

Author:  wtd [ Mon Jan 03, 2005 9:05 pm ]
Post subject: 

dodge_tomahawk wrote:
with what language? haskell only?


Yes. 20 bits if you get it right and PM me before the 9th. Smile

Hint: My tutorial covers similar territory.

Author:  AsianSensation [ Mon Jan 03, 2005 10:48 pm ]
Post subject: 

nice wtd, I think this is a good challenge, and should not only be stickified, but also receive proper funding. Very Happy

If you run out of bits, just ask, the mods will be happy to reimburse you.

Author:  Andy [ Tue Jan 04, 2005 8:47 pm ]
Post subject: 

lol.. i doubt wtd will run out any time soon

Author:  bugzpodder [ Tue Jan 04, 2005 8:52 pm ]
Post subject: 

i'd post questions but i am too cheap to give away my bits... (like how rich ppl likes to hold their money)

Author:  Andy [ Tue Jan 04, 2005 8:55 pm ]
Post subject: 

LOL.. i'll give away bits for u bugz

Author:  bugzpodder [ Tue Jan 04, 2005 11:34 pm ]
Post subject: 

would you? here goes...
5 bits for each question... due date is whatever wtd has set
C++ questions
PM me the ans
for each question you get wrong, you get -5 bits hehe... if your final award is below 0 then it will count as 0. you can skip it at no penalty

1) What is the minimum/maximum integer value that you can store in a 32-bit signed integer? write in hexadecimal

2) what does ((((1<<5)+3)&(6))>>1)^5 evaluates to?

3) whats is 32ULL

4) when will the following code segment print "Hi".
int x;
cin>>x;
if (x) cout<<"Hello"<<endl; else cout<<"Hi"<<endl;

Author:  Martin [ Wed Jan 05, 2005 12:44 am ]
Post subject: 

I'm guessing I'm not allowed to answer, eh?

Author:  Andy [ Wed Jan 05, 2005 7:56 am ]
Post subject: 

lol and me neither.. only question thats somewhat hard is the 32ull one

Author:  bugzpodder [ Wed Jan 05, 2005 8:40 am ]
Post subject: 

mods can answer, you just wont get any bits.

Author:  rizzix [ Wed Jan 05, 2005 3:13 pm ]
Post subject: 

Quote:
32ULL is an unsigned long long literal
he u should have asked whts 13ULL ^^

Author:  bugzpodder [ Wed Jan 05, 2005 4:55 pm ]
Post subject: 

why 13?

Author:  rizzix [ Wed Jan 05, 2005 5:16 pm ]
Post subject: 

or even simply 3, funny u get replays saying BULL

Author:  wtd [ Wed Jan 05, 2005 10:19 pm ]
Post subject: 

For 30 bits, just to shake things up.

I have the following class in Ruby:

code:
class Foo
   def initialize(bar, baz)
      @bar, @baz = bar, baz
   end
end


Now, @bar and @baz are private, as all instance variables are in Ruby, but I can write methods which let me access those variables.

With only two additional lines of code add the ability to read and write to @bar, and read @baz.

If you use more than two lines, there will be no bits. Smile

Next question!

I have a Haskell function for multiplying an integer by two. Its type is:

code:
double :: Int -> Int


Without changing the name "double", write the shortest possible function definition. This is a 20 bit question.

Author:  wtd [ Fri Jan 07, 2005 9:26 pm ]
Post subject:  Answer to the 1/1/2005 - 1/7/2005 question

Hikaru79 won 20 bits for answering correctly, and Cervantes and Tony merit an honorable mention for taking an interest.

Though:

code:
p [1, 2, 3].collect { |x| x * 2 }


And:

code:
p [1, 2, 3].collect do |x| x * 2 end


Are nearly identical, there is a difference in precendence. In the former, the block binds immediately to the "collect" method. In the latter, the block binds to the "p" method. The "p" method disregards the block, and the "collect" method, without a block, just returns the array.

As a result, the first is essentially equal to:

code:
p([1, 2, 3].collect { |x| x * 2 })


And the second:

code:
p([1, 2, 3].collect) do |x| x * 2 end


But as mentioned, p disregards the block, so it's essentially:

code:
p([1, 2, 3].collect)


And collect just returns the same array when it doesn't have a block, so we might as well have written:

code:
p([1, 2, 3])

Author:  wtd [ Wed Jan 12, 2005 7:16 pm ]
Post subject: 

As for the C++ question:

Quote:
I write the following program and compile it with a modern C++ compiler (GCC 3.3):

code:
#include <iostream.h>

main()
{
   cout << "Hello world!" << endl;
}


It compiles and runs, but I've made four mistakes. Name them. 5 bits for each mistake.



  1. code:
    #include <iostream.h>


    Should be:

    code:
    #include <iostream>


    The "iostream.h" header is deprecated, and future compilers are not guaranteed to support it.
  2. "main" must be declared to return "int". This is mandated by the C++ standard. Using "void" does not conform to the standard. Operating systems rely on that integer being returned to determine whether the program ran successfully.
  3. I'm using "cout" and "endl" without either qualifying them as being in the "std" namespace, or including:

    code:
    using namespace std;

  4. In conjunction with number 2, I need to return zero to indicate the program finished successfully.

Author:  Andy [ Wed Jan 12, 2005 7:18 pm ]
Post subject: 

so technically.. there are only two rite? 8)

Author:  wtd [ Wed Jan 12, 2005 7:22 pm ]
Post subject: 

Quote:
Write a program which prompts for the user's name and accepts it on a single line, then greets the user in all caps. A sample run might look like:

code:
You are? Simon
HELLO SIMON!  SORRY FOR YELLING!!!


Reference material:

http://www.haskell.org
http://www.familygeek.com/haskell/tutorial.html


The answer could look like:

code:
module Main where

import IO
import Char

main :: IO ()
main = do
  putStr "You are? "
  hFlush stdout
  name <- getLine
  let greeting = "hello " ++ name ++ "!  sorry for yelling!!!"
  putStrLn $ map toUpper greeting

Author:  wtd [ Wed Jan 12, 2005 7:23 pm ]
Post subject: 

Andy wrote:
so technically.. there are only two rite? 8)


No, there are four. Perhaps you could argue two and three are connected, but that's still at least three. Smile

Author:  Andy [ Wed Jan 12, 2005 7:27 pm ]
Post subject: 

well.. i noe its unconventional, but if u put void infront of main, and add the .h to the iostream, then it would be fine

Author:  wtd [ Wed Jan 12, 2005 7:41 pm ]
Post subject: 

Andy wrote:
well.. i noe its unconventional, but if u put void infront of main, and add the .h to the iostream, then it would be fine


It will compile, but it won't be fine. Neither is acceptable, according to the C++ standard.

Author:  Andy [ Wed Jan 12, 2005 10:36 pm ]
Post subject: 

since when did u conform to the norm wtd?

Author:  wtd [ Wed Jan 12, 2005 10:40 pm ]
Post subject: 

Andy wrote:
since when did u conform to the norm wtd?


Since I started wanting my code to work right. Wink

Let me just reduce it to this: any time you spend learning nonstandard C++ or java, or whatever is time you've lost and you'll never get back. It's time you've not only not spent learning something useful, but it's work you have to undo later on, meaning even less time to learn useful stuff.

Author:  wtd [ Tue Jan 25, 2005 11:57 pm ]
Post subject: 

The answer to this one is way overdue.

wtd wrote:
For 30 bits, just to shake things up.

I have the following class in Ruby:

code:
class Foo
   def initialize(bar, baz)
      @bar, @baz = bar, baz
   end
end


Now, @bar and @baz are private, as all instance variables are in Ruby, but I can write methods which let me access those variables.

With only two additional lines of code add the ability to read and write to @bar, and read @baz.

If you use more than two lines, there will be no bits. Smile


code:
class Foo
   attr_accessor :bar
   attr_reader :baz
   def initialize(bar, baz)
      @bar, @baz = bar, baz
   end
end


wtd wrote:
Next question!

I have a Haskell function for multiplying an integer by two. Its type is:

code:
double :: Int -> Int


Without changing the name "double", write the shortest possible function definition. This is a 20 bit question.


We start with the obvious:

code:
double n = n * 2


But we realize that n is redundant, so we use a partial application of the * operator, which is really just a function itself.

code:
double=(*2)


And that, folks, is as short as it gets.

Author:  wtd [ Wed Apr 13, 2005 1:21 pm ]
Post subject: 

The following will not compile. Make the minimal necessary change such that it does compile, and PM me with your answer.

c++:
class A
{
   private:
      const int& b;
   public:
      A(const int& init_b)
      {
         b = init_b;
      }
};

int main()
{
   int foo(42);
   A bar(foo);

   return 0;
}

Author:  wtd [ Wed Apr 13, 2005 2:16 pm ]
Post subject: 

Sorry, rizzix, that's incorrect. Smile

Author:  rizzix [ Wed Apr 13, 2005 2:19 pm ]
Post subject: 

yea i deleted the post.. did't read it correctly Razz try adding an &

Author:  wtd [ Wed Apr 13, 2005 2:24 pm ]
Post subject: 

Nope. Nowhere do you add an & in the solution. Smile

Author:  rizzix [ Wed Apr 13, 2005 2:26 pm ]
Post subject: 

then it has to be the const.. but.. well i'm not fimiliar with the &.. anyhow.. then isint int & b = &k; the way to go.. and not int &b = k;

Author:  Martin [ Wed Apr 13, 2005 2:32 pm ]
Post subject: 

Here's a hint: what if you wanted to do this?
c++:

#include <iostream>
class A
{
   private:
      const int& b;
   public:
      A(const int& init_b)
      {
         std::cout << b << std::endl;
         b = init_b;
      }
};

int main()
{
   int foo(42);
   A bar(foo);

   return 0;
}

Author:  rizzix [ Wed Apr 13, 2005 2:34 pm ]
Post subject: 

huh? howz that a hint.. i got it already.. gee.. the alias is defined const. pfft. i shouldn't.. point is.. the referencing is wrong.. now isin't it?

as for my second question.. constructors cannot initialise const values?

Author:  Martin [ Wed Apr 13, 2005 2:38 pm ]
Post subject: 

the const is fine the way it is.

Author:  wtd [ Wed Apr 13, 2005 2:40 pm ]
Post subject: 

In C++, in addition to regular old C style pointers there're also references. A reference is declareed like so:

code:
int& foo


Whereas a regular int would be declared as:

code:
int foo;


And a pointer to an int as:

code:
int * foo;


A reference to a constant int would be like so:

code:
const int& foo;


If we have an int variable, like so:

code:
int foo(42);


We can assign it to an int reference like so:

code:
int& bar(foo);


The & used as a prefix operator returns the address in memory of the variable. This is useful when dealing with pointers, but not so much references.

For instance, we might have:

code:
int foo(42);
int * bar(&foo);

Author:  rizzix [ Wed Apr 13, 2005 2:41 pm ]
Post subject: 

martin:i dont think so. i compiled it.. and apparently contstuctors cannot initialise const values.

Author:  Martin [ Wed Apr 13, 2005 2:43 pm ]
Post subject: 

Yes they can. I already got this one.

Author:  wtd [ Wed Apr 13, 2005 2:43 pm ]
Post subject: 

rizzix wrote:
martin:i dont think so. i compiled it.. and apparently contstuctors cannot initialise const values.


Oh, I assure you they can. Are you sure you understand C++ constructors as well as you think? What you think is initialization might not be initialization at all. Wink

Author:  rizzix [ Wed Apr 13, 2005 2:52 pm ]
Post subject: 

the how do u intialise an alias.

Author:  wtd [ Wed Apr 13, 2005 2:55 pm ]
Post subject: 

For clarity, the term is "reference", and if I tell you that it'll give away the answer. Ah, I'll just PM the solution to you. Smile

Author:  wtd [ Wed Apr 13, 2005 4:44 pm ]
Post subject: 

For 30 bits, what's wrong with the following "hello world" program that causes it not to compile?

ada:
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello_World is
begin
   Put_Line("Hello world!");
end hello_world;

Author:  wtd [ Wed Apr 13, 2005 10:45 pm ]
Post subject: 

For a whopping 100 bits, explain how the following Eiffel classes demonstrate the concept of "uniform access".

code:
class
   NAME
creation { ANY }
   with_both
feature { ANY }
   with_both(f, l : STRING) is
      require
         f /= "" and l /= ""
      do
         first := f
         last := l
      end
   full_name : STRING is
      do
         Result := first + " " + last
      end
feature { NONE }
   first, last : STRING
end


code:
class
   TEST
creation { ANY }
   make
feature { ANY }
   make is
      local
         bob : NAME
      do
         create bob.with_both("Bob", "Smith)
         std_output.put_string(bob.full_name)
         std_output.put_new_line
      end
end

Author:  wtd [ Thu Apr 14, 2005 2:02 am ]
Post subject: 

And, since I thoroughly confused rizzix, a Java-oriented question. Smile

Let's say we have a class for helping us deal with cards.

code:
class Card
{
   public static final int HEART = 1;
   public static final int DIAMOND = 2;
   public static final int CLUB = 3;
   public static final int SPADE = 4;

   private int suit;
   private int card;

   public Card(int suit, int card)
   {
      this.suit = suit;
      this.suit = card;
   }   

   public int getSuit()
   {
      return suit;
   }

   public int getCard()
   {
      return card;
   }
}


What's fundamentally wrong with this design?

Author:  rizzix [ Thu Apr 14, 2005 8:04 am ]
Post subject: 

solution? wrote:
Type safety and domain restiction is the fundamental problem. The suit of the card is defined as of type 'int' so is the 'card value'.

Problem here, is if you do go ahead with this kind of implementation, it is not type safe hence the client could pass any interger as an argument to the consturctor. Now this it self is the troublesome design problem. But lets assume we want to do that (pass an interger). The issue is that domain is not resticted, hence any interger value may be pass to the constuctor with no runtime error being issued. But this could futher lead to a design problem since, throwing an exception for simply creating a Card object is not a very nice thing to do. Besides as far as possible errors such as these should be caught at Compile time not Runtime.


Solution: use enums.

Author:  wtd [ Thu Apr 14, 2005 1:41 pm ]
Post subject: 

Bingo.

Author:  wtd [ Thu Apr 14, 2005 5:02 pm ]
Post subject: 

Objective-C this time. I expect rizzix to chime in. Smile

Create three classes (Foo, Bar, and Baz), all direct subclasses of Object, such that only Foo and Bar implement a "speak" method which returns void and simply prints the name of the class to standard output. Use stdio.h for the output.

Write a void function "speak" which accepts either a Foo or Bar object, but will produce at least a compile time warning if a Baz object is passed to speak.

The main function should look like:

code:
int main()
{
        Foo *foo = [[Foo alloc] init];
        Bar *bar = [[Bar alloc] init];
        Baz *baz = [[Baz alloc] init];

        speak(foo);
        speak(bar);
        speak(baz);

        return 0;
}


And the implementation of each of the classes should look like:

code:
@implementation Foo
-(void)speak
{
        puts("Foo");
}
@end

@implementation Bar
-(void)speak
{
        puts("Bar");
}
@end

@implementation Baz
@end

Author:  rizzix [ Fri Apr 15, 2005 2:27 pm ]
Post subject: 

solution wrote:
@protocol Speak
- (void) speak
@end

@interface Foo : NSObject <Speak>
{}
@end

@interface Bar : NSObject <Speak>
{}
@end

@interface Baz : NSObject
{}
@end

void speak(id<Speak> k) {
[k speak];
}

Author:  wtd [ Fri Apr 15, 2005 4:06 pm ]
Post subject: 

Nice.

Author:  [Gandalf] [ Fri Apr 15, 2005 4:17 pm ]
Post subject: 

wtd wrote:
For 30 bits, what's wrong with the following "hello world" program that causes it not to compile?

ada:
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello_World is
begin
   Put_Line("Hello world!");
end hello_world;


I dont know if this is still valid, but I thought I might as well try...

Is the problem that first letters in the hello_world where you say "end hello_world" not the same case as the procedure "procedure Hello_World"?

btw, I don't know ada Wink

Author:  wtd [ Fri Apr 15, 2005 4:21 pm ]
Post subject: 

[Gandalf] wrote:
wtd wrote:
For 30 bits, what's wrong with the following "hello world" program that causes it not to compile?

ada:
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello_World is
begin
   Put_Line("Hello world!");
end hello_world;


I dont know if this is still valid, but I thought I might as well try...

Is the problem that first letters in the hello_world where you say "end hello_world" not the same case as the procedure "procedure Hello_World"?

btw, I don't know ada Wink


I suppose now is as good a time as any to tell everyone...

It's a trick question. Ada is a case-insensitive programming language.

hello_world
Hello_World
HELLO_WORLD
hELLO_wORLD

They're all the same. Smile

The program compiles and runs without any problems.

Congratulations to Hikaru79 for figuring this one out.

Author:  wtd [ Sat Apr 23, 2005 11:36 pm ]
Post subject: 

In Haskell:

code:
4 + 3


Will return the number 7 as an int.

code:
4.0 + 3


Returns 7.0.

Alter the first expression so that it returns 7.0 without using a function, or writing out a float literal, as in the second.

Author:  rizzix [ Sun Apr 24, 2005 12:20 am ]
Post subject: 

solution wrote:
4 + 3 :: Float

Author:  wtd [ Fri May 27, 2005 12:56 pm ]
Post subject: 

I dn't even know if there are enough bits as reward for answering all of these...

That said, prove that you know C++. Smile

Do you know what all of the different uses of "const" or "static" mean?

Do you understand why a normal class can be split into a header and a ".cpp" source file, but a templated class cannot?

Do you understand why you shouldn't use identifiers beginning with two underscores, even though it's technically legal?

Do you understand the difference between:

code:
int c = 0;


and

code:
int c(0);


or

code:
c++;


and

code:
++c;


Do you understand why one of the following works and the other doesn't?

code:
struct foo
{
   const int a;
   
   foo(const int init_a)
   {
      a = init_a;
   }
};


code:
struct foo
{
   const int a;
   
   foo(const int init_a) : a(init_a) { }
};


Do you understand why this code is wasteful?

code:
int a[] = {1, 2, 3, 4, 5, 6, 8, 7, 9};
int b[9];

for (int i(0); i < 9; ++i)
{
   b[i] = a[i];
}


Do you know how to replace that loop with a single line of code?

Do you know why one constructor cannot be called from another constructor?

Do you know when and why to define a destructor?

Do you understand how to create and use function objects?

Do you know why the following is bad form?

code:
std::string s[] = {"hello", "world", "foo", "bar"};
std::string concatenated;

for (int i(0); i < 4; ++i)
{
   concatenated += s[i];
}


Do you know what to replace the above with?

Do you know the difference between a struct and a class?

Do you know the difference between the following, and why the first is better code?

code:
struct name
{
   const std::string first, last;
   
   name(std::string f, std::string l) : first(f), last(l) { }

   std::string full_name() const { return first + " " + last; }
};

struct grade_collection : private std::vector<int>
{
   int total() const
   {
      int sum(0);
      for (int i(0); i < size(); ++i)
      {
         sum += at(i);
      }
      return sum;
   }

   int average() const
   {
      return total() / size();
   }

   void add_grade(int g)
   {
      push_back(g);
   }
};

struct student : public name, public grade_collection
{
   student(std::string f, std::string l) : name(f, l), grade_collection() { }
};


code:
struct name
{
   const std::string first, last;
   
   name(std::string f, std::string l) : first(f), last(l) { }

   std::string full_name() const { return first + " " + last; }
};

struct grade_collection : public std::vector<int>
{
   int total() const
   {
      int sum(0);
      for (int i(0); i < size(); ++i)
      {
         sum += at(i);
      }
      return sum;
   }

   int average() const
   {
      return total() / size();
   }

   void add_grade(int g)
   {
      push_back(g);
   }
};

struct student : public name, public grade_collection
{
   student(std::string f, std::string l) : name(f, l), grade_collection() { }
};


Do you understand the difference between the following?

code:
for (int i(0); i < 4; ++i)
{
   std::cout << some_vector[i] << std::endl;
}


code:
for (int i(0); i < 4; ++i)
{
   std::cout << some_vector.at(i) << std::endl;
}


Do you understand why even the second of those is bad, and why the following is better?

code:
for (std::vector<some_type>::iterator i(some_vector.begin()); i != some_vector.end(); i++)
{
   std::cout << *i << std::endl;
}


Demonstrate use a function object combined with std::for_each from the STL to duplicate the above loop, while also allowing for use of any output stream, and not just std::cout.

Author:  [Gandalf] [ Fri Jul 01, 2005 6:57 pm ]
Post subject: 

I think that since that post seems to have scared people off, and nobody seems to be able to answer them all, we should start picking it apart piece by piece. So, I will start with my minor knowledge of c++.

wtd wrote:
Do you understand the difference between:

code:
int c = 0;


and

code:
int c(0);


or

code:
c++;


and

code:
++c;



Do you know the difference between a struct and a class?

Well, for the first two, the first one uses assignment, and the second one uses initialization. I'm not sure of the differences of what they do, but they are two different operations, and they are used in different contexts usually.

For the second two, the first is a postfix increment, and the second is a prefix increment. They both increment the value by one, but the postfix is not as good since it still outputs the previous value, not the newly incremented one.

For the last question, a struct makes all member functions/variables public, while classes allow you to declare what is private/public/or protected. This prevents bugs because you can control when and where the member of the class is manipulated.

*ahh, well, I tried* Smile

Author:  rizzix [ Fri Jul 01, 2005 7:01 pm ]
Post subject: 

ehm... you are wrong the first and second are the same.. they are both initialisations... they are just two different notations for the same thing..

Author:  wtd [ Fri Jul 01, 2005 7:05 pm ]
Post subject: 

[Gandalf] wrote:
I think that since that post seems to have scared people off, and nobody seems to be able to answer them all, we should start picking it apart piece by piece. So, I will start with my minor knowledge of c++.

wtd wrote:
Do you understand the difference between:

code:
int c = 0;


and

code:
int c(0);


or

code:
c++;


and

code:
++c;



Do you know the difference between a struct and a class?

Well, for the first two, the first one uses assignment, and the second one uses initialization. I'm not sure of the differences of what they do, but they are two different operations, and they are used in different contexts usually.

For the second two, the first is a postfix increment, and the second is a prefix increment. They both increment the value by one, but the postfix is not as good since it still outputs the previous value, not the newly incremented one.

For the last question, a struct makes all member functions/variables public, while classes allow you to declare what is private/public/or protected. This prevents bugs because you can control when and where the member of the class is manipulated.


Close, but not quite. Postfix and prefix incrementing are both equally "good", which is to say they both have value when used correctly.

The postfix version will both increment the variable and return its previous value. This is a trickier operation, and generally requires a bit (but that may be a very small bit) more overhead. If you're incrementing in a void context, using the prefix version may be slightly faster.

As for structs, they still allow for access specifiers.

code:
struct foo
{
   private:
      int a;
   public:
     foo(int init_a) : a(init_a) { }
};


Is perfectly legal.

Author:  [Gandalf] [ Sat Jul 02, 2005 8:02 pm ]
Post subject: 

Ok, I don't get it, you said it yourself:
wtd wrote:
a struct (class with all public members)

Is that not what I said? Confused

Author:  wtd [ Sat Jul 02, 2005 9:25 pm ]
Post subject: 

[Gandalf] wrote:
Ok, I don't get it, you said it yourself:
wtd wrote:
a struct (class with all public members)

Is that not what I said? Confused


Public by default, yes, but that can be modified, just as in a class. Smile

Author:  MysticVegeta [ Wed Jul 20, 2005 8:37 am ]
Post subject: 

I think
code:
int c;
declares an integer c
code:
int c[0];
declares an array
code:
c++
increments the value of c by 1
code:
int b = ++c;
makes the value b = (c+1) but the value of c stays same

I dont know, i might be wrong, i read the C++ for dummies a long time ago Laughing lol

Author:  [Gandalf] [ Wed Jul 20, 2005 11:51 am ]
Post subject: 

MysticVegeta wrote:
I think
code:
int c;
declares an integer c
code:
int c[0];
declares an array
code:
c++
increments the value of c by 1
code:
int b = ++c;
makes the value b = (c+1) but the value of c stays same

Well, it was int c(0); not int c[0];. Using the () brackets to initialize is the "C++ syle" while using the = would be another method of initialization used in C, Java, and most others (it's still used in C++ too). Also, I think he explained post/pre increments already Wink.

Ok, so how about this:
In a struct all members are public by default, while in a class they are private by default. By default meaning, if you do not put any access limited (or whatever). ?

Author:  Martin [ Thu Jul 21, 2005 8:25 pm ]
Post subject: 

Some awesome C++ code:

code:
cout << 5[2 + "abcdefghi"] << endl;


Very Happy

And of course, some of the coolest C code that I've seen in a while. Ported from SPARC by a Mark Sherry.

code:
#include <stdio.h>
#include <sys/types.h>

int globaldummy;

void
entry (void (*blabber) ())
{
  blabber ();
}

void
quux (void)
{
  globaldummy++;
}

void
bar (void)
{
  printf ("first instruction\n");
  globaldummy++;
  printf ("after the entry point\n");
}

main ()
{
  void (*crigglesnash) (void);
  size_t fnsize;

  fnsize = bar - quux - 5;
  for (crigglesnash = bar; memcmp (crigglesnash, quux + fnsize, fnsize);
       crigglesnash += fnsize);
  entry (crigglesnash);
}

Author:  [Gandalf] [ Sat Jul 23, 2005 7:28 pm ]
Post subject: 

Interesting code, I'll try it out.

Alright, an improvement over my previous explanations.
code:
int c(0);

This style of of assignment can only be used when the variable is being declared. So the () method is only usable when initializing. You cannot, for example, do something like this:
code:
int c;
c(0);

while you can do something like this:
code:
int c;
c = 0;


Quote:
Do you know when and why to define a destructor?

A constructor can 'allocate' memory, or for example open a file, and a destructor is needed to automatically close that file, and deallocate the resources without creating a new function.

How about some bits? Laughing

Author:  wtd [ Sat Jul 23, 2005 8:07 pm ]
Post subject: 

[Gandalf] wrote:
Quote:
Do you know when and why to define a destructor?

A constructor can 'allocate' memory, or for example open a file, and a destructor is needed to automatically close that file, and deallocate the resources without creating a new function.


Sure. +50 bits.

If we continue to develop the following class, would it need a destructor? If so, write that destructor.

c++:
class Student
{
   private:
      std::vector<double> *grades;
   public:
      const std::string first_name, last_name;
};

Author:  Mr. T [ Wed Sep 21, 2005 11:46 pm ]
Post subject:  Alex's Opinion

I think it's about time for a Turing question. Twisted Evil

Author:  wtd [ Wed Sep 21, 2005 11:50 pm ]
Post subject:  Re: Alex's Opinion

Pwned wrote:
I think it's about time for a Turing question. Twisted Evil


Turing's not interesting enough to do anything tricky. Razz

Author:  beard0 [ Thu Sep 22, 2005 7:03 am ]
Post subject: 

I think it's about time for another question, period..... please?

(And Turing is interesting enough... grr)

Author:  wtd [ Thu Sep 22, 2005 11:41 am ]
Post subject: 

Well, it may be "interesting" by some definition of that word, but these tests are meant to test details, and things that are often overlooked.

I either don't know Turing well enough to myself test others on such things, or haven't seen an opportunity to ask such questions.

With that said, the next question:

Ok, Pythonistas, this one's for you again.

Given the class Foo:

Python:
class Foo(object):
   def __init__(self):
      self.bar = 42


We can easily add attributes to an instance of Foo at run-time.

Python:
baz = Foo()
baz.ninja = 27.3
print baz.ninja


That's not a problem.

Create a subclass Wooble of Foo which makes all added attributes strings. Make sure it doesn't change the type of "bar".

Do this in one function in the Wooble class.

Author:  wtd [ Thu Sep 22, 2005 12:06 pm ]
Post subject: 

A Haskell question:

Let's have a simple factorial program.

code:
import IO

main =
  do
    putStr "Enter a number: "
    hFlush stdout
    inputLine <- hGetLine stdin
    let inputNumber = read input
    let factorial = product [1..number]
    let strFactorial = show factorial
    putStrLn strFactorial


Now... rewrite main as a single line of code with no explicit passing of state (such as: "let inputNumber = read input" and "let factorial = product [1..number]").

Author:  wtd [ Thu Sep 22, 2005 12:11 pm ]
Post subject: 

A Ruby question.

Write a class Ninja, for which calling a method it doesn't have raises no errors, but rather stores information about the method call (the name of the method and the arguments passed to it).

Author:  wtd [ Thu Sep 22, 2005 12:14 pm ]
Post subject: 

A C++ question.

Given that we have a file "input_file" open and pointing to a plain text file, and a std::vector of characters "chars_of_input_file", write a single line of code which will slurp all of the chars in the file into the vector.

You may not use "for" or "while", or multiple semi-colons (you're allowed one to terminate the entire line).

Author:  wtd [ Thu Sep 22, 2005 12:58 pm ]
Post subject: 

Objective-Caml question.

I have a module Foo:

code:
module Foo =
   struct
      let bar = "hello"
      let print_bar () = print_endline bar
   end;;


Make it impossible to access "bar" from outside of the module.

Author:  wtd [ Thu Sep 22, 2005 4:48 pm ]
Post subject: 

I have two Objective-C classes:

code:
@interface Foo : Object
- (void) sayHello;
@end

@interface Bar : Object
- (void) sayHello;
@end


Both have different implementations of sayHello, but the implementations aren't important.

I want to pass objects of these classes to a function.

code:
void sayHello(id greetingObject)
{
   [greetingObject sayHello];
}


Here I've used the "id" type, which for lack of a better explanation essentially includes anything.

But what if I only want to accept objects which have a "- (void) sayHello" method? And I don't want to just get an error at run-time. I want to enforce that limit.

Modify the code to make that possible.

The entire original program:

code:
#import <objc/Object.h>
#include <stdio.h>

@interface Foo : Object
- (void) sayHello;
@end

@interface Bar : Object
- (void) sayHello;
@end

void sayHello(id);

int main()
{
   Foo *f = [[Foo alloc] init];
   Bar *b = [[Bar alloc] init];

   sayHello(f);
   sayHello(b);
}

void sayHello(id greetingObject)
{
   [greetingObject sayHello];
}

@implementation Foo
- (void) sayHello
{
   puts("Hello");
}
@end

@implementation Bar
- (void) sayHello
{
   puts("Yo");
}
@end

Author:  Hikaru79 [ Fri Sep 23, 2005 8:30 pm ]
Post subject: 

wtd wrote:
Well, it may be "interesting" by some definition of that word, but these tests are meant to test details, and things that are often overlooked.

I either don't know Turing well enough to myself test others on such things, or haven't seen an opportunity to ask such questions.

With that said, the next question:

Ok, Pythonistas, this one's for you again.

Given the class Foo:

Python:
class Foo(object):
   def __init__(self):
      self.bar = 42


We can easily add attributes to an instance of Foo at run-time.

Python:
baz = Foo()
baz.ninja = 27.3
print baz.ninja


That's not a problem.

Create a subclass Wooble of Foo which makes all added attributes strings. Make sure it doesn't change the type of "bar".

Do this in one function in the Wooble class.

Python:
class Wooble(Foo):
        def __setattr__( self, name, value ):
                if name!='bar':
                        self.__dict__[name] = str(value)
                else:
                        self.__dict__[name] = value

I feel bad about the 'if name!='bar' thing, but it fits the problem description, as you said Twisted Evil

Author:  Hikaru79 [ Fri Sep 23, 2005 11:24 pm ]
Post subject: 

wtd wrote:
A Haskell question:

Let's have a simple factorial program.

code:
import IO

main =
  do
    putStr "Enter a number: "
    hFlush stdout
    inputLine <- hGetLine stdin
    let inputNumber = read input
    let factorial = product [1..number]
    let strFactorial = show factorial
    putStrLn strFactorial


Now... rewrite main as a single line of code with no explicit passing of state (such as: "let inputNumber = read input" and "let factorial = product [1..number]").

Is this OK?
Haskell:
import IO;

main = do { putStr "Enter a number: " ; hFlush stdout ; inputLine <- hGetLine stdin ; putStrLn $ show $ product [1..read inputLine] }

Author:  wtd [ Sat Sep 24, 2005 12:26 am ]
Post subject: 

And neither one is correct, since there's explicit passing of state.

Author:  rizzix [ Sat Sep 24, 2005 12:27 am ]
Post subject: 

mb i realized that...

Author:  rizzix [ Sat Sep 24, 2005 12:55 am ]
Post subject: 

here's it...

Haskell:
import IO

main = putStr "Enter a number: " >> hFlush stdout >> hGetLine stdin >>= \inputLine -> (putStrLn $ show $ product [1 .. read inputLine])

Author:  wtd [ Sat Sep 24, 2005 3:15 am ]
Post subject: 

Nice try, but you're using an unnecessary eta-expansion. Study function composition, young padawan.

Author:  rizzix [ Sat Sep 24, 2005 10:16 am ]
Post subject: 

No i don't know much about functional composition in haskell.. (actually i understand the concept, but i don;t know how to apply it there)

but i might as well ans ur other 2, they seem too easy

wtd wrote:
A C++ question.

Given that we have a file "input_file" open and pointing to a plain text file, and a std::vector of characters "chars_of_input_file", write a single line of code which will slurp all of the chars in the file into the vector.

You may not use "for" or "while", or multiple semi-colons (you're allowed one to terminate the entire line).


c++:
chars_of_input_file.insert(chars_of_input_file.begin(), istream_iterator<char>(input_file), istream_iterator<char>());


and for the Obj-C one..

obj-c:
#import <objc/Object.h>
#include <stdio.h>

@protocol SaysHello
    - (void) sayHello;
@end

@interface Foo : Object <SaysHello>
- (void) sayHello;
@end

@interface Bar : Object <SaysHello>
- (void) sayHello;
@end

void sayHello(id);

int main()
{
   Foo *f = [[Foo alloc] init];
   Bar *b = [[Bar alloc] init];

   sayHello(f);
   sayHello(b);
}

void sayHello(id<SaysHello> greetingObject)
{
   [greetingObject sayHello];
}

@implementation Foo
- (void) sayHello
{
   puts("Hello");
}
@end

@implementation Bar
- (void) sayHello
{
   puts("Yo");
}
@end

Author:  wtd [ Sat Sep 24, 2005 10:51 am ]
Post subject: 

rizzix wrote:
and for the Obj-C one..

obj-c:
#import <objc/Object.h>
#include <stdio.h>

@protocol SaysHello
    - (void) sayHello;
@end

@interface Foo : Object <SaysHello>
- (void) sayHello;
@end

@interface Bar : Object <SaysHello>
- (void) sayHello;
@end

void sayHello(id);

int main()
{
   Foo *f = [[Foo alloc] init];
   Bar *b = [[Bar alloc] init];

   sayHello(f);
   sayHello(b);
}

void sayHello(id<SaysHello> greetingObject)
{
   [greetingObject sayHello];
}

@implementation Foo
- (void) sayHello
{
   puts("Hello");
}
@end

@implementation Bar
- (void) sayHello
{
   puts("Yo");
}
@end


That actually compiles and works correctly, but you have too many lines. You're working too hard. Smile

Author:  rizzix [ Sat Sep 24, 2005 12:10 pm ]
Post subject: 

hmm i just added 3 lines of code and modifed another 3 lines..
wht's the shorter alternative?

Author:  Mr. T [ Sat Sep 24, 2005 2:07 pm ]
Post subject:  Re: Alex's Opinion

wtd wrote:
Pwned wrote:
I think it's about time for a Turing question. Twisted Evil


Turing's not interesting enough to do anything tricky. Razz

Well then a challenge will also exist for the person writing the question. Laughing

Author:  wtd [ Sat Sep 24, 2005 2:10 pm ]
Post subject: 

rizzix wrote:
hmm i just added 3 lines of code and modifed another 3 lines..
wht's the shorter alternative?


code:
@interface Foo : Object <SaysHello>
- (void) sayHello;
@end


By specifying that Foo implements the SaysHello protocol, you're also saying that Foo has a "- (void) sayHello" method. There's no need to say this again.

code:
@interface Foo : Object <SaysHello>
@end


Works perfectly well. Smile

Author:  rizzix [ Sat Sep 24, 2005 2:25 pm ]
Post subject: 

ah but that's more work.. i needed to delete 2 extra lines Laughing

Author:  wtd [ Sat Sep 24, 2005 2:52 pm ]
Post subject: 

A C++ question.

What part ofthe following prevents it from compiling in Visual C++ 6.0?

c++:
template <typename T>
class Foo
{
   private:
      T m_value;
   
   public:
      Foo();
      Foo(T);

      T value() const;

      template <typename _T>
      void add(_T);
};

template <typename T>
Foo<T>::Foo() : m_value(T()) { }

template <typename T>
Foo<T>::Foo(T initValue) : m_value(initValue) { }

template <typename T>
T Foo<T>::value() const
{
   return m_value;
}

template <typename T>
template <typename _T>
void Foo<T>::add(_T other)
{
   m_value += other;
}


Will this successfully compile with GCC or a newer version of Microsoft's C++ compiler?

Modify the above so that it will compile in Visual C++ 6.0.

Author:  wtd [ Sat Sep 24, 2005 10:12 pm ]
Post subject: 

I have the following simple Ada generic package:

ada:
generic
    Size : Positive;
    type Item_Type is private;
  package Generic_Stack is
    procedure Push(E : in  Item_Type);
    procedure Pop (E : out Item_Type);
    Overflow, Underflow : exception;
  end Generic_Stack;


With body:

ada:
package body Generic_Stack is
    type Table is array (Positive range <>) of Item_Type;
    Space : Table(1 .. Size);
    Index : Natural := 0;

    procedure Push(E : in Item_Type) is
    begin
      if Index >= Size then
        raise Overflow;
      end if;
      Index := Index + 1;
      Space(Index) := E;
    end Push;

    procedure Pop(E : out Item_Type) is
    begin
      if Index = 0 then
        raise Underflow;
      end if;
      E := Space(Index);
      Index := Index - 1;
    end Pop;

  end Generic_Stack;


That can be used like so:

ada:
procedure Test_Proc is
  package Stack_Int is new Generic_Stack(Size => 200, Item => Integer);

  A : Integer;
begin
  Stack_Int.Push(42);
  Stack_Int.Pop(A);
end Test_Proc;


Modify the package declaration for Generic_Stack such that the type used for Item_Type must work with the equality (=) operator.

If you add more than one line, you're doing it wrong. Wink

Author:  wtd [ Sun Sep 25, 2005 1:57 am ]
Post subject: 

I have the following Python class:

Python:
class Foo(object):
   def __init__(self):
      self.__bar = 42


Where self.__bar is (essentially) a private variable.

Add a single line of code to ths class which provides a read-only accessor named "bar" for that private variable.

Author:  Hikaru79 [ Sun Sep 25, 2005 10:45 am ]
Post subject: 

Python:
class Foo(object):
   def __init__(self):
      self.__bar = 42
   def bar(self): return self.__bar


? Or does that not count because you have to call "myObject.bar()" instead of "myObject.bar" ?

Author:  wtd [ Sun Sep 25, 2005 11:20 am ]
Post subject: 

Hikaru79 wrote:
Python:
class Foo(object):
   def __init__(self):
      self.__bar = 42
   def bar(self): return self.__bar


? Or does that not count because you have to call "myObject.bar()" instead of "myObject.bar" ?


Exactly. Smile

Author:  wtd [ Tue Sep 27, 2005 12:31 pm ]
Post subject: 

Ruby challenge!

Write a class Foo whereby you can run this code:

code:
>> Foo.new.collect { |x| x * 2}
=> ["foofoo", "barbar", "bazbaz"]


Without cheating by having a method all on one line or using semicolons, do this in six lines. Blank lines won't be included in the count.

One line blocks are permitted.

When you're finished, do the equivalent in Python to make the following possible:

code:
>>> map(lambda x: x + x, Foo())
['foofoo', 'barbar', 'bazbaz']

Author:  wtd [ Wed Sep 28, 2005 3:16 am ]
Post subject: 

Write the shortest possible piece of code that makes it possible to create a very simple object with:

Python:
x()

Author:  wtd [ Thu Sep 29, 2005 5:10 pm ]
Post subject: 

wtd wrote:
A Haskell question:

Let's have a simple factorial program.

code:
import IO

main =
  do
    putStr "Enter a number: "
    hFlush stdout
    inputLine <- hGetLine stdin
    let inputNumber = read input
    let factorial = product [1..number]
    let strFactorial = show factorial
    putStrLn strFactorial


Now... rewrite main as a single line of code with no explicit passing of state (such as: "let inputNumber = read input" and "let factorial = product [1..number]").


code:
putStr "Enter a number: " >> hFlush stdout >> hGetLine stdin >>= print . product . enumFromTo 1 . read

Author:  wtd [ Thu Oct 20, 2005 9:11 pm ]
Post subject: 

code:
putStr "Enter a number: " >> hFlush stdout >> hGetLine stdin >>= print . product . enumFromTo 1 . read


Rewrite this without using the >> operator. You're still permitted to use the >>= operator.

Author:  Martin [ Thu Oct 20, 2005 10:18 pm ]
Post subject: 

I just edited the title of the topic to reflect, well, present times.

Author:  wtd [ Thu Oct 20, 2005 10:25 pm ]
Post subject: 

Thanks.

Now answer some questions. Razz

Author:  rizzix [ Thu Oct 20, 2005 10:48 pm ]
Post subject: 

code:
main = sequence[putStr "Enter a number: ", hFlush stdout, hGetLine stdin >>= print . product . enumFromTo 1 . read]
???

Author:  wtd [ Thu Oct 20, 2005 11:34 pm ]
Post subject: 

While that works, I was thinking of:

code:
putStr "Enter a number: " >>= \_ -> hFlush stdout >>= \_ -> hGetLine stdin >>= print . product . enumFromTo 1 . read

Author:  wtd [ Wed Nov 23, 2005 8:21 pm ]
Post subject: 

A new C++ Test Your Skills.

I start with the following source:

c++:
#include <iostream>

using namespace std;

int main()
{
   int a = 4, b = 5;

   cout << a << b << endl;
   cout << a << b << endl;

   return 0;
}


This prints:

code:
45
45


Add two lines of code to this which will make it print:

code:
45
54


You may not compact code to meet the two line limit, nor may you introduce new variables, nor may you use macros. You also may not alter any of the code in the original source.

Author:  [Gandalf] [ Thu Nov 24, 2005 1:18 am ]
Post subject: 

c++:
#include <iostream>

using namespace std;

int main()
{
   int a = 4, b = 5;

   cout << a << b << endl;
   cout << b << a << endl;
   return 0;
   cout << a << b << endl;
}

Creative solution, no? And in only one extra line. Laughing

Author:  wtd [ Thu Nov 24, 2005 1:28 am ]
Post subject: 

Ah, but you've changed the order of two of the lines. Smile

Yes, you could have two return statements in there, but I'd consider that bad form. The ideal solution will involve no such hacks.

In fact, the final solution shouldn't be "hackish" in the slightest. Smile

Author:  [Gandalf] [ Thu Nov 24, 2005 1:33 am ]
Post subject: 

Ah, but you didn't mention that it had to follow good form Wink.

Well, for that I'll have to look into it a little bit more...

Author:  wtd [ Thu Nov 24, 2005 1:35 am ]
Post subject: 

Shame there's no easy way to swap the values in a and b.

Author:  Martin [ Thu Nov 24, 2005 2:21 am ]
Post subject: 

c++:
#include <iostream>

using namespace std;

int main()
{
   int a = 4, b = 5;

   cout << a << b << endl;
   a = a + b - (b = a); // 4 + 5 - (4)
   cout << a << b << endl;

   return 0;
}


In half of two lines. Boo yeah!

Author:  md [ Thu Nov 24, 2005 2:25 am ]
Post subject: 

Martin wrote:
c++:
#include <iostream>

using namespace std;

int main()
{
   int a = 4, b = 5;

   cout << a << b << endl;
   a = a + b - (b = a); // 4 + 5 - (4)
   cout << a << b << endl;

   return 0;
}


In half of two lines. Boo yeah!

I think you need brackets around (a+b), otherwise the second brackets get evaluated first and then b == a == 4, so a + b = 8 - 4 = 4 Wink

Author:  Martin [ Thu Nov 24, 2005 2:30 am ]
Post subject: 

Worked in Java. I don't have a C++ compiler at work.

Author:  md [ Thu Nov 24, 2005 2:32 am ]
Post subject: 

Hmmm... could it be that the evaluation doesn't follow normal bedmas rules? In that case it would certainly work... most interesting... Oh well, I'll give it a shot tomorrow once I get around to checking out gcc on linux

Author:  wtd [ Thu Nov 24, 2005 2:42 am ]
Post subject: 

Martin wrote:
c++:
#include <iostream>

using namespace std;

int main()
{
   int a = 4, b = 5;

   cout << a << b << endl;
   a = a + b - (b = a); // 4 + 5 - (4)
   cout << a << b << endl;

   return 0;
}


In half of two lines. Boo yeah!


Well, I did specify in response to Gandalf that the solution should not be "hackish", and I'd say this qualifies. Smile

For instance, make this work with two strings.

c++:
#include <iostream>
#include <string>

using namespace std;

int main()
{
   string a = "4", b = "5";

   cout << a << b << endl;
   a = a + b - (b = a); // 4 + 5 - (4)
   cout << a << b << endl;

   return 0;
}

Author:  [Gandalf] [ Thu Nov 24, 2005 3:18 am ]
Post subject: 

c++:
#include <iostream>
#include <string>

using namespace std;

int main()
{
   string a = "4", b = "5";

   cout << a << b << endl;
   a.swap(b);
   cout << a << b << endl;
   return 0;
}


Wink

Tony's program compiles and runs fine for me...

Author:  Martin [ Thu Nov 24, 2005 3:24 am ]
Post subject: 

Alright wtd, let's hear the solution.

Author:  wtd [ Thu Nov 24, 2005 4:24 am ]
Post subject: 

Just to make you all hate me...

c++:
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
   int a = 4, b = 5;

   cout << a << b << endl;
   swap(a, b);
   cout << a << b << endl;

   return 0;
}

Author:  Martin [ Thu Nov 24, 2005 7:01 am ]
Post subject: 

It's alright wtd. I've hated you ever since I decided to buy my iMac.

Author:  wtd [ Thu Nov 24, 2005 5:29 pm ]
Post subject: 

Here's a python question. Smile

Python:
class Student(object):
   def __init__(self, name, *grades):
      self.name = name
      self.grades = grades
   def __str__(self):
      return "%s has an average of %.2f" % (self.name, self.average_grade)


Add a single line of code which makes the above class work correctly. It must not only work, but also accurately report the student's average grade.

Author:  Hikaru79 [ Thu Nov 24, 2005 7:07 pm ]
Post subject: 

Python:
class Student(object):
   def __init__(self, name, *grades):
      self.name = name
      self.grades = grades
      self.average_grade = sum(*grades)/len(*grades)
   def __str__(self):
      return "%s has an average of %.2f" % (self.name, self.average_grade)
     
foo = Student ( "Adrian", [40,34,40,50,69] )

print foo

This okay?

EDIT: w00t! 600 posts Very Happy

Author:  wtd [ Thu Nov 24, 2005 7:10 pm ]
Post subject: 

Try that again after:

Python:
foo.grades.append(100)

Author:  wtd [ Mon Nov 28, 2005 11:24 am ]
Post subject: 

wtd wrote:
Here's a python question. Smile

Python:
class Student(object):
   def __init__(self, name, *grades):
      self.name = name
      self.grades = grades
   def __str__(self):
      return "%s has an average of %.2f" % (self.name, self.average_grade)


Add a single line of code which makes the above class work correctly. It must not only work, but also accurately report the student's average grade.


The solution:

Python:
class Student(object):
   def __init__(self, name, *grades):
      self.name = name
      self.grades = grades
   def __str__(self):
      return "%s has an average of %.2f" % (self.name, self.average_grade)
   average_grade = property(lambda self: float(sum(self.grades)) / len(self.grades))

Author:  rizzix [ Thu Dec 01, 2005 2:21 pm ]
Post subject: 

Write a Perl one-liner to print out the 8-12th lines of a file. (this means i should be able to execute the code with perl -e)

Author:  wtd [ Thu Dec 01, 2005 2:40 pm ]
Post subject: 

code:
perl -ne "BEGIN{$c=0}print if++$c>7&&$c<13" file_name_here

Author:  rizzix [ Thu Dec 01, 2005 3:02 pm ]
Post subject: 

hmm.. ok.. but may i add one more criteria?

Try and avoid the braces {}

Author:  rizzix [ Thu Dec 01, 2005 5:14 pm ]
Post subject: 

Write a Perl one-liner, but avoid using any {} blocks.

The one-liner should parse a file extracting all Java-like comments where nesting comments is not allowed. (i.e you can safely assume there are no nested comments)

Sample Input:
Java:
import java.awt.*;
import javax.swing.*;

public class test {
     public static void main(String[] args) {
         // insert your application initialization code here
        JFrame frame = new JFrame("Test Application"); /* create a new JFrame */
        Dimension screenSize = frame.getToolkit().getScreenSize();
       
        frame.getContentPane().add(new JLabel("Hello World!"))
        frame.setBounds(screenSize.width/4, screenSize.height/4,
                        screenSize.width/2, screenSize.height/2);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true); /* always the last SWING method in main*/
     }
}


Sample Output:
code:
  6: insert your application initialization code here
  7: create a new JFrame
 14: always the last SWING method in main

Author:  wtd [ Thu Dec 01, 2005 5:34 pm ]
Post subject: 

The simplest way I can think of does involve using the BEGIN block again.

Author:  wtd [ Thu Dec 01, 2005 7:31 pm ]
Post subject: 

Language: O'Caml

code:
# let h = Hashtbl.create 10;;
val h : ('_a, '_b) Hashtbl.t = <abstr>
# Hashtbl.add h "foo" 42;;
- : unit = ()
# Hashtbl.add h "bar" 27;;
- : unit = ()
# h;;
- : (string, int) Hashtbl.t = <abstr>


Now, we know that the Hashtbl module has a "fold" function which takes a function, a hashtable, and an initial value.

The function it takes accepts three arguments: the key of the current entry, the value of the current entry, and the "accumulator" value.

Knowing this, write an expression which retrieves the keys from "h" as a list of strings.

Author:  rizzix [ Thu Dec 01, 2005 8:26 pm ]
Post subject: 

rizzix wrote:
Write a Perl one-liner to print out the 8-12th lines of a file. (this means i should be able to execute the code with perl -e)


The solution...

Perl:
8 .. 12 and print while (<>)

Author:  wtd [ Thu Dec 01, 2005 8:52 pm ]
Post subject: 

rizzix wrote:
rizzix wrote:
Write a Perl one-liner to print out the 8-12th lines of a file. (this means i should be able to execute the code with perl -e)


The solution...

Perl:
8 .. 12 and print while (<>)


The parens shouldn't be necessary due to the way postfix loops work.

Author:  rizzix [ Thu Dec 01, 2005 9:07 pm ]
Post subject: 

yep... now solve the other one Wink

Author:  rizzix [ Mon Dec 05, 2005 8:22 pm ]
Post subject: 

rizzix wrote:
Write a Perl one-liner, but avoid using any {} blocks.

The one-liner should parse a file extracting all Java-like comments where nesting /* */ comments is not allowed. (i.e you can safely assume there are no nested /* */ comments)


The Solution...
Perl:
(s|.*/{2}(.*)|$1| or s|.*/\*|| .. s|\*/.*||) and s|\s*|| and printf "%3d: %s", $., $_ while <>



Breaking it down...

First we match /* to */ and extract contents within // to \n with the following regexs:
Perl:
s|.*/{2}(.*)|$1|
Perl:
s|.*/\*|| .. s|\*/.*||
Note: we use the substitution since we are only interested in the content that lies within these delimiters.

Then we trim out the whitespace off the result:
Perl:
s|\s*||
Finally we print it:
Perl:
printf "%3d: %s", $., $_

Author:  Hikaru79 [ Wed Dec 07, 2005 4:30 pm ]
Post subject: 

Holy mother of God. I'm oddly reminded of the bash.org quote that goes:
bash.org wrote:
s7ank: i want to be one of those guys that types
"s/j&jd//.^$ueu*///djsls/sm."
and it's a perl script that turns dog crap into gold.

Author:  md [ Wed Dec 07, 2005 5:46 pm ]
Post subject: 

My mind just went *boink*. You should really put warnings up before showing code like that...

Author:  wtd [ Tue Dec 13, 2005 5:28 am ]
Post subject: 

Java TYS:

code:
import java.util.*;

public class OldArrayListTest {
   public static void main(String[] args) {
      ArrayList a = new ArrayList();
      a.add("hello");
      a.add("world");
   }
}


Demonstrate the command that will compile this without warnings using the Java 1.5.0 compiler.

Author:  Hikaru79 [ Tue Dec 13, 2005 7:05 am ]
Post subject: 

Java:
import java.util.*;

public class OldArrayListTest {
   public static void main(String[] args) {
      ArrayList<String> a = new ArrayList<String>();
      a.add("hello");
      a.add("world");
   }
}


Like so? Smile

Author:  wtd [ Tue Dec 13, 2005 9:54 am ]
Post subject: 

Nope, but thanks for playing our game. The code I posted should compile without alteration.

Author:  Hikaru79 [ Tue Dec 13, 2005 3:48 pm ]
Post subject: 

wtd wrote:
Nope, but thanks for playing our game. The code I posted should compile without alteration.


Oooh. I misread the question. You want the actual command used to compile it. In that case,
code:
javac -nowarn OldArrayListTest.java
There Smile No more warning.

Author:  wtd [ Tue Dec 13, 2005 4:43 pm ]
Post subject: 

Hikaru79 wrote:
wtd wrote:
Nope, but thanks for playing our game. The code I posted should compile without alteration.


Oooh. I misread the question. You want the actual command used to compile it. In that case,
code:
javac -nowarn OldArrayListTest.java
There Smile No more warning.


Not quite there yet. Turning off warnings is cheating. Smile

Author:  Hikaru79 [ Tue Dec 13, 2005 5:09 pm ]
Post subject: 

wtd wrote:
Not quite there yet. Turning off warnings is cheating. Smile

Drat Sad But it technically does do what you asked Wink

How about this?
code:
javac -source 1.4 OldArrayListTest.java

Author:  wtd [ Tue Dec 13, 2005 5:26 pm ]
Post subject: 

Hikaru79 wrote:
wtd wrote:
Not quite there yet. Turning off warnings is cheating. Smile

Drat Sad But it technically does do what you asked Wink

How about this?
code:
javac -source 1.4 OldArrayListTest.java


It's about time you figured it out. Smile

Author:  wtd [ Wed Dec 14, 2005 8:15 pm ]
Post subject: 

O'Caml TYS:

Given a function "find" which takes a "'a list" and a "'a" and returns None if the list doesn't contain the specified element, and Some int indicating the position in the list if it does...

Take this code:

code:
match find some_list some_value with
   | None -> print_endline "Not found"
   | Some pos -> print_endline ("Found it at: " ^ string_of_int pos)


And modify it such that "Found it at: " becomes "Found it at even: " if the position is an even number. If it's odd, the message should remain the same as in the above code.

You may not use "if" or "else".

Author:  wtd [ Fri Dec 16, 2005 2:37 am ]
Post subject: 

Haskell TYS:

Reimplement Haskell's zipWith function. Replicate all of zipWith's functionality and behaviors. To avoid ambiguity, call your function "myZipWith".

You may not use "if", "case", or "|", and your function should consume at most two lines.

Author:  Cervantes [ Fri Dec 16, 2005 8:02 pm ]
Post subject: 

wtd wrote:
O'Caml TYS:

Given a function "find" which takes a "'a list" and a "'a" and returns None if the list doesn't contain the specified element, and Some int indicating the position in the list if it does...

Take this code:

code:
match find some_list some_value with
   | None -> print_endline "Not found"
   | Some pos -> print_endline ("Found it at: " ^ string_of_int pos)


And modify it such that "Found it at: " becomes "Found it at even: " if the position is an even number. If it's odd, the message should remain the same as in the above code.

You may not use "if" or "else".


code:
match find some_list some_value with
   | None -> print_endline "Not found"
   | Some pos when pos mod 2 == 0 -> print_endline ("Found it at even: " ^ string_of_int pos)
   | Some pos -> print_endline ("Found it at: " ^ string_of_int pos)

Author:  wtd [ Wed Dec 21, 2005 5:05 pm ]
Post subject: 

Ok smartguy...

Redefine List.map in terms of List.fold_left.

code:
let map f = ...

Author:  Geminias [ Tue Dec 18, 2007 6:10 pm ]
Post subject:  RE:test your skills (2005)

I guess I'll give her a go:

1. Do you know what all of the different uses of "const" or "static" mean?

const prevents an initialized value from changing. It can also be used to specify that a method will not change any data in the class. It can also be used in a function/method to prevent a certain parameter from being reassigned.

static is either a containment specifier that allows you to tell the compiler to store a variable in global memory, or it is something else that I dont know what it is called but allows you to specify static members or functions of a class so that you can access them without an instance of that class and the data is accessible by all instances of this class.

2. Do you understand why a normal class can be split into a header and a ".cpp" source file, but a templated class cannot?

This is not true, you can #include "object.cpp" at the bottom of the header file to give the compiler information about the template.

3. Do you understand why you shouldn't use identifiers beginning with two underscores, even though it's technically legal?

Someone told me that system libraries and so forth use the __ prefix on some of their variables. Other than that I really don't know.

4. Do you understand the difference between:
c++ / ++c

the first increments c and returns c before the inc. second incs and returns inc value.

5. Do you understand why one of the following works and the other doesn't?

the const keyword on the "a" variable prevents a from being assigned. In the second code the initializer form is used which is allowed. The details of this are sketchy to me because I thought

constructor : initialize(someVal)

translated to: initialize = someVal.

to be continued... please give feedback in the meantime

Author:  OneOffDriveByPoster [ Tue Dec 18, 2007 7:31 pm ]
Post subject: 

wtd @ Wed Jan 12, 2005 7:16 pm wrote:
In conjunction with number 2, I need to return zero to indicate the program finished successfully.
No; not really. Some versions of GCC are buggy in that respect though (IIRC). (I am making the assumption that posting to old TYS threads with answers, etc. is not necroposting).


: