Clicky

Mustafa Veysi Soyvural: December 2007

Sunday, 23 December 2007

Rotation of a String

Q.)Given a string s1 and a string s2, write a snippet to say whether s2 is a
rotation of s1 using only one call to strstr routine?

(eg given s1 = ABCD and s2 = CDAB, return true,
given s1 = ABCD, and s2 = ACBD , return false)

If you add s1by itself then you will get s1=ABCDABCD, as you can see now you will be able to make a decision whether s2 is a rotation or not.

Test Cases:
- s1 = NULL
- s2 = NULL
- Both s1 and s2 are NULL
- s1 = "\0", s2 = "\0" ( the rotation of empty string is itself:) )
- s1 = "ABCD", s2 = "CDAB"
- s1 = "ABCD", s2 = "CD"
- s1 = "ABCD", s2 = "CDBA"
- s1 = "KUJU", s2 = "JUKU"

typedef enum { False, True } Boolean;

Boolean isStringRotate( const char s1[ ], const char s2[ ] ) {
int len1 = 0, len2 = 0;
char *s = NULL;
if ( NULL == s1 || NULL == s2 )
return False;

len1 = strlen( s1 );
len2 = strlen( s2 );
if ( len1 != len2 ) return False;

s = ( char * )malloc( len1 + len2 + 1 );
s[ 0 ] = '\0';
strcat(s, s1);
strcat(s, s1);

if ( !strncmp(&s[ len1 / 2 ], s2, len1) )
return True;
return False;
}

Monday, 17 December 2007

Reverse Words of a String

Q.) How do you reverse the words in a string?

"My name is Amit Agarwal"
to
"Agarwal Amit is name My"

A O(n) and 'in space' solution is appreciable.

- First reverse the whole string
- Then reverse each word in the string

Test Cases:
- NULL string
- "" empty string
- "a" string that consists only one word
- "mustafa"
- "a b"
- "Mustafa Veysi Soyvural"
- "Mustafa Veysi Soyvural" more than one space between words

void reverse_words( char s[] ) {
char *p, temp;
int len = 0, i = 0, index = 0, word_len = 0;
if ( NULL == s ) return;
for ( p = s; *p != '\0'; p++ );
len = p - s;

/* reverse whole string */
for ( i = 0; i < (len / 2); i++ ) {
temp = s[ i ];
s[ i ] = s[ len - i - 1 ];
s[ len - i - 1 ] = temp;
}

/* reverse each word */
p = s;
while ( index < len ) {
if ( *p != ' ' && *p != '\0' ) p++;
else {
word_len = p - &s[ index ];
/* reverse word */
for ( i = 0; i < (word_len / 2 ); i++ ) {
temp = s[ i + index ];
s[ i + index ] = s[ index + word_len - i - 1 ];
s[ index + word_len - i - 1 ] = temp;
}
index += word_len + 1;
p++;
}
}
}

Friday, 14 December 2007

Singleton Pattern

Sometimes you need to only one instance of a class exist during the program runs.
Here is a Singleton Pattern Implementation in C++.

hedar file:

class Singleton {
private:
static Singleton * single;
Singleton( ) { }
Singleton( const Singleton & instance ) { }
const Singleton & operator = ( const Singleton & instance ) { }
public:
static Singleton * getInstance();
~Singleton( ) { }
};




source file:

Singleton * Singleton::single = NULL;
Singleton * Singleton::getInstance( ) {
if( NULL == single ) {
single = new Singleton( );
}
return single;
}

Thursday, 13 December 2007

Linked List Class

Here is the node.h file where node class and methods definitions exist:

#ifndef NODE_H_
#define NODE_H_

template <typename Type>
class Node {
Type data;
Node<Type> * next;
Node( ) { }
public:
Node( Type );
Type getData( ) const;
Node * getNext( ) const;
void setNext( Node<Type> * );
~Node( );
};

#endif



Here is the node.cpp file where Node Class methods are implemented.
template <typename Type>
Node<Type>::Node( Type _data ) {
this->data = _data;
this->next = 0;
}

template <typename Type>
Type Node<Type>::getData( ) const {
return this->data;
}

template <typename Type>
Node<Type>* Node<Type>::getNext( ) const {
return this->next;
}

template <typename Type>
void Node<Type>::setNext( Node<Type> *node ) {
this->next = node;
}

template <typename Type>
Node<Type>::~Node( ) {
this->next = 0;
}




Here is the list.h file where List Class and methods exist.
#ifndef LIST_H_
#define LIST_H_

#include "node.h"

template <typename Type>
class List {
Node<Type> * head;
Node<Type> * tail;
unsigned int length;
public:
List( );
List( const List & );
bool insert( Type data );
bool remove( unsigned int );
bool removeAtLast( unsigned int );
void insertSorted( Type data );
void reverse( );
void print( std::ostream & out ) const;
unsigned int size( ) const;
bool isEmpty( ) const;
Type get( unsigned int index ) const;
const Node<Type> * getMidNode( ) const ;
const List<Type> & getFirstHalf( ) const ;
const List<Type> & operator = ( const List<Type> & );
List<Type> operator + ( const List<Type> & ) const;
void operator += ( const List<Type> & );
bool operator == ( const List<Type> & ) const;
bool operator != ( const List<Type> & ) const;
void clear( );
~List( );
};

#endif




Here is the list.cpp file where List Class methods are implemented:
#include "node.h"
template <typename Type>
List<Type>::List( ) {
this->head = this->tail = 0;
this->length = 0;
}

template <typename Type>
List<Type>::List( const List<Type> & list ) {
this->head = this->tail = 0;
this->length = 0;

for ( Node<Type> * p = list.head; p; p = p->getNext( ) ) {
this->insert( p->getData( ) );
}
}

template <typename Type>
bool List<Type>::insert( Type data ) {
Node<Type> * node = new Node<Type>( data );
if ( 0 == node ) return false;
if ( 0 == head ) {
this->head = this->tail = node;
} else {
this->tail->setNext( node );
this->tail = node;
}
this->length++;
return true;
}

template <typename Type>
void List<Type>::insertSorted( Type data ) {
if ( this->isEmpty( ) ) {
this->insert( data );
} else {
Node<Type> * node = new Node<Type>( data );
Node<Type> * p = head, * q;
while ( p->getNext( ) && data > p->getData( ) ) {
q = p;
p = p->getNext( );
}
if ( p == head ) { //insert beginning of the list
node->setNext( head );
head = node;
} else if ( p->getNext( ) == 0 ) { //insert end of the list
p->setNext( node );
this->tail = node;
} else { //insert
node->setNext( p );
q->setNext( node );
}
this->length++;
}
}

template <typename Type>
void List<Type>::print( std::ostream & out ) const {
for ( Node<Type> * p = head; p; p = p->getNext( ) ) {
out << p->getData( ) << " - ";
}
out << endl;
}

template <typename Type>
unsigned int List<Type>::size( ) const {
return length;
}

template <typename Type>
Type List<Type>::get( unsigned int index ) const {
if ( this->isEmpty( ) ) {
throw "List is empty.";
}

if ( index >= this->length )
throw "Index is out of boundary.";

int counter = 0;
Node<Type> *p = this->head;
while ( p && ( counter < index ) ) {
counter++;
p = p->getNext( );
}
return p->getData( );
}




template <typename Type>
void List<Type>::reverse( ) {
Node<Type> * p, * q, * r;
p = q = r = 0;
r = this->head;
while ( r ) {
q = p;
p = r;
r = r->getNext( );
p->setNext( q );
}
this->head = p;
}

template <typename Type>
const List<Type> & List<Type>::getFirstHalf( ) const {
List<Type> *list = new List( );
Node<Type> *p, *q;
q = p = this->head;

int counter = 1;
while ( p ) {
p = p->getNext( );
if( counter++ % 2 == 0 ) {
list->insert( q->getData( ) );
q = q->getNext( );
}
}
return *list;
}

template <typename Type>
const Node<Type> * List<Type>::getMidNode( ) const {
Node<Type> *p, *q;
q = p = this->head;

int counter = 1;
while ( p ) {
p = p->getNext( );
if( counter++ % 2 == 0 ) {
q = q->getNext( );
}
}
return q;
}


template <typename Type>
bool List<Type>::isEmpty( ) const {
if ( 0 == this->head ) return true;
return false;
}

/*********************************
** n between 0 and length - 1
**********************************/
template <typename Type>
bool List<Type>::remove( unsigned int n ) {
if ( n >= this->length ) return false;
if ( this->length == 1 ) {
this->clear( );
return true;
}

int counter = 0;
Node<Type> *p, *q;
q = p = this->head;
while ( counter++ < n && p ) {
q = p;
p = p->getNext( );
}
if ( counter <= n ) return false;

if ( p == this->head ) {
this->head = p->getNext( );
}
else {
q->setNext( p->getNext( ) );
}
if ( p == this->tail ) {
this->tail = q;
}

delete p;
this->length--;
return true;
}

/******************************
** n between 0 and length - 1
*******************************/
template <typename Type>
bool List<Type>::removeAtLast( unsigned int n ) {
return this->remove( this->length - n - 1 );
}

template <typename Type>
const List<Type> & List<Type>::operator =( const List<Type> & list ) {
this->clear( );

for ( Node<Type> * p = list.head; p; p = p->getNext( ) ) {
this->insert( p->getData( ) );
}

return *this;
}

template <typename Type>
List<Type> List<Type>::operator +(const List<Type> & list) const {
List<Type> result;

for ( Node<Type> * p = this->head; p; p = p->getNext( ) ) {
result.insert( p->getData( ) );
}

for ( Node<Type> * p = list.head; p; p = p->getNext( ) ) {
result.insert( p->getData( ) );
}

return result;
}

template <typename Type>
void List<Type>::operator += ( const List<Type> & list ) {
for ( Node<Type> *p = list.head; p; p = p->getNext( ) ) {
this->insert( p->getData( ) );
}
}

template <typename Type>
bool List<Type>::operator == ( const List<Type> & list ) const {
if ( this->length != list.length ) return false;
Node<Type> *p = this->head, *q = list.head;
while ( p && q ) {
if ( p->getData( ) != q->getData( ) ) return false;
p = p->getNext( );
q = q->getNext( );
}
if ( (p && !q) || (!p && q) ) return false;
return true;
}

template <typename Type>
bool List<Type>::operator != ( const List<Type> & list ) const {
return !( this->operator==( list ) );
}

template <typename Type>
void List<Type>::clear( ) {
Node<Type> *p = this->head, *next;
while ( p ) {
next = p->getNext( );
delete p;
p = next;
}
this->head = 0;
this->tail = 0;
this->length = 0;
}

template <typename Type>
List<Type>::~List( ) {
this->clear( );
}


Tuesday, 11 December 2007

Linked List

hi,
i wanna just give some problems of linked list and solutions.

Q.1.)Given a singly-linked, find out the mid point of a single linked list in a
single parse of the list. Assume the program would be loaded in read-only
memory so no manipulation of the list is allowed.

Having two pointers makes easy to implement gettig middle node of a linked list.
while one pointer goes on the whole list the other pointer goes as half as first pinter's.

node_t * get_mid_node( list_t * list ) {
node_t *p, *q;
int counter = 1;
if ( NULL == list ) return NULL;
p = list->head;
q = list->head;

while ( p ) {
p = p->next;
if ( counter++ 2 == 0 ) {
q = q->next;
}
}
return q;
}




Q.2.)Given: 2 Unsorted single linked list

Todo: Fastest and optimised way to merge and make a single sorted list with
these 2 unsorted single linked list.
list_t * get_intersection_of_two_sorted_list ( list_t * list1, list_t * list2 ) {
node_t *first, *second;
list_t *intersection_list;
if ( !list1 || !list2 ) return NULL;

intersection_list = ( list_t * ) malloc( sizeof( list_t ) );
if ( NULL == intersection_list ) {
fprintf(stderr, "Bad memory allocation error\n");
return NULL;
}
while ( first && second ) {
if ( first->data < second->data ) first = first->next;
else if ( second->data < first->data ) second = second->next;
else {
add_list( intersection_list, first->data );
first = first->next;
second = second->next;
}
}
}





Q.3.)Given a linked list, your are asked to find out the nth last element in
the linked-list. (n would be given as the argument to the function)

Last nth element is ( l - n + 1)th element from the beginning, so having two pointers:
- Two pointers indicates the list->head at first
- First pointer goes to nth node from the beginning
- Both pointers goes simultaneously until first pointer comes to the end of the list
- Now second pointer walks ( l - n ) nodes, head node is also assumed one walk for two pointers.
- Then secod pointer now indicates the last nth element.

Test Cases:
- List is null
- List is empty
- List with length 1 ( get 1 )
- List with length 2 ( get 1, 2 )
- List with length 3 ( get 3, 1, 2 )
- Any value larger than the size of list
int getLastNth( list_t *list, unsigned int n ) {
int counter;
node_t *p, *q;

if ( NULL == list ) {
fprintf( stderr, "list is null...(getLastNth)\n" );
exit(1);
}

p = list->head;
q = list->head;
for ( counter = 0; p && counter < n - 1; p = p->next, counter++ );

if ( NULL == p ) {
fprintf( stderr, "Index is out boundary...(getLastNth)\n" );
exit(1);
}

while ( p->next ) {
q = q->next;
p = p->next;
}
return q->data;
}




Q.4.)Print reverse order of a singly linked list.
void print_list_reverse_order( node_t * head ) {
if ( NULL == head ) return;
print_list_reverse_order( head->next );
printf("%d\n", head->data);
}

An Impressing Operator (Xor)

Now, lets talk about Xor operator. You can use this operator in many ways that you will see in some exercises here.

i ll give some remindful information about Xor gate:
- it yields 1 if there exists odd number of 1 value inputs
- x Xor 1 = not(x)
- x Xor 0 = x

Q.1.) Given two arrays A and B. Array 'A' contains all the elements of 'B' but
one more element extra.....

Find out the extra element......

Restrictions: Dont use any relational ops ( > or > or == etc....), array
elements are not in order ...,

int getDistinctElementFromTwoArrays( int arr1[ ], int len1, int arr2[ ], int len2 ) {
if ( len1 < 0 || len2 < 0 ) throw out_of_range( "Length of arrays must be bigger than 0." );

int result = arr1[ 0 ];
for ( int i = 1; i < len1; i++ ) {
result ^= arr1[ i ];
}

for ( int i = 0; i < len2; i++ ) {
result ^= arr2[ i ];
}

return result;
}

#include <iostream>
using namespace std;

int main ( int argc, char *argv[] ) {
try {
int arr1[ ] = { 1, 3, 5, 6, 7, -1, -3 };
int arr2[ ] = { 7, -3, 6, 1, -1, 5 };
int len1 = sizeof( arr1 ) / sizeof( arr1[ 0 ] )
int len2 = sizeof( arr2 ) / sizeof( arr2[ 0 ] );

cout << getDistinctElementFromTwoArrays( arr1, len1, arr2, len2 ) << endl;
}
catch ( out_of_range orex ) {
cout << orex.what( ) << endl;
}
return 0;
}






Q.2.)Given an array of numbers, except for one number all the others, occur
twice. Give an algorithm to find that number which occurs only once in the
array.

int getDistinctElement( int arr1[], int len1 ) {
if ( len1 < 0 ) throw out_of_range("Length must be bigger than 0");
int result = arr1[ 0 ];

for ( int i = 1; i < len1; i++ ) {
result ^= arr1[ i ];
}

return result;
}



#include <iostream>
#include <stdexcept>
using namespace std;

int main ( int argc, char *argv[] ) {
try {
int arr1[ ] = { -1, 1, 2, 3, 2, 1, -1 };
int len1 = sizeof( arr1 ) / sizeof( arr1[ 0 ] );

cout << getDistinctElement( arr1, len1 ) << endl;
}
catch ( out_of_range orex ) {
cout << orex.what( ) << endl;
}

return 0;
}

Shifting Operation

Hi, there is a good division and multiplication method by using shifting.
Lets take an example 833794 and divide this number by 10, shift this number to right only once: 83379, and if you want to divide by 100 shift this number to right twice:
8337. The same method is validate also for multiplication with only a little bit change, that is, only shift to left.

Now lets do some exercises :)

Q.1.)Given a numbers x and n, where n is a power of 2, write C code, which
gives the multiple of n which is greater than or equal to x.
ex :
I/P: 13 8
O/P: 16

I/P: 17 16
O/P: 32

The challenge: Do not use division or modulo operator.

unsigned int getBiggerPowerOf2( unsigned int x, unsigned int n ) {
if ( n == 0 ) return 0;
while ( n < x ) {
n = n << 1;
}
return n;
}






Q.2.)Write a C function, which takes a number n and positions p1 and p2 and returns if the the bits at positions p1 and p2 are set or not.
bool isBitsSet( int num, int p1, int p2 ) {
int temp = 0;
temp = ( 1 << (p1 - 1) ) + ( 1 << (p2 - 1) );
num = num & temp;
if ( num == temp ) return true;
return false;
}




Q.3.)Write a C function, which takes a number n and positions p1 and p2 and returns if the the bits at positions p1 and p2 are same or not.

bool isSameBits( int num, int p1, int p2 ) {
int temp = num;

temp = 1 & ( temp >> (p1 - 1) );
num = 1 & ( num >> (p2 - 1) );

return ( temp == num );
}




Q.4.) Give a fast way to multiply a number by 7.
    number * 8 = number << 3;
number = ( number << 3 ) - number;