Programming 2
Week 2: Notes

This week we learned about more features of C# including integer and floating-point types, numeric conversions, the 'do', 'foreach' and 'switch' statements, the conditional operator (?:), and single- and multi-dimensional arrays.

You can read about these topics in chapters 2-4 of Essential C#.

Tutorial programs

We solved these exercises in the tutorial:

Rotate a Matrix

Write a program that reads an N x N matrix of integers and prints it out rotated 90 degrees to the right.

using static System.Console;

class Program {
    static void Main(string[] args) {
        string s = ReadLine();
        string[] words = s.Split(null);
        int n = words.Length;

        int[,] a = new int[n, n];

        // first row
        for (int i = 0 ; i < n ; ++i)
            a[0, i] = int.Parse(words[i]);

        // remaining rows
        for (int r = 1 ; r < n ; ++r) {
            words = ReadLine().Split(null);
            for (int c = 0 ; c < n; ++c)
                a[r, c] = int.Parse(words[c]);
        }

        // print out rotated matrix

        for (int c = 0 ; c < n ; ++c) {
            for (int r = n - 1 ; r >= 0 ; --r)
                Write($"{a[r, c]} ");
            WriteLine();
        }
    }
}

Zombies

Some zombies are chasing a player. Each zombie can see infinitely far in a 180° field of view. Write a program that reads the X-Y position of the player, the X-Y position of a zombie, and the direction vector f indicating the direction the zombie is facing. Each position or vector is a pair of floating-point numbers. The program should print "can see" if the zombie can see the player, otherwise "cannot see".

using static System.Console;

class Program {

    // Read N coordinates on a single line and 
    // parse them into N doubles.
    static double[] read_coords() {
        string[] words = ReadLine().Split(null);
        
        double[] r = new double[words.Length];
        for (int i = 0 ; i < words.Length ; ++i)
            r[i] = double.Parse(words[i]);
        return r;
    }

    static void Main(string[] args) {
        double[] player = read_coords();
        double[] zombie = read_coords();
        double[] zombie_dir = read_coords();
        double[] zombie_to_player = { player[0] - zombie[0], player[1] - zombie[1] };

        double dot_prod = zombie_to_player[0] * zombie_dir[0] + 
                          zombie_to_player[1] * zombie_dir[1];

        WriteLine(dot_prod > 0 ? "can see" : "cannot see");
    }
}