Tuesday, May 28, 2013

Monday, May 27, 2013

Average storage

Write a simple program that reads integer numbers and prints average value of all read numbers after each reading. Use as little memory as possible.

Sunday, May 26, 2013

1,000,000 bytes

How much memory does sorted sequence of 1,000,000 bytes require to be stored?

Saturday, May 25, 2013

Strange javascript

alerter = function(x) {
  alert(x);
}
(function() {
  alerter("Test")
})()
The problem is, "Test" will never be printed. What's wrong?

Friday, May 24, 2013

chmod -x /bin/chmod

$ sudo chmod -x /bin/chmod
$ sudo chmod +x /bin/chmod
sudo: chmod: command not found
Err. What should I do now?

Thursday, May 23, 2013

Round

Let's define r(x), (x > 0) like the number of the the least non-zero position in the decimal number, i. e.
r(12.1) = -1
r(2)    = 0
r(12)   = 0
r(10)   = 1
etc.

Given, b > a > 0, find all numbers in (a,b) where r() has its maxima .

(The point of the problem is to find "most rounded" numbers between a and b).

Wednesday, May 22, 2013

ret

     mov  cx, 0
s:   cmp  cx, 000A
     je   end
     inc  cx
     mov  ax, [si]
     mov  [di], ax
     push s
     ret
end:
What and why does this code do?

Tuesday, May 21, 2013

Weak refs

Look at this Perl code:
use Scalar::Util qw( weaken );

my ( $weak_a, $weak_b, $weak_c );

{
        my $a = {
                name => 'a',
        };

        my $b = {
                a    => $a,
                name => 'b',
        };

        my $c = {
                a    => $a,
                b    => $b,
                name => 'c',
        };

        $a->{b} = $b;

        $weak_a = $a;
        $weak_b = $b;
        $weak_c = $c;

        weaken( $weak_a );
        weaken( $weak_b );
        weaken( $weak_c );
}

print $weak_a->{name};
print $weak_b->{name};
print $weak_c->{name};

What and why will be printed?

Monday, May 20, 2013

INC_AND_READ

Imagine you have a shared object containing integer value that supports three atomic operations:
  • READ (read value)
  • INC_AND_READ (increment and read value)
  • DEC (decrement value)
The init value is 0.

How do you implement mutex and semaphore using this object?

Sunday, May 19, 2013

Lost minus

def quiz
    a = Proc.new do
        return 1
    end
    
    b = Proc.new do
        return -1
    end
    
    c = Proc.new do |x, y|
        return x.call * y.call
    end
    
    return c.call(a,b)
end

puts quiz
This Ruby script prints "1\n". Why?

Saturday, May 18, 2013

if 0;

There are a number of Perl scripts starting with:
#!/usr/local/bin/perl 
eval 'exec perl $0 ${1+"$@"}' if 0;
Why?

Friday, May 17, 2013

string constant

What's a point of using string constants in this Ruby code?
ANIMAL3 = 'rat'
ANIMAL6 = 'rabbit'
def animal3to6(animal)
  length = animal.length
  if length > 6
    return ANIMAL6
  elsif length < 3
    return ANIMAL3
  else
    return animal
  end
end

Thursday, May 16, 2013

self-call

Malware programs often use code like this:
   call a
a: pop ax
Why?

Wednesday, May 15, 2013

Overriding VS overloading

There is following Java code:
import java.io.*;
class Animal {
    public String sound() {
        return "[no]";
    }
}

class Cat extends Animal {
    public String sound() {
        return "mew";
    }
}

class Dog extends Animal {
    public String sound() {
        return "bow-wow";
    }
}

public class Quiz {
    private static String default_name(Animal a) {
        return "animal";
    }

    private static String default_name(Cat c) {
        return "Shoelace";
    }

    private static String default_name(Dog d) {
        return "Pluto";
    }

    public static void main(String[] args) {
        Animal a = new Dog();

        System.out.println(
            default_name(a) + " says " + a.sound()
        );
    }
}
What and why will be printed?

Monday, May 13, 2013

C magic

Your C compiler almost certainly recognizes this idiom and compiles it to a single processor instruction.
unsigned int x, y;
y = (x << shift) | (x >> (sizeof(x)*8 - shift));
What instruction is that ?

Sunday, May 12, 2013

DNS record error

DNS records for domain.com look like this:
domain.com    IN  SOA   ...
@             IN  NS    ns1.hoster.com
@             IN  NS    ns2.hoster.com
@             IN  MX 10 mx.yandex.ru.
domain.com    IN  A     89.89.89.89
*.domain.com  IN  A     89.90.90.90
But domain.com and blog.domain.com still aren't resolved. What's a problem?

Saturday, May 11, 2013

Perl+Ruby code

$perl = 1 if nil;
eval '
        if ( 2 > 1 ) {
                print "Hi, I\'m Perl!\n";
        }
' if $perl;
eval '
        if 2 > 1
                puts "Hi, I\'m Ruby"
        end
' if ! $perl;
This approach allows you to write scripts that can be understood by both Perl and Ruby interpreters (It should never be used in real life though).

Find a way to do the same with Python+Ruby (or try any other pair of languages you know).

Friday, May 10, 2013

ls columns

Have you ever wondered why "ls" shows you columns but works perfectly with other unix utils, as though every filename is placed on its own line?
$ ls
file_a file_f file_k file_p file_u file_z
file_b file_g file_l file_q file_v
file_c file_h file_m file_r file_w
file_d file_i file_n file_s file_x
file_e file_j file_o file_t file_y
$ ls | wc
     26      26     182
$ ls | grep w
file_w

Thursday, May 9, 2013

9 May

Today is Victory Day in Russia, so we need to add some plot in the quiz.

Marshal Zhukov has a database that helps him to fight. It contains "tank_types" relation that looks like this:
 name | secret_name | ...
------+-------------+-----
 T-28 | UQCFIQUGCVA | ...
 T-34 | JBHVCAIOAOA | ...
 T-45 | NVFAFOEAGQF | ...
 ...  | ...         | ...
Of course both "name" and "secret name" are unique and have corresponding constraints.

Every day Stalin emails the list of new secret names for some tank types. All data in emails is always valid. Zhukov orders one of his officers to write a script that helps him renew data in the database according to daily emails.

The officer runs vim and write the following ruby script:
data = Email.new('...').get_data
data.each do |name, secret_name|
  query(
    'UPDATE tank_types SET secret_name = ? WHERE name = ?',
    secret_name, name
  )
end
Checking this script Zhukov immediately sees a problem that it may cause. What's a problem? How to fix that?

Wednesday, May 8, 2013

Gap finder

There is some database-relation called "t". It's know that the result of
SELECT x FROM t;
has following form:
a
a+1
a+2
...
a+k1-1
a+k1+1
...
a+k2-1
a+k2+1
...
a+kn-1
a+kn+1
...
a+b-1
a+b
Mind, that ki + 1 < ki+1.

Write SQL query that returns:
a+k1
a+k2
...
a+kn.
Don't use cool features like Postgres generate_series.

Tuesday, May 7, 2013

a=b, b=a

We have some piece of legacy Perl code:
my $args = My::Args->get();
my $length = $args->{length};
foreach my $element( @list ) {
    action1( $element );
    try { action2( $element ); $args->{length} = $length; };
    action3( $element );
}
It's extremely ugly and also has one logical mistake. Try to find that mistake and guess why such a code ever existed.

Monday, May 6, 2013

The "same" return type

Look at this piece of C++ code:
#include <string>
#include <iostream>

using namespace std;

class Animal {
    public:

    string color;

    virtual Animal * clone() {
        Animal * new_animal = new Animal(*this);
        return new_animal;
    }
};

class Dog : public Animal {
    public:

    int fangs;

    Dog() : fangs(4) {}

    Dog * clone() {
        Dog * new_dog = new Dog(*this);
        return new_dog;
    }
};

class Cat : public Animal {
    public:

    int tail_length;

    Cat() : tail_length(10) {}

    Cat * clone() {
        Cat * new_cat = new Cat(*this);
        return new_cat;
    }
};

class Shop {
    public:

    string animals_color;

    Animal * new_like(Animal * a) {
        Animal * new_animal = a->clone();
        new_animal->color = this->animals_color;
        return new_animal;
    }
};

int main(void) {
    Cat c;
    c.color = "white";

    Shop s;
    s.animals_color = "black";

    Cat * new_cat = dynamic_cast<Cat*>(s.new_like(&c));

    cout << new_cat->color;
}

As you can see, dynamic_cast is used here ("static" is also suitable though), because we know that the return type of new_like() is always the same as its argument (as it uses clone() inside).

Of course this is ugly. How do you improve this without significant changes?