Programming 2, Summer 2022
Week 3: Exercises

1. Printing with Commas

Write a program that reads a single line containing an integer which may be arbitrarily large, and writes the integer with embedded commas.

Input:

28470562348756298345

Output:

28,470,562,348,756,298,345

2. Integer Conversions

What value do you think each of these programs will print?

a)

int i = 300;
WriteLine((byte) i);

b)

int j = 200;
WriteLine((sbyte) j);

c)

int k = 1050;
WriteLine((int) (byte) k);

d)

long l =  256_256_256_256;
WriteLine((long) (byte) (short) (int) l);

3. Halving and Squaring

We learned in the lecture that a double is a 64-bit floating point number with a 1-bit sign S, an 11-bit signed exponent E and a 52-bit mantissa M. The mantissa is a number between 1 and 2, represented in binary. The value of the floating-point number is basically

S · M · 2E

What values do you think these programs will print, at least approximately?

a)

int i = 1;
for (double d = 1.0; d > 0 ; d /= 2)
    i += 1;
WriteLine(i);

b)

int i = 1;
for (double d = 0.5; d > 0 ; d = d * d)
    i += 1;
WriteLine(i);

4. 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.

Input:

2 4 6 8
8 6 4 2
1 3 7 9
9 7 3 1

Output:

9 1 8 2
7 3 6 4
3 7 4 6
1 9 2 8

5. Zombies

Some zombies are chasing a player. Here is a top-down view:

Image credit: © Copyright 2014-2020, Juan Linietsky, Ariel Manzur and the Godot community (CC-BY 3.0)

Each zombie can see infinitely far in a 180° field of view as indicated by the light blue half-circular shapes above. In the picture above, zombie A can see the player, but zombie B cannot.

Write a program that reads, on three lines:

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".

6. Integer Square Root

Write a program that reads an integer n, and computes and prints the integer square root of n, i.e. the non-negative integer i such that i2 = n. If no such integer exists, print "not a square". Do not call any library functions. Your method must run in time O(log N) in the worst case.

7. 3-D Tic-Tac-Toe

The game of 3-D Tic-Tac-Toe is played on a 4x4x4 cube of cells. As in ordinary Tic-Tac-Toe, players take turn placing marks X or O. The winner is the first player to form four in a row in any direction:

Write a program that alllows two players to play 3-D Tic-Tac-Toe. After each move, the program should print out the board in a format such as this:

...X
....
.O..
X..O

....
....
.O.O
..OX

...X
..OX
.O.O
OO.X

XX.X
XXO.
.OO.
O..X

Each player should enter their move as three digits (each from 0-3) representing a level, row, and column number. For example, '303' would represent the upper-right square in the lowest level.