Monday, March 14, 2011

Tic tac toe

For my second object oriented programming module. we were told to write an unbeatable tic tac toe playing machine.
(not exactly big blue or Watson, but fun nonetheless)

#include <iostream>
#include <string>
#include <vector>
using namespace std;

bool isWin(vector<vector<int> > board, int playerNum){

int size = board.size();

//check verticals
for(int row=0; row<size; row++){
bool win = 1;
for(int col=0, player=board[row][col]; col<size; col++){
if(player!=playerNum || player!=board[row][col]) {
win = 0;
break;
}
}
if(win==1) return 1;
}

//check horizontals
for(int col=0; col<size; col++){
bool win = 1;
for(int row=0, player=board[row][col]; row<size; row++){
if(player!=playerNum || player!=board[row][col]) {
win = 0;
break;
}
}
if(win==1) return 1;
}

//check forward diagonal
bool win = 1;
for(int diag=0, player=board[diag][diag]; diag<size; diag++){
if(player!=playerNum || player!=board[diag][diag]){
win=0;
break;
}
}
if(win==1) return 1;

//check backward diagonal
win =1;
for(int diag=0, player=board[diag][size-diag-1]; diag<size; diag++){
if(player!=playerNum || player!=board[diag][size-diag-1u]){
win=0;
break;
}
}
if(win==1) return 1;

return 0;
}

//print the gui
void printBoard(vector<vector<int> > board){
unsigned int size = board.size();
for(unsigned int row=0; row<size; row++){
for(unsigned int col=0; col<size; col++){
string mark = " ";
if(board[row][col]==1){
mark = "X";
}
else if (board[row][col]==2){
mark = "O";
}
cout << mark;
if(col==(size-1)) cout<<endl;
else cout<<" | ";
}
if(row!=size-1) cout << " ---------";
cout<<endl;
}
}

//generate a vector of possible board configurations
vector<vector<vector <int > > > getAllPossibleMoves(vector<vector<int > > board, unsigned int player){
vector<vector<vector <int > > > allPossibleMoves;
unsigned int size = board.size();
for(unsigned int row=0; row<size; row++){
for(unsigned int col=0; col<size; col++){
if(board[row][col] == 0){
board[row][col] = player;
allPossibleMoves.push_back(board);
board[row][col] = 0;
}
}
}
return allPossibleMoves;
}

//return 1 if board is full, otherwise 0
bool boardFull(vector<vector<int> > board){
unsigned int size = board.size();
for(unsigned int row=0; row<size; row++){
for(unsigned int col=0; col<size; col++){
if(board[row][col]==0) {return 0;}
}
}
return 1;
}

int nextBestMoveSub(vector<vector<int> > board, bool isNextMove){
if((isNextMove==1) && isWin(board,1) ){
return 2;
}
isNextMove = 0; //no longer the next move, have to play more moves
if(isWin(board,1)) return 1;//if this move wins return win
//return draw if board is full
if(boardFull(board))return 0;


vector<vector<vector<int> > > allOpponentsPossibleMoves = getAllPossibleMoves(board,2);
unsigned int opponentsMoves = allOpponentsPossibleMoves.size();

//check if opponent won, if he did, this move is sure lose.
for(unsigned int opponentMove=0; opponentMove<opponentsMoves; opponentMove++){
if(isWin(allOpponentsPossibleMoves[opponentMove],2)) return -1;
}

int outcome = 1;
//check if any of my future moves would result in a win.
for(unsigned int opponentMove=0; opponentMove<opponentsMoves; opponentMove++){
vector<vector<vector<int> > > allMyPossibleMoves = getAllPossibleMoves(allOpponentsPossibleMoves[opponentMove],1);
unsigned int myMoves = allMyPossibleMoves.size();

int myBest = -1;
//for each of my possible moves, check for the best possible outcome
for(unsigned int myMove=0; myMove<myMoves; myMove++){
int winLoseDraw = nextBestMoveSub(allMyPossibleMoves[myMove], isNextMove);
myBest = (winLoseDraw>=myBest)?winLoseDraw:myBest;
}

//for each of the opponents move, check for the worst possible outcome
outcome = (myBest<=outcome)?myBest:outcome;
}

return outcome;
}

vector<vector<int> > nextBestMove(vector<vector<int> > board){
vector<vector<int> > bestMove;
bool foundWin = 0;

vector<vector<vector<int> > > allMyPossibleMoves = getAllPossibleMoves(board,1);
unsigned int myMoves = allMyPossibleMoves.size();

//for each of my possible moves, check if it results in win, if so return win
for(unsigned int myMove=0; myMove<myMoves; myMove++){
int winLoseDraw = nextBestMoveSub(allMyPossibleMoves[myMove], 1);
if(winLoseDraw==2) return allMyPossibleMoves[myMove];//next move win, return it
if(winLoseDraw==1){
bestMove = allMyPossibleMoves[myMove];//sure win in unknown number of moves
foundWin = 1;
}
if(bestMove.size()==0) bestMove = allMyPossibleMoves[myMove];//not initialized, just take the move as default
if(!foundWin && winLoseDraw==0) bestMove = allMyPossibleMoves[myMove];//if winning move haven't been found, take draw
}
return bestMove;

}


void playGame(){
while(true){
//initialize the board
const unsigned int size = 3;
vector<vector<int> > board = vector<vector<int> >(size);
for(unsigned int i=0; i < size; i++){
board[i] = vector<int>(size);
}

//randomly choose a spot to move to

srand(time(NULL));
unsigned int firstMoveRow = rand()%size;
unsigned int firstMoveCol = rand()%size;

board[firstMoveRow][firstMoveCol]=1;

//print board
printBoard(board);

int outcome = 0;
//while board still has movable space
while(!boardFull(board)){

unsigned int row = 0;
unsigned int col = 0;

//ask user for input
while(true){
cout<<"please make a move by entering row and col numbers (eg: for the first square, 0 0)"<<endl;
cin>>row>>col;

if(cin.fail()||(row<0)||(row>=size)||(col<0)||(col>=size)){
cout<<"input error, please try again"<<endl;
cin.clear();
cin.ignore(1000, '\n');
continue;
}

//check if spot is taken
if(board[row][col]!=0){
cout<<"spot already taken, please try again"<<endl;
printBoard(board);
}else{
board[row][col]=2;
//print board
printBoard(board);
break;
}
}
if(isWin(board, 2)){
outcome = 2;
break;
}

//nextMove(board)
cout<<"my move"<<endl;
board = nextBestMove(board);

//print board
printBoard(board);

if(isWin(board,1)){
outcome = 1;
break;
}
}

vector<string> endGameMessage(3);
endGameMessage[0] = "We draw, you want to play again(y,n)?";
endGameMessage[1] = "I win!, you want to play again(y,n)?";
endGameMessage[2] = "You Win!!, this should never have happened, you want to play again(y,n)?";

cout<<endGameMessage[outcome]<<endl;
string playAgain = "n";
cin>>playAgain;
if(playAgain!="y") return;
}
}


int main (){
playGame();
//assignment1Question2();
//assignment1Question2();
//testIsTrivial();
//problem1();
return 0;
}

Decimal to Binary manipulations

For my first object oriented programming module, (it's been awhile since I did this in Comp Science, Memories!)
We were told to write an algorithm that would change a decimal number to binary numbers.

This was further extended to printing only the non trivial (sum of all bits not equal to one) and constant auto-correlating bits for number 0 to 2^14.

The code for decimal to bin
#include <string>
#include<fstream>
using namespace std;

//takes an int and returns the binary representation as a string
string decToBin(unsigned int intToConvert, unsigned int size){

register unsigned int tempInt = intToConvert;
string binRep="";
unsigned int i = 0;
do{
i++;
binRep = char((tempInt & 1u)+48u) + binRep;
tempInt >>= 1;
}while(i<size);

return binRep;
}


void assignment1Question1(){
const unsigned int size = 15u;
unsigned int maxBinarySize = 1<<size;
ofstream out("binary15.txt");
for (unsigned int i=0; i<maxBinarySize; i++){
out<<decToBin(i,size)<<endl;
}
}

int main(){
assignment1Question1();
return 0;
}



The code for const auto correlation and non trival
#include <string>
#include<fstream>
using namespace std;

//takes an int and returns the binary representation as a string
string decToBin(unsigned int intToConvert, unsigned int size){

register unsigned int tempInt = intToConvert;
string binRep="";
unsigned int i = 0;
do{
i++;
binRep = char((tempInt & 1u)+48u) + binRep;
tempInt >>= 1;
}while(i<size);

return binRep;
}

//MIT HAKMEM count
int sumOfBits(unsigned int test){

register unsigned int tmp;
tmp = test - ((test >> 1) & 033333333333)
- ((test >> 2) & 011111111111);
return ((tmp + (tmp >> 3)) & 030707070707) % 63;
}

//checks if an integer is of constant auto correlation
bool isConstAutoCor(unsigned int test, unsigned int size){
unsigned int shifted = test;
unsigned int autoCorNum = 0;
bool firstPass = 1;
//shift the bits, size-1 times to check for autocorrelation
for(unsigned int i=1; i < size; i++){
//shift the bits to the right
shifted = (shifted >> 1) | ( (1u & shifted) << (size-1));
//AND the shifted value with the test value to find the autoCorrelation number
unsigned int bitCount = sumOfBits(test & shifted);
//on first pass, set the autocorrelation number
if(firstPass==1){
firstPass=0;
autoCorNum = bitCount;
}
//on subsequent passes, check if the new autoCorrelation number is the same as the AC numbers found so far
else if(bitCount != autoCorNum){
return 0;
}
}
//only true if all autocorrelation numbers are equal
return 1;
}

//checks if an int is trivial
bool isTrivial(unsigned int test, unsigned int size){
unsigned int sum = sumOfBits(test);
if((sum <= 1) || (sum >= size-1)){
return 1;
}
return 0;
}

void assignment1Question2(){
const unsigned int size = 15u;
unsigned int maxBinarySize = 1<<size;
ofstream out("binary15a.txt");
for (unsigned int i=0; i<maxBinarySize; i++){
//we are looking for non trivial AND constant auto correlated binaries
if(!isTrivial(i, size)&&isConstAutoCor(i,size)){
out<<decToBin(i,size)<<endl;
}
}
}

int main(){
assignment1Question2();
}

If I were a Bond fund Manager with a mid term view

We were told by our Bond's Professor (can somebody say shaken not stirred) to imagine we were bond fund managers with a mid term view.

This is what our bond fund would look like:

Bond Portfolio Strategy

a) Investment objective

The objective of the bond portfolio recommended in this paper (Excalibur US Bond Portfolio) seeks to earn better returns than that of an identified benchmark index fund. Excalibur would achieve higher returns through the use of an index plus strategy. The Portfolio seeks current income, with capital appreciation and growth of income, by investing at least 20% of its net assets in bonds of governments and government agencies, 75% in corporate bonds issued in the US and the rest of it in cash. The asset-mix will be a diversified portfolio of fixed income instruments of varying maturities.

b) Benchmark

The benchmark index for Excalibur will be the PIMCO Total Return Fund (Bloomberg Code: PTTRX US, refer to Appendix A) where its objective is maximum total return, consistent with preservation of capital and prudent investment management. The Fund invests at least 65% of its assets in a portfolio of investment-grade fixed income instruments of varying maturities. The annualized 5 year return is 8.29%. .

c) Strategy

Excalibur will be adopting an index plus strategy with 20% invested in PIMCO’s top 10 holdings to achieve preservation of capital, the remaining 75% holdings will be actively managed, leaving behind 5% in cash. The Portfolio seeks to achieve alpha through active management in the selection of corporate bonds. Given various analysts’ calls that 2011 would potentially be the year where equities outperform bonds, it is essential to identify areas of alpha to outperform a pure capital preservation portfolio, e.g. PTTRX US.

The actively managed Excalibur will take the form of a bullet portfolio with majority of the holding held in medium term corporate bonds. While the US Bond market is divided into six sectors; namely, U.S. Treasury, agency, municipal, corporate, asset-backed securities and mortgage sector. In lieu of the Portfolio restriction to invest in high grade bonds (A rating and above), there will not be any asset-backed securities and mortgage sector in the bond holdings.

The reasons for adopting such a strategy are as such:

i. Existence of a Sweet Spot

Research conducted by the Excalibur research department reviews that there exist a sweet spot in the middle term range in specific industries. These bonds are least affected by any interest rate volatility. The sweet spot issues currently have a higher credit spread as opposed to similar issues of shorter and longer maturity terms. The existence of such higher credit spread in an improving economic environment has been shown to act as a buffer to interest rate volatility (Refer to Appendix B: “Assessing the trade-off between credit risk and rate risk.” Goldman Sachs).

ii. Interest rates Movement

The US Federal Reserve rate has been at a low of 0.25 per cent since 2009. Although, it is forecasted that the central bank is unlikely to raise the short term interest rates in the near future. However, there is a likely chance that long term interest rates would be raised. In such an event, long term bond prices are expected to fall thereby making the bullet strategy more favourable as compared to the barbell and ladder strategies.

iii. Portfolio Duration

Investing in high coupon, high yield to maturity issues lowers our portfolio duration thereby protecting Excalibur in the event of rising interest rates.

iv. Portfolio Flexibility

Excalibur, with its low duration and relative immunity to interest rate movements bequeaths it the flexibility of changing its mix when better yields are expected in other sectors or maturities.

v. Investors Objective

Excalibur is targeted mainly at investors with medium term investment horizon (5 to 10 years).

d) Portfolio Allocation

i. Passive management – 20% in Pimco’s Top 10 Holdings

PIMCO TOP 10 HOLDINGS

Allocation

T-NOTE 2.500 30-Jun-2017

3.095%

T-NOTE 3.500 15-May-2020

2.984%

T-NOTE 3.125 30-Apr-2017

2.842%

T-NOTE 2.125 31-May-2015

2.148%

FNCL 4.500 2010

1.729%

T-NOTE 2.750 31-May-2017

1.709%

T-NOTE 3.625 15-Feb-2020

1.445%

BNTNF 10 01-01-2012

1.292%

T-NOTE 2.500 30-Apr-2015

1.146%

T-NOTE 0.625 30-Jun-2012

1.051%

Figure 4: Pimco Total Return Fund, Top 10 Holdings as at Nov 30, 2010

ii. Active management – 75% in Corporate Bonds

CORPORATES

Allocation

Coupon

Maturity

YTM

Rating

Sector

Industry

MERRILL LYNCH & CO INC

5%

5.700%

02-May-17

5.702%

A

Financial

Banks

CATERPILLAR FINL CORP PWRNTSBE

5%

6.500%

15-Mar-16

5.620%

A

Financial

Banks

REINSURANCE GROUP AMER INC

5%

5.625%

15-Mar-17

4.963%

A

Financial

Insurance

SHELL INTERNATIONAL FIN BV

5%

5.200%

22-Mar-17

2.992%

AA

Energy

Oil

CHEVRON CORPORATION

5%

4.950%

03-Mar-19

3.065%

AA

Energy

Oil

XTO ENERGY INC

5%

6.250%

01-Aug-17

3.118%

AAA

Energy

Oil

TOYOTA MTR CR CORP TMCC CORENO

5%

5.350%

21-Feb-17

4.709%

AA

Consumer Cyclical

Auto Mobiles

DAIMLER CHRYSLER NORTH AMER HL

5%

8.500%

18-Jan-31

5.376%

A

Consumer Cyclical

Auto Mobiles

DISNEY WALT CO MTNS BE

5%

5.625%

15-Sep-16

2.456%

A

Consumer Cyclical

Media Company

EMERSON ELEC CO

5%

5.375%

15-Oct-17

3.112%

A

Utility

Electricity

UNION ELEC CO

5%

5.100%

01-Aug-18

4.089%

A

Utility

Electricity

ATLANTIC CITY ELEC CO

5%

7.750%

15-Nov-18

3.630%

A

Utility

Electricity

DU PONT E I DE NEMOURS & CO

5%

6.000%

15-Jul-18

3.545%

A

Materials

Chemicals

RIO TINTO FIN USA LTD

5%

6.500%

15-Jul-18

3.785%

A

Materials

Metal Mining

BHP BILLITON FIN USA LTD

5%

5.400%

29-Mar-17

2.799%

A

Materials

Metal Mining

Figure 5: Selected Corporate Bonds


Since our fund was based on the PIMCO total return fund as its index, we used excel to match the duration of our holdings to that of PIMCO.