Showing posts with label Puzzle. Show all posts
Showing posts with label Puzzle. Show all posts

Thursday, June 1, 2023

C# Puzzle No.25 (intermediate)

Let's have list of references to objects of a custom type that have a state. Let's loop through the list and alter the internal state of each object on the list.

Will the change of the internal state be preserved after the loop ends?

A first answer should of course be yes.

Take a look at this then:

var elements =
    Enumerable.Range(0, 10)
        .Select( i => new Foo() { Bar = i });

foreach ( var e in elements )
{
    // yields 0,1,2,3,4,5,6,7,8,9 which is correct
    Console.WriteLine( e.Bar );
}

foreach ( var e in elements )
{
    e.Bar += 10;

    // yields 10, 11, ...., 19
    Console.WriteLine( e.Bar ); 
}

foreach ( var e in elements )
{
    // yields 0,1,2,3,4,5,6,7,8,9 which doesn't seem correct 
    // (original values restored)!
    Console.WriteLine( e.Bar );
    
    // expected: 10, 11, ..., 19!
}


public class Foo
{
    public int Bar { get; set; }
}

First we create a list of elements. Then we loop it to check if it's correct. Then we loop it to alter the internal state of objects.

Then we loop again and, oddly, it seems like original values are restored.

Not that obvious to spot what's wrong here, a similar issue was caught on production code. The goal is to find a simplest fix.

Friday, August 26, 2022

TypeScript puzzle No.2 (easy)

Consider following code

class Foo {
  bar() {
    return 1
  }
}

const foo = new Foo
foo.bar()

Now consider that for some reason we want to include a type assertion, rather than just foo we want foo as Foo.

class Foo {
  bar() {
    return 1
  }
}

const foo = new Foo
(foo as Foo).bar()

Surprisingly, this one doesn't compile, the error points to the last line and says

Block-scoped variable 'foo' used before its declaration

As always, your goal is to explain the unexpected behavior here.

Friday, July 30, 2021

Javascript Puzzle No.2

Given the code
let working = {
  foo: function() {
    console.log("working");
  }
};

let notworking = {
  foo() {
    console.log("notworking");
  }
}

new working.foo();
new notworking.foo();
and its output
Uncaught TypeError: notworking.foo is not a constructor
please explain why this particular function cannot be used as a constructor function.

Hint: based on this SO question where the explanation is provided.

Thursday, April 15, 2021

C# Puzzle No.24 (intermediate)

Given a generic interface definition
public interface IDoSomething : IDisposable { }
please explain why this is possible
class DoesSomething<String> : IDoSomething<String>
{
    public void Dispose()
    {
    }
}
and this is not possible (doesn't compile)
class DoesSomething<string> : IDoSomething<string>
{
    public void Dispose()
    {
    }
}
An explanation can be found here.

Thursday, September 28, 2017

Javascript Puzzle No.1 (beginner)

For few years I've been posting C# puzzles here, each puzzle was about a language feature or an unexpected semantics of some base class library methods. This post starts a new series, Javascript puzzles. Here's the first, easy one. Consider following generator function
function* foo()
{
    var n = 0;
    while ( true ) {
        yield n++;
    }
}
This seemingly creates an infinite enumeration of 0, 1, 2, etc. However, a simple test
for ( var i=0; i<10; i++ )
{
    console.log( foo().next().value );
}
reveals it doesn't really do what it's supposed to
0
0
0
0
0
0
0
0
0
0
The question here is to explain the incorrect behavior of the generator.

Thursday, December 12, 2013

C# Puzzle No.23 (intermediate)

Closures are interesting and helpful. In short, closure is a function that can be exposed to the outside world that captures part of its external environment, even though the environment could be private to outside world.

This puzzle involves following short snippet inspired by the Javascript: Definitive Guide book

// create array of 10 functions
static Func<int>[] constfuncs()
{
    Func<int>[] funcs = new Func<int>[10];
 
    for ( var i = 0; i < 10; i++ )
    {
        funcs[i] = () => i;
    }
 
    return funcs;
}
 
...
 
var funcs = constfuncs();
for ( int i = 0; i < 10; i++ )
    Console.WriteLine( funcs[i]() );
 
// output:
// 10
// 10
// ...
// 10

Side note: closures in Javascript work very similar and the output of corresponding Javascript snippet would be the same

function constfuncs() {
  var funcs = [];
  for(var i = 0; i < 10; i++)
  {
    funcs[i] = function() { return i; };
  }
  return funcs;
}
 
var funcs = constfuncs();
for ( var i = 0; i < 10; i++ )
    console.log( funcs[i]() );

End of side note

Your task here is not only to explain the behavior (easy part) but also correct the inner loop of the constfuncs method so that the code outputs

0
1
2
3
4
5
6
7
8
9

More specifically, you are allowed to modify only this line of code

funcs[i] = () => i;

You are free to propose a solution for the JavaScript version as well. The book doesn’t provide one, if you are interested.

Thursday, December 2, 2010

C# Puzzle No.22 (beginner)

The .FirstOrDefault(…) LINQ’s method is quite handy until you realize that “default” in fact means default(T) which then means “null” if you deal with reference types. This could cause problems if you expect anything but null.

class Program
{
    static void Main( string[] args )
    {
        List<User> Users = 
             new List<User>() { new User() { Name = "u1" } };
 
        var name = 
            Users
                .FirstOrDefault( u => u.Name == "u2" )
                // boom! FirstOrDefault returns null
                .Name;
 
        Console.WriteLine( name );
        Console.ReadLine();
    }
}
 
class User
{
    public string Name;
}

What if you have a Null Object you’d like to provide as the “default” instead of default(T)?

class User
{
    public string Name;
 
    public static User NullValue
    {
        get
        {
            return new User() { Name = "NULL" };
        }
    }
}

The easiest workaround is to add an additional, overloaded version of FirstOrDefault which could accept a reference to an object which should be returned as the “default”:

class Program
{
    static void Main( string[] args )
    {
        List<User> Users = new List<User>() { new User() { Name = "u1" } };
 
        var name = 
            Users
                // use new, overloaded FirstOrDefault implemented below
                .FirstOrDefault( u => u.Name == "u2", User.NullValue )
                .Name;
 
        Console.WriteLine( name );
        Console.ReadLine();
    }
}
 
public static class LinqExtension
{
    public static T FirstOrDefault<T>( 
        this IEnumerable<T> Entites, 
        Func<T, 
        bool> Predicate, 
        T Default )
    {
        var entity = Entites.FirstOrDefault( Predicate );
 
        // return provided Default if there are no matching entities
        if ( (object)entity != (object)default( T ) ) 
            return entity;
        else
            return Default;
    }
}
 
class User
{
    public string Name;
 
    public static User NullValue
    {
        get
        {
            return new User() { Name = "NULL" };
        }
    }
}

Your goal is to achieve the same effect but with no new extension methods. In other words – you are restricted to the standard set of LINQ operators.

class Program
{
    static void Main( string[] args )
    {
        List<User> Users = new List<User>() { new User() { Name = "u1" } };
 
        var name = 
            Users
                // linq query here which returns the matching object
                // or User.NullValue as the "default"
                // so that this field reference below always succeeds 
                .Name;
 
        Console.WriteLine( name );
        Console.ReadLine();
    }
}
 
class User
{
    public string Name;
 
    public static User NullValue
    {
        get
        {
            return new User() { Name = "NULL" };
        }
    }
}

Friday, June 25, 2010

C# Puzzle No.21 (beginner)

Is it possible to call a method on a null object reference? Of course, not!

static void Main( string[] args )
{
    Foo _foo = null;
 
    // will throw NullReferenceException
    Console.WriteLine( _foo.Bar() );
 
    Console.ReadLine();
}

Oh, really?

Your goal is to provide all necessary auxiliary definitions and implementations so that the code above not only does not throw NullReferenceException but also writes “Hello world” at the console.

Wednesday, June 16, 2010

C# Puzzle No.20 (intermediate)

Suppose you are writing a class for a generic vector and you want to naively implement a method to add two vectors:

public class Vec<T>
{
    public T x { get; set; }
    public T y { get; set; }
 
    public Vec() { }
    public Vec( T x, T y ) { this.x = x; this.y = y; }
 
    public static Vec<T> Add( Vec<T> v1, Vec<T> v2 )
    {
        return new Vec<T>( v1.x + v2.x, v1.y + v2.y );
    }
}

This won’t work. The compiler is unable to interpret the “+” for type T so v1.x + v2.x cannot be compiled.

One of possible approaches could be to restrict possible Ts with a type constraint so that “+” can be replaced with a method of an interface implemented by T. Such approach, however, does not take you anywhere since you cannot impose an interface on an existing type and thus, Vec<int> or Vec<double> would still fail to compile.

Another common approach is to define an auxiliary interface:

public interface IAdder<T>
{
    T Add( T t1, T t2 );
}

so that Vec::Add can be now implemented as:

public static Vec<T> Add( Vec<T> v1, Vec<T> v2, IAdder<T> Adder )
{
    return new Vec<T>( Adder.Add( v1.x, v2.x ), Adder.Add( v1.y, v2.y ) );
}

and used:

public class IntAdder : IAdder<int>
{
    public int Add( int t1, int t2 )
    {
        return t1 + t2;
    }
}
 
class Program
{
    static void Main( string[] args )
    {
        Vec<int> v1 = new Vec<int>( 4, 5 );
        Vec<int> v2 = new Vec<int>( 6, 7 );
 
        Vec<int> v3 = Vec<int>.Add( v1, v2, new IntAdder() );
 
        Console.ReadLine();
    }
}

While this works, there are obvious drawbacks – an extra implementation of the auxiliary interface has to be provided for any T you want to use your Vec class with. Also, the signature of the Add method is now rather clumsy.

Let’s then just start again:

public class Vec<T>
{
    public T x { get; set; }
    public T y { get; set; }
 
    public Vec() { }
    public Vec( T x, T y ) { this.x = x; this.y = y; }
 
    public static Vec<T> Add( Vec<T> v1, Vec<T> v2 )
    {
       // ???
    }
}

Your goal is to provide valid implementation of the Add method so that the returning vector is a sum of two provided vectors and the generic class works for built-in numeric types. You are not allowed to use reflection (or any BCL API) but rather depend solely on the features of the C# language.