Tuesday, October 29, 2024

Dynamic programming - Introduction

Dynamic programming is a method for solving problems that involve overlapping subproblems and repeated computation for the same sub-structure. This approach optimizes by breaking down complex problems and avoiding redundant work.

To make this clearer, let’s consider a real-world example: imagine there are 200 houses in an apartment complex, and four people are tasked with checking which houses are locked. Each person checks and records the state of the houses every hour. However, if they don’t coordinate, some houses might be checked multiple times, wasting time and resources. Instead, if the four people share real-time information about which houses they’ve already checked, they can avoid redundant checks, speeding up the process and saving energy.

In computer science, this is similar to “Dynamic Programming.” When a problem has overlapping sub-structures, its time complexity can become exponential. By using techniques like memoization or bottom-up dynamic programming, we can often reduce this complexity to linear or polynomial time.

Monday, December 12, 2016

Combination Algorithms



1. Longest Common Subsequence


2. Tower Of Hanoi


3. Tower of Hanoi program in java




Friday, December 9, 2016

SUBSET/COMBINATION Generating and coding.

In this video we will discuss about the idea behind generating combination/subset from the give set. Here the set can be a string, Each character is considered as single element.






Sunday, October 2, 2016

Longest Common Subsequence

Longest Common Sub-Sequence


Idea behind the logic is

1. If the two string's first character is same then truncate both and use the truncated string and proceed.
2. if the first two character is not same then, first truncate one character from string s1 and call the function, then truncate the character from string s2 and call the function again. and take the max from that.
 


#include <stdio.h>
#include <strings.h>
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

int lcs(char *s1, char *s2) {

 if (strlen(s1) == 0 || strlen(s2) == 0) 
  return 0;

 if (*s1 == *s2) {

  return 1+lcs(s1+1, s2+1);
 }
 else {

  return MAX(lcs(s1+1, s2), lcs(s1, s2+1));
 }
}

int main() {

 char s2[] = "abcd";
 char s1[] = "efgh";

 printf("%d\n", strlen(s2));

 int c = lcs(s1, s2);

 printf("%d   count = %d\n", c, count);
}

Wednesday, January 13, 2016

Javascript Programming Language



















Monday, October 26, 2015

 Swift Programming Langauge



































Monday, April 27, 2015

Data Structure and Algorithms - Binary Search Tree



BST - Insert
Here we discussed about, what is binary tree and what properties makes binary search tree. theory of binary search tree and the actual implementation.

BST - Delete
Here we discuss about what are cases we need to consider before deleting a node and how to make the binary tree properties intact after deleting the node.

Count Number of elements in the given binary tree, I will be explaining how to do this programatically and hands on coding as well.

              

In the below video I am going to explain you how to find the smallest and largest element in the given binary tree.



Sunday, March 9, 2014

Controlling AC light from iOS application. Node.js is actually sends data to Arduino, iOS application send data to Node.js

Thursday, April 11, 2013

How to use SOAP WebService API - Objective-C iOS

http://www.w3schools.com/webservices/tempconvert.asmx

The above URL provides two SOAP web service

1. CelsiusToFahrenheit

Request Format:


POST /webservices/tempconvert.asmx HTTP/1.1
Host: www.w3schools.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/CelsiusToFahrenheit"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <CelsiusToFahrenheit xmlns="http://tempuri.org/">
      <Celsius>string</Celsius>
    </CelsiusToFahrenheit>
  </soap:Body>
</soap:Envelope>
   
Response Format


HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <CelsiusToFahrenheitResponse xmlns="http://tempuri.org/">
      <CelsiusToFahrenheitResult>string</CelsiusToFahrenheitResult>
    </CelsiusToFahrenheitResponse>
  </soap:Body>
</soap:Envelope>

2. FahrenheitToCelsius

Request Format:



POST /webservices/tempconvert.asmx HTTP/1.1
Host: www.w3schools.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/FahrenheitToCelsius"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <FahrenheitToCelsius xmlns="http://tempuri.org/">
      <Fahrenheit>string</Fahrenheit>
    </FahrenheitToCelsius>
  </soap:Body>
</soap:Envelope>
Response Format:



HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <FahrenheitToCelsiusResponse xmlns="http://tempuri.org/">
      <FahrenheitToCelsiusResult>string</FahrenheitToCelsiusResult>
    </FahrenheitToCelsiusResponse>
  </soap:Body>
</soap:Envelope>

iPhone application is going to consume these two service to convert Fahrenheit to Celsius and vice versa. 


#import <Foundation/Foundation.h>


@interface RequestResponseHandler : NSObject<NSURLConnectionDelegate, NSXMLParserDelegate>
{
    NSURLConnection *connection;
    NSMutableData *responseData;
    CallBack callback;
    
    NSMutableDictionary *model;
}

-(void) executeRequest:(NSURLRequest*) request completion:(CallBack) completionCallback;

+(RequestResponseHandler*) sharedInstance;

@end




#import "RequestResponseHandler.h"
#import "CelsiusToFahrenheitResponse.h"
#import "FahrenheitToCelsiusResponse.h"

static RequestResponseHandler *sharedInstance;

@implementation RequestResponseHandler

- (id)init
{
    self = [super init];
    if (self) {
        responseData = [[NSMutableData alloc] init];
    }
    return self;
}

+(RequestResponseHandler*) sharedInstance
{
    if  (sharedInstance == nil)
    {
        sharedInstance = [[self alloc] init];
    }
    
    return sharedInstance;

}

-(void) executeRequest:(NSURLRequest*) request completion:(CallBack)completionCallback
{
    callback = completionCallback;
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aconnection {
    
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:responseData];
    parser.delegate = self;
    [parser parse];
}


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
        
    if ([elementName isEqualToString:@"CelsiusToFahrenheitResult"])
    {
        model = [[NSMutableDictionary alloc] init];
        [model setObject:@"" forKey:@"CelsiusToFahrenheitResult"];
    }
    else if ([elementName isEqualToString:@"FahrenheitToCelsiusResult"])
    {
        model = [[NSMutableDictionary alloc] init];
        [model setObject:@"" forKey:@"FahrenheitToCelsiusResult"];
    }
 
}

//This method is to store the result between element (Result):
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
 
    NSArray *keys = [model allKeys];
    for (NSString *key in keys) {
        [model setValue:string forKey:key];
    }
        
}


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
{
    if ([elementName isEqualToString:@"CelsiusToFahrenheitResult"] || [elementName isEqualToString:@"FahrenheitToCelsiusResult"]) {
        callback(model);
    }
}


@end

#import <Foundation/Foundation.h>


@interface SoapRequestFactory : NSObject

+(SoapRequestFactory*) defaultInstance;
-(NSURLRequest*) getRequestForType:(REQUEST_TYPE) requestType embeddingValue:(NSString*) value;

@end

#import "SoapRequestFactory.h"

static SoapRequestFactory *sharedInstance;

@implementation SoapRequestFactory


+(SoapRequestFactory*) defaultInstance
{
    if  (sharedInstance == nil)
    {
        sharedInstance = [[self alloc] init];
    }
    
    return sharedInstance;
}

-(NSURLRequest*) getRequestForType:(REQUEST_TYPE) requestType embeddingValue:(NSString*) value
{
    switch (requestType) {
        case CELSIUS_TO_FAHRENHEIT:
            return [self getCelsiusToFahrenheit:value];
            
        case FAHRENHEIT_TO_CELSIUS:
            return [self getFahrenheitToCelsius:value];

            
        default:
            break;
    }
}

-(NSURLRequest*) getCelsiusToFahrenheit:(NSString*) value
{
    
    NSString *soapMessage = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    "<soap:Body>"
    "<CelsiusToFahrenheit xmlns=\"http://tempuri.org/\">"
    "<Celsius>%@</Celsius>"
    "</CelsiusToFahrenheit>"
    "</soap:Body>"
    "</soap:Envelope>";
    
    
    NSString *message = [NSString stringWithFormat:soapMessage, value];

    NSURL *url = [NSURL URLWithString:@"http://w3schools.com/webservices/tempconvert.asmx"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [message length]];
    
    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [message dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    return theRequest;
}




-(NSURLRequest*) getFahrenheitToCelsius:(NSString *) value
{
    NSString *soapMessage = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    "<soap:Body>"
    "<FahrenheitToCelsius xmlns=\"http://tempuri.org/\">"
    "<Fahrenheit>%@</Fahrenheit>"
    "</FahrenheitToCelsius>"
    "</soap:Body>"
    "</soap:Envelope>";
    
    NSString *message = [NSString stringWithFormat:soapMessage, value];
    
    NSURL *url = [NSURL URLWithString:@"http://w3schools.com/webservices/tempconvert.asmx"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [message length]];
    
    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"http://tempuri.org/FahrenheitToCelsius" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [message dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    return theRequest;
}



@end

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>
{
    IBOutlet UISegmentedControl *segmentedControl;
    IBOutlet UILabel *result;
    NSString *value;
}

-(IBAction)segmentControlChanged:(id) sender;

@end

#import "ViewController.h"

#import "SoapRequestFactory.h"
#import "RequestResponseHandler.h"
#import "CelsiusToFahrenheitResponse.h"
#import "FahrenheitToCelsiusResponse.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    value = textField.text;
    [self segmentControlChanged:segmentedControl];
    
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated.
}

-(IBAction)segmentControlChanged:(UISegmentedControl*) sender
{
    NSURLRequest *request = [[SoapRequestFactory defaultInstance] getRequestForType:sender.selectedSegmentIndex embeddingValue:value];
    
    if (sender.selectedSegmentIndex == 0) {
        [[RequestResponseHandler sharedInstance] executeRequest:request  completion:^(NSDictionary *response){
            result.text = [response valueForKey:@"CelsiusToFahrenheitResult"];            
            
        }];
    }
    else
    {
        [[RequestResponseHandler sharedInstance] executeRequest:request  completion:^(NSDictionary *response){
            result.text = [response valueForKey:@"FahrenheitToCelsiusResult"];            
        }];
    }
}

@end

Tuesday, April 9, 2013

Facade Design Pattern - Objective-C


Facade design pattern just hides the sub system's interface and provides single interface to the client.

In everyday life we are using lots of facade design pattern without knowing it.
for example

    [data writeToFile:path atomically:YES];

writeToFile method opens a file pointer in write mode and writes the content and closes the file pointer, All these three functionality is taken care by writeToFile method, It hides the three different activities.

Earlier we use to open the file pointer and write the data, finally close the file pointer. The client has to manage everything but Facade design pattern hides all the details and expose the subject interface to the client. Client has no idea about how its going to write the data into DISK.


I am going to take a problem and solve using FACADE DESIGN PATTERN.

The problem is, 

     When an employee resigns from an organization, the very last day the employee has to go to all the department to get the clearance signature to make sure he/she do not have any pending clearance.
 
    Here the client is an Employee, the sub systems are Admin department, Finance department, Reporting manager.  So i would like to introduce the facade pattern to sort out the employee roaming behind all the department to get the clearance.  The employee only has to go to particular department when he has some pending records which requires in-person meeting. All Resigned employee no need to go to all the department to get the signature.





ClearenceCheckDelegate protocol, Each department should implement the interface. This implementation changes based on the department. But the interface is common for all the department so that facade can call method on each department to know the clearance status of an employee.


//
//  ClearenceCheckDelegate.h
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol ClearenceCheckDelegate <NSObject>

-(BOOL) clearenceCheckForEmployeeID:(NSString*) employeeCode;

@end

//
//  FinanceDepartnment.h
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ClearenceCheckDelegate.h"

@interface FinanceDepartnment : NSObject<ClearenceCheckDelegate>
{
    NSMutableDictionary *employeeClerence;
}


@end


We have hardcoded the employee clearance status, But in real time it may come  from Database or from web service, Since we are discussing about the facade design pattern we do not have to concentrate on the data source.


//
//  FinanceDepartnment.m
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import "FinanceDepartnment.h"

@implementation FinanceDepartnment

- (id)init
{
    self = [super init];
    if (self) {
        employeeClerence = [[NSMutableDictionary alloc] init];
        
        [employeeClerence setObject:[NSNumber numberWithBool:YES] forKey:@"1234"];
        [employeeClerence setObject:[NSNumber numberWithBool:YES] forKey:@"1235"];
    }
    return self;
}


-(BOOL) clearenceCheckForEmployeeID:(NSString*) employeeCode
{
    NSNumber *isCleared = [employeeClerence objectForKey:employeeCode];
    
    return [isCleared boolValue];
}

@end

//
//  AdminDepartnment.h
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ClearenceCheckDelegate.h"

@interface AdminDepartnment : NSObject<ClearenceCheckDelegate>
{
    NSMutableDictionary *employeeClerence;
}

@end

//
//  AdminDepartnment.m
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import "AdminDepartnment.h"

@implementation AdminDepartnment

- (id)init
{
    self = [super init];
    if (self) {
        employeeClerence = [[NSMutableDictionary alloc] init];
        
        [employeeClerence setObject:[NSNumber numberWithBool:YES] forKey:@"1234"];
        [employeeClerence setObject:[NSNumber numberWithBool:NO] forKey:@"1235"];
    }
    return self;
}

-(BOOL) clearenceCheckForEmployeeID:(NSString*) employeeCode
{
    NSNumber *isCleared = [employeeClerence objectForKey:employeeCode];
    
    return [isCleared boolValue];
}

@end

//
//  ReportingManager.h
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ClearenceCheckDelegate.h"

@interface ReportingManager : NSObject<ClearenceCheckDelegate>
{
    NSMutableDictionary *employeeClerence;
}

@end

//
//  ReportingManager.m
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import "ReportingManager.h"

@implementation ReportingManager

- (id)init
{
    self = [super init];
    if (self) {
        employeeClerence = [[NSMutableDictionary alloc] init];
        
        [employeeClerence setObject:[NSNumber numberWithBool:YES] forKey:@"1234"];
        [employeeClerence setObject:[NSNumber numberWithBool:YES] forKey:@"1235"];
    }
    return self;
}


-(BOOL) clearenceCheckForEmployeeID:(NSString*) employeeCode
{
    NSNumber *isCleared = [employeeClerence objectForKey:employeeCode];
    
    return [isCleared boolValue];
}


@end







employee class acts as facade,  canIGetMyExperienceLetter is the interface to the client and it in turns checks clearance for an employee with all the department.




 
//
//  RelievingManagerFacade.h
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ClearenceCheckDelegate.h"

@interface RelievingManagerFacade : NSObject
{
    NSMutableArray *clearenceDepts;
}

-(void) addClearenceDept:(id<ClearenceCheckDelegate>) dept;

-(BOOL) canIGetMyExperienceLetter:(NSString*) employeeCode;

@end

//
//  RelievingManagerFacade.m
//  FacadeDesignPattern
//
//  Created by Stalin on 09/04/13.
//  Copyright (c) 2013 Stalin. All rights reserved.
//

#import "RelievingManagerFacade.h"
#import "ClearenceCheckDelegate.h"

@implementation RelievingManagerFacade

- (id)init
{
    self = [super init];
    if (self) {
        
        clearenceDepts = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void) addClearenceDept:(id<ClearenceCheckDelegate>) dept
{
        [clearenceDepts addObject:dept];
}

-(BOOL) canIGetMyExperienceLetter:(NSString*) employeeCode
{
    for (id<ClearenceCheckDelegate> dept in clearenceDepts)
    {
        if ([dept conformsToProtocol:@protocol(ClearenceCheckDelegate)])
        {
             if ([dept clearenceCheckForEmployeeID:employeeCode] == false)
             {
                 return false;
             }
        }
    }
    
    return true;
}

@end







    RelievingManagerFacade *hr = [[RelievingManagerFacade alloc] init];
    
    //adding the clearence dept
    [hr addClearenceDept:[[FinanceDepartnment alloc] init]];
    [hr addClearenceDept:[[AdminDepartnment alloc] init]];
    [hr addClearenceDept:[[ReportingManager alloc] init]];
    

    if ([hr canIGetMyExperienceLetter:@"1234"])
    {
        NSLog(@"Employee code 1234.  Yes,  You do not have any pending clearence. You will get it now.");
    }
    else
    {
        NSLog(@"Employee code 1234. NO, You have some pending clearence.");
    }
    
    if ([hr canIGetMyExperienceLetter:@"1235"])
    {
        NSLog(@"Employee code 1235. Yes,  You do not have any pending clearence. You will get it now.");
    }
    else
    {
        NSLog(@"Employee code 1235. NO, You have some pending clearence.");
    }





State Design Pattern - Mars Rover Example


The below is the popular problem for state design pattern. I got this problem as part of interview process for a company and i solved the problem and find the code in this post.


Expectation 

 

1. For the solution, we would want you to use either C++ or Java.

2. We are interested in the DESIGN ASPECT of your solution and would like to evaluate your OBJECT ORIENTED PROGRAMMING SKILLS.

3. You may use external libraries or tools for building or testing purposes.

4. Optionally, you may also include a brief explanation of your design and assumptions along with your code.

5. Kindly note that we are NOT expecting a web-based application or a comprehensive UI. Rather, we are expecting a simple, console based application and interested in your source code.

==========

INTRODUCTION TO THE PROBLEM

 

The problem below require some kind of input. You are free to implement

any mechanism for feeding input into your solution (for example, using hard

coded data within a unit test).  You should provide sufficient evidence

that your solution is complete by, as a minimum, indicating that it works

correctly against the supplied test data.

 

 

MARS ROVERS

 

A squad of robotic rovers are to be landed by NASA on a plateau on Mars. This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.

 

A rover's position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

 

In order to control a rover, NASA sends a simple string of letters. The

possible letters are 'L', 'R' and 'M'. 'L' and 'R' makes the rover spin 90

degrees left or right respectively, without moving from its current spot.

'M' means move forward one grid point, and maintain the same heading.

 

Assume that the square directly North from (x, y) is (x, y+1).

 

INPUT:

The first line of input is the upper-right coordinates of the plateau, the

lower-left coordinates are assumed to be 0,0.

 

The rest of the input is information pertaining to the rovers that have

been deployed. Each rover has two lines of input. The first line gives the rover's position, and the second line is a series of instructions telling the rover how to explore the plateau.

 

The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover's orientation.

 

Each rover will be finished sequentially, which means that the second rover won't start to move until the first one has finished moving.

 

 

OUTPUT

The output for each rover should be its final co-ordinates and heading.

 

INPUT AND OUTPUT

 

Test Input:

5 5

1 2 N

LMLMLMLMM

3 3 E

MMRMMRMRRM

 

Expected Output:

1 3 N

5 1 E



















//
//  RoverHeadingInterface.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#ifndef MarsRoverApp_RoverHeadingInterface_h
#define MarsRoverApp_RoverHeadingInterface_h

class RoverHeading
{
    public:
        RoverHeading() {}
        virtual void turnLeft() = 0;
        virtual void turnRight() = 0;
};

#endif





//
//  MoveRoverInterface.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//


#ifndef MarsRoverApp_MoveRoverInterface_h
#define MarsRoverApp_MoveRoverInterface_h

#include "RoverHeadingInterface.h"
#include "Position.h"
class Rover;

class MoveRover:public RoverHeading
{
    
protected:
    char heading;
    Rover *rover;
        
public:
    MoveRover(Rover* rover, char heading);
    
    virtual void move() = 0;
    
    char currentHeading();
};

#endif





//
//  MoveRoverInterface.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "MoveRoverInterface.h"


MoveRover::MoveRover(Rover* rover, char heading)
{
    this->rover = rover;
    this->heading = heading;
}


char MoveRover::currentHeading()
{
    return heading;
}

//
//  PlaneBounds.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#ifndef __MarsRoverApp__PlaneBounds__
#define __MarsRoverApp__PlaneBounds__

#include <iostream>

class PlaneBounds
{
private:
    int xTerritory, yTerritory;
    
public:
    PlaneBounds(int x, int y);
    bool isSafeToMove(int value);
};

#endif /* defined(__MarsRoverApp__PlaneBounds__) */

//
//  PlaneBounds.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "PlaneBounds.h"

PlaneBounds::PlaneBounds(int x, int y)
{
    xTerritory = x;
    yTerritory = y;
}


bool PlaneBounds::isSafeToMove(int value)
{
    if (0 <= value && value <= xTerritory && value <= yTerritory)
    {
        return true;
    }
    else
    {
        return false;
    }
}





//
//  Position.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#ifndef __MarsRoverApp__Position__
#define __MarsRoverApp__Position__

#include <iostream>
#include "PlaneBounds.h"

class Position
{
private:
    int x, y;
    PlaneBounds *territory;
    
public:
    Position(int x, int y, PlaneBounds *territory);
    int getX();
    int getY();
    void incrementY();
    void incrementX();
    void decrementY();
    void decrementX();
};

#endif /* defined(__MarsRoverApp__Position__) */





//
//  Position.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "Position.h"

Position::Position(int x, int y, PlaneBounds *territory)
{
    this->x = x;
    this->y = y;
    this->territory = territory;
}

int Position::getX()
{
    return x;
}

int Position::getY()
{
    return y;
}


void Position::incrementY()
{
    if (territory->isSafeToMove(y+1))
    {
          y++;
    }
    else
    {
        std::cout<<"I cannot move towards NORTH, I reached territory!";
        exit(0);
    }
  
}

void Position::incrementX()
{
    if (territory->isSafeToMove(x+1))
    {
        x++;
    }
    else
    {
        std::cout<<"I cannot move towards EAST, I reached territory!";
        exit(0);
    }
}

void Position::decrementX()
{
    if (territory->isSafeToMove(x-1))
    {
        x--;
    }
    else
    {
        std::cout<<"I cannot move towards WEST, I reached territory!";
        exit(0);
    }
}

void Position::decrementY()
{
    if (territory->isSafeToMove(y-1))
    {
        y--;
    }
    else
    {
        std::cout<<"I cannot move SOUTH, I reached territory!";
        exit(0);
    }
}





//
//  HeadWest.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//


#ifndef __MarsRoverApp__HeadWest__
#define __MarsRoverApp__HeadWest__

#include "MoveRoverInterface.h"

#include <iostream>

class HeadWest: public MoveRover
{
public:
    HeadWest(Rover* rover);
    void turnLeft();
    void turnRight();
    void move();
    
};

#endif /* defined(__MarsRoverApp__HeadWest__) */





//
//  HeadWest.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "HeadWest.h"
#include "Rover.h"
#include "HeadSouth.h"
#include "HeadNorth.h"


HeadWest::HeadWest(Rover* rover):MoveRover(rover, 'W')
{
    
}

void HeadWest::turnLeft()
{
    rover->operateRover = new HeadSouth(rover);
}

void HeadWest::turnRight()
{
    rover->operateRover = new HeadNorth(rover);
}

void HeadWest::move()
{
    rover->position->decrementX();
}





//
//  HeadEast.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//


#ifndef __MarsRoverApp__HeadEast__
#define __MarsRoverApp__HeadEast__

#include "MoveRoverInterface.h"
#include <iostream>

class HeadEast: public MoveRover
{
    public:
        HeadEast(Rover* rover);
        void turnLeft();
        void turnRight();
        void move();

};


#endif /* defined(__MarsRoverApp__HeadEast__) */





//
//  HeadEast.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "HeadEast.h"
#include "Rover.h"
#include "HeadNorth.h"
#include "HeadSouth.h"

HeadEast::HeadEast(Rover* rover):MoveRover(rover, 'E')
{
    
}

 void HeadEast::turnLeft()
{
    rover->operateRover = new HeadNorth(rover);
}

void HeadEast::turnRight()
{
    rover->operateRover = new HeadSouth(rover);
}

void HeadEast::move()
{
    rover->position->incrementX();
}





//
//  HeadSouth.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//


#ifndef __MarsRoverApp__HeadSouth__
#define __MarsRoverApp__HeadSouth__
#include "MoveRoverInterface.h"

#include <iostream>

class HeadSouth: public MoveRover
{
    public:
        HeadSouth(Rover* rover);
        void turnLeft();
        void turnRight();
        void move();
};

#endif /* defined(__MarsRoverApp__HeadSouth__) */





//
//  HeadSouth.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "HeadSouth.h"
#include "Position.h"
#include "HeadEast.h"
#include "HeadWest.h"
#include "Rover.h"


HeadSouth::HeadSouth(Rover* rover):MoveRover(rover, 'S')
{
    
}

void HeadSouth::turnLeft()
{
    rover->operateRover = new HeadEast(rover);
}

void HeadSouth::turnRight()
{
    rover->operateRover = new HeadWest(rover);
}

void HeadSouth::move()
{
    rover->position->decrementY();
}





//
//  HeadNorth.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//
#include "MoveRoverInterface.h"

#ifndef __MarsRoverApp__HeadNorth__
#define __MarsRoverApp__HeadNorth__

#include <iostream>

class HeadNorth: public MoveRover
{
    public:
        HeadNorth(Rover* rover);
        void turnLeft();
        void turnRight();
        void move();
    
};

#endif /* defined(__MarsRoverApp__HeadNorth__) */





//
//  HeadNorth.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "HeadNorth.h"
#include "Rover.h"
#include "HeadWest.h"
#include "HeadEast.h"

HeadNorth::HeadNorth(Rover* rover):MoveRover(rover, 'N')
{
    
}

void HeadNorth::turnLeft()
{
    rover->operateRover = new HeadWest(rover);
}

void HeadNorth::turnRight()
{
    rover->operateRover = new HeadEast(rover);
}

void HeadNorth::move()
{
    rover->position->incrementY();
}





//
//  Rover.h
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//


#ifndef __MarsRoverApp__Rover__
#define __MarsRoverApp__Rover__

#include <string.h>
#include <iostream>
#include "MoveRoverInterface.h"

class Rover
{
    
    public: Position *position;
    public: MoveRover *operateRover;

    public:

        Rover(int x, int y, char heading, PlaneBounds *territory);
        void sendCommand(const char *commandString);
    
        void currentPosition();
};

#endif /* defined(__MarsRoverApp__Rover__) */





//
//  Rover.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include "Rover.h"
#include "HeadEast.h"
#include "HeadNorth.h"
#include "HeadSouth.h"
#include "HeadWest.h"

Rover::Rover(int x, int y, char heading, PlaneBounds *territory)
{
    position = new Position(x, y, territory);
    
    switch (heading) {
        case 'W':
            operateRover = new HeadWest(this);
            break;
            
        case 'S':
            operateRover = new HeadSouth(this);
            break;

        case 'N':
            operateRover = new HeadNorth(this);
            break;

        case 'E':
            operateRover = new HeadEast(this);
            break;
    }
    
}

void Rover::currentPosition()
{
    std::cout<<position->getX()<<" "<<position->getY()<<" "<<operateRover->currentHeading()<<"\n";
}

void Rover::sendCommand(const char *commandString)
{
    size_t commandLength = strlen(commandString);
    
    for (int index = 0; index < commandLength; index++) {
        
        switch (commandString[index]) {
            case 'M':
                operateRover->move();
                break;
                
            case 'L':
                operateRover->turnLeft();
                break;
                
            case 'R':
                operateRover->turnRight();
                break;

                
            default:
                std::cout<<commandString[index]<<" "<<"is an unknown command!";
                break;
        }
    }
}





//
//  main.cpp
//  MarsRoverApp
//
//  Created by Stalin S on 4/2/13.
//  Copyright (c) 2013 Stalin S. All rights reserved.
//

#include <iostream>
#include "Rover.h"

int main(int argc, const char * argv[])
{
    PlaneBounds *territory = new PlaneBounds(5, 5);
    Rover *rover = new Rover(1, 2, 'N', territory);
    rover->currentPosition();
    rover->sendCommand("LMLMLMLMM");
    rover->currentPosition();
    std::cout<<"\n\n\n";
    
    Rover *rover1 = new Rover(3, 3, 'E', territory);
    rover1->currentPosition();
    rover1->sendCommand("MMRMMRMRRM");
    rover1->currentPosition();
    std::cout<<"\n\n\n";

    
    Rover *rover2 = new Rover(1, 2, 'N', territory);
    rover2->currentPosition();
    rover2->sendCommand("LMLMLMLMMMMM");
    rover2->currentPosition();
    std::cout<<"\n\n\n";

    

}






Output:





1 2 N
1 3 N



3 3 E
5 1 E



1 2 N
I cannot move towards NORTH, I reached territory!