tag:blogger.com,1999:blog-56554796995712213272024-02-21T03:14:33.600+05:30Programming Puzzles and TricksCome up with your puzzles in programming and get the answers.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.comBlogger12125truetag:blogger.com,1999:blog-5655479699571221327.post-25310205772860026202010-03-30T17:19:00.002+05:302010-03-30T17:22:49.885+05:30Oracle Timestamp conversion from epoch and vice-versaI searched the net but didn't get the code so publishing it here.<br /><br />class OracleTimeStamp<br />{<br />public:<br />static Timestamp ToTimestamp(Oracle::ENV env, const struct timeval &tv);<br />static void ToEpoch(const Timestamp& ts, struct timeval &tv);<br />};<br /><br />Timestamp<br />OracleTimeStamp::ToTimestamp(Oracle::ENV env, const struct timeval &tv)<br />{<br /> char buffer[100] = {0};<br /> time_t curtime = tv.tv_sec;<br /><br /> strftime(buffer,30,"%Y %m %d %H %M %S",localtime(&curtime));<br /><br /> stringstream strstream;<br /> strstream.clear();<br /> strstream << buffer << " " << tv.tv_usec;<br /><br /> int year;<br /> int month;<br /> int day;<br /> int hour;<br /> int minute;<br /> int seconds;<br /> long int millisec;<br /><br /> strstream >> year;<br /> strstream >> month;<br /> strstream >> day;<br /> strstream >> hour;<br /> strstream >> minute;<br /> strstream >> seconds;<br /> strstream >> millisec;<br /> millisec *= 1000;<br /> Timestamp ts(env, year, month, day, hour, minute, seconds, millisec);<br /> return ts;<br />}<br /><br /><br /><br />void<br />OracleTimeStamp::ToEpoch(const Timestamp& ts, struct timeval &tv)<br />{<br /> string date_time = ts.toText("yyyy mm dd hh24:mi:ss.FF", 6);<br /> date_time.replace(13, 1, " ");<br /> date_time.replace(16, 1, " ");<br /> date_time.replace(19, 1, " ");<br /><br /> stringstream date_time_stream;<br /> date_time_stream.clear();<br /> date_time_stream << date_time;<br /><br /> struct tm time_val;<br /> date_time_stream >> time_val.tm_year;<br /> time_val.tm_year -= 1900;<br /> date_time_stream >> time_val.tm_mon;<br /> time_val.tm_mon -= 1;<br /> date_time_stream >> time_val.tm_mday;<br /> date_time_stream >> time_val.tm_hour;<br /> date_time_stream >> time_val.tm_min;<br /> date_time_stream >> time_val.tm_sec;<br /><br /> date_time_stream >> tv.tv_usec;<br /><br /> // Assign the values to struct tm<br /> // Then get the microsecond value directly into tv.tv_usec<br /> time_t time_in_sec;<br /> time_in_sec = mktime(&time_val);<br /> tv.tv_sec = time_in_sec;<br /> return;<br />}Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-12485925644175849302010-03-30T17:11:00.004+05:302010-03-30T17:18:51.886+05:30C++ function overloading on Return TypeIt is possible to overload the functions based on return type.<br /><br />I am not talking about the functions with 'CV' qualifier.<br />For e.g,<br />class C<br />{<br />public:<br />void foo() const;<br />int foo() volatile;<br />double foo() const volatile;<br />};<br /><br />This way we can have overloading. But in reality they are not overloaded for same object. It depends on what kind of object. For eg, when you create const object of C, it will call void foo(), similarly for volatile , it is int foo() etc...<br />So in real sense they are not overloaded.<br /><br />Where as if you use template, you can overload the functions based on the return type.<br /><br />class OverLoad<br />{<br />public:<br /> template < T > // just declaration , no definition<br /> T GetMe();<br />};<br /><br />template <><br />int<br />OverLoad::GetMe()<br />{<br /> return int;<br />}<br /><br />template <><br />std::string<br />OverLoad::GetMe()<br />{<br /> return std::string();<br />}template <><br /><br />double<br />OverLoad::GetMe()<br />{<br /> return 2.2;<br />}<br />etc...<br /><br />These functions can be called by the same object.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-53232232071596553072008-03-28T12:21:00.005+05:302008-03-28T12:29:37.748+05:30Template MetaprogrammingWe must have seen that C++ has incorporated template metaprogramming.<br />It also mentions that it gets calculated at compile time ( Wow! ).<br />This saves the execution time of a program which is great.<br />So lets see the standard example give in C++ Templates book by Vandevoorde/Josuttis.<br /><br />template <int N><br />class Pow3 {<br /> public:<br /> enum { result = 3 * Pow3<N-1>::result };<br />};<br /><br />template <><br />class Pow3<0> {<br /> public:<br /> enum { result = 1 };<br />};<br /><br />Now when you write the program like : <br /><br />int main() try {<br /> cout << " 3 to power 3 is : " << Pow3<3>::result << endl;<br /> return 0;<br />} catch(...) {<br /> cout << "Uncaught exception..." << endl;<br />}<br /><br />It prints : 27.<br />Conceptually enums are constants and constants are to be given value at compile time only.<br />Therefore, we can assume that Pow3<3>::result was having 27 as value.<br />But how will you prove that compiler did the actual calculation for you ???<br />If you are not sure check out the reply for this blog.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com1tag:blogger.com,1999:blog-5655479699571221327.post-70296946408179399652008-03-06T12:08:00.003+05:302008-03-06T12:12:53.398+05:30Depth First Search without writing codeI am going to show how depth first search ( DFS ) without using any algorithm.<br />Actually I am making use of the algorithm which compilers already have implemented :-)<br />The virtual inheritance property is compiler makes sure that it follows the depth first search logic to instantiate the virtual base classes.<br />Here is the code and output:<br /><br />/*<br /> * =====================================================================================<br /> *<br /> * Filename: DepthFirstSearch.cpp<br /> *<br /> * Description: Without writing code DFS implementation<br /> * A B C D<br /> * \ / \ /<br /> * E F <br /> * \ /<br /> * \ /<br /> * G<br /> * Version: 1.0<br /> * Created: 03/06/2008 11:21:34 AM IST<br /> * Revision: none<br /> * Compiler: gcc<br /> *<br /> * Author: Siddhartha Singh : <siddhusingh@gmail.com> <br /> * Company: <br /> *<br /> * =====================================================================================<br /> */<br /><br />#include <iostream><br /><br />using std::cout;<br />using std::endl;<br /><br /><br />class A {<br /> public:<br /> A() {<br /> cout << "A()" << endl;<br /> }<br />};<br />class B {<br /> public:<br /> B() {<br /> cout << "B()" << endl;<br /> }<br />};<br />class C {<br /> public:<br /> C() {<br /> cout << "C()" << endl;<br /> }<br />};<br />class D {<br /> public:<br /> D() {<br /> cout << "D()" << endl;<br /> }<br />};<br />class E : public virtual A, virtual public B {<br /> public:<br /> E() {<br /> cout << "E()" << endl;<br /> }<br />};<br />class F : public virtual C, virtual public D {<br /> public:<br /> F() {<br /> cout << "F()" << endl;<br /> }<br />};<br />class G : virtual public E, virtual public F {<br /> public:<br /> G() {<br /> cout << "G()" << endl;<br /> }<br />};<br /><br />int main() try {<br /> G g;<br /> return 0;<br />} catch(...) {<br /> cout << "Uncaught exception..." << endl;<br />}<br /><br /><br />--------------------------------------------------------<br />Output :<br />A()<br />B()<br />E()<br />C()<br />D()<br />F()<br />G()<br /><br />So no need to write algo to find how DFS works ( Short cut to success ;-)Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-58616709263050582462008-02-20T16:37:00.003+05:302008-02-20T16:52:28.902+05:30Diamond Ring formation is Not a problem But a solutionMany a times in C++ people ( mostly interviewers ) ask : What is Diamond Ring problem?<br />The reply should be : It is not a problem rather a solution.<br />Scenario : When there is a common base class inherited by a child from immediate base classes. It leads to ambiguity. For e.g., Consider this situiation<br />class B : public A {};<br />class C : public A {};<br />class D : public B, public C {} //this leads to two instances of A in D , one from B another from C<br /><br />The diagram looks like :<br /> A A<br /> \ /<br /> B C<br /> \ /<br /> D<br />This causes two instances of A to be in D. Which leads to ambiguity problem the moment you create an instance of D.<br /><br />The way to resolve is A should be inherited to B and C virtually.<br />i.e <br />class B : virtual public A {}<br />class C : public virtual A {}<br />class D : public B, public C {}<br /><br />When it is virtual inheritance, it differs from normal inheritance. Standard doesn't talk about how to implement it. But the behavior is when you create any child class' object in the hierarchy what is guaranteed is the A class' constructor gets called directly from the child class ( I will write another post as how to create final class in C++ using virtual inheritance ).<br />In case of virtual inheritance the diagram would look like (diamond ring). This solves the ambiguity problem by having reference to A in B and C and not the instance of A.<br /><br /> A<br /> / \<br /> B C<br /> \ /<br /> D<br /><br />Final wordings : Diamond ring is actually a solution and not a problem.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-9326722039137079592007-10-15T17:38:00.000+05:302007-10-15T17:41:15.636+05:30Is Strategy Pattern any different than Polymorphism of OOPsI am not sure if Strategy ( or Policy ) pattern is any different than simple use of Polymorphism with Encapsulation of OOPs theory.<br />So why should it be a part of GoF Design Pattern.<br />Comments welcome<br />Cheers,<br />SiddharthaAnonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com1tag:blogger.com,1999:blog-5655479699571221327.post-70570686321369437172007-10-04T15:07:00.000+05:302007-10-04T16:12:54.786+05:30Item 10 of More Effective C++ in an easy wayThough Scott's view is that I don't have RAII, but my approach saves un-necessary complications of using auto_ptr / smart_ptr. I respect Scott's view at the same time many people are not aware of the advantages of auto_ptr / smart_ptr and why to have more learning curve when a user doesn't want it at that time.<br /><br />Basically <span> I have initialized the pointers and then allocated memory to prevent resource leak during construction in the initialization list.<br /></span><span>#include <iostream><br />#include <string><br />#include <list><br />using namespace std;<br /><br /></span><span> class Image {<br />public:<br />Image(const string& imageDataFileName) {<br />fileName = imageDataFileName;<br />}<br />~Image() {<br />cout << "~Image()..." << endl;<br />}<br />private:<br />string fileName;<br />};<br /> <br />class AudioClip {<br />public:<br />AudioClip(const string& audioDataFileName) {<br />fileName = audioDataFileName;<br />throw exception();<br />}<br />~AudioClip() {<br />cout </span><span><< </span><span> "~AudioClip()..." </span><span><< </span><span> endl;<br />}<br />private:<br />string fileName;<br />};<br /> <br />class PhoneNumber {<br />public:<br />PhoneNumber(const int number) {<br />phNumber = number;<br />}<br />private:<br />int phNumber;<br />};<br /> <br />class BookEntry {<br />public:<br />BookEntry(const string& name,<br />const string& address = "",<br />const string& imageFileName = " ",<br />const string& audioClipFileName = " ") try : theName(name),theAddress(address),<br />// theImage(0),theAudioClip(0), // so sad that multiple initialization is not allowed <img alt="Sad" /><br />theImage(imageFileName != ""<br />? theImage=0, new Image(imageFileName) //This is the trick ',' operator does the job<br />: 0),<br />theAudioClip(audioClipFileName != ""<br />? theAudioClip = 0,new AudioClip(audioClipFileName)<br />: 0) {<br />} catch(...) {<br />cout </span><span><< </span><span> "exception caught during construction of BookEntry..." </span><span><< </span><span> endl;<br />if(theImage) delete theImage;<br />if(theAudioClip) delete theAudioClip;<br />throw;<br />}<br /> <br />~BookEntry() {<br />delete theImage;<br />delete theAudioClip;<br />}<br />void addPhoneNumber ( const PhoneNumber& number);<br />private:<br />string theName;<br />string theAddress;<br />list</span><span> < </span><span>PhoneNumber</span><span>> </span><span>thePhones;<br />Image *theImage;<br />AudioClip *theAudioClip;<br />};<br /> <br />int main() try {<br />cout </span><span><< </span><span> "Hello World!" </span><span><< </span><span> endl;<br />BookEntry bookEntry("sid");<br />return 0;<br />}<br />catch(exception &e) {<br />cout </span><span><< </span><span> " exception caught " </span><span><< </span><span> endl;<br />}<br />catch(...) {<br />cout </span><span><< </span><span> "Uncaught exception..." </span><span><< </span><span> endl;<br />}<br /> </span>Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-56461827089743956832007-09-30T15:09:00.000+05:302007-09-30T15:16:53.257+05:30Subtraction in BinaryWhat do you use to subtract two binary numbers?<br />two's compliment?<br />Why to have so complicated approach ( of course on Paper )<br />Just use our basic decimal system approach and subtract the number normally.<br />For e.g.,<br />binary decimal<br />100 4<br />011 3<br /><br />subtract 4-3 = 1<br />Just think that 4 is hundred in binary and 3 is eleven ( as it looks like visually ).<br />Now subtract 11 from 100 , you will get 89. Now replace 8 by 0 and 9 by 1<br />you will get 1 as the answer in binary.<br /><br />When you subtract two binary numbers as decimal numbers, you have four possible numbers 0,1 , 8 and 9. Now since the answer should be in binary, 8 is even so replace by 0 ( as 8 mod 2 = 0) and 9 is odd so replace by 1 ( as 9 mod 2 = 1 ).<br /><br />See how easy it goes !Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-13730213012928561632007-09-27T14:29:00.000+05:302007-09-27T16:55:54.103+05:30Singly linked list as DoublyWith the linked list the major concern is the space consumed by the pointer in the structure.<br />For singly linked list, there is one extra pointer in each node to point to the next node.<br />Similarly in doubly linked list, there are two extra pointers in each node, one point to previous node and other point to next node.<br />Now depending upon the machine word size, if it is 32 bit, the pointer consume 4 bytes and in 64 bit machine it consumes 64 bits. Which is quite a bit.<br />I have written a code in C++, which just take the space of a singly linked list but it can be used to traverse both ways like doubly linked list.<br /><br />#include <iostream><br />using std::cout;<br />using std::endl;<br /><br /><br />template <typename><br />class NODE {<br /> public:<br /> NODE() {<br /> next = NULL;<br /> }<br /> NODE(const TYPE data) : data(data), next(NULL) { }<br /> TYPE getData() {<br /> return data;<br /> }<br /> NODE *getNext() {<br /> return next;<br /> }<br /> void setNext(long next) {<br /> this->next = reinterpret_cast<node>(next);<br /> }<br /> private:<br /> TYPE data;<br /> NODE *next;<br />};<br /><br />template <typename><br />class LIST {<br /> public:<br /> LIST() {<br /> XORdata = head = tail = NULL;<br /> }<br /> void add(TYPE data);<br /> void traverseForward();<br /> void traverseBackward();<br /> private:<br /> NODE<type> *head;<br /> NODE<type> *tail;<br /> NODE<type> *XORdata;<br />};<br /><br />template<typename><br />void LIST<type>::traverseBackward() {<br /> NODE<type> *tempTail = tail;<br /> NODE<type> *tempTail1 = tail;<br /> NODE<type> *tempXOR = XORdata;<br /> while(tempTail) {<br /> cout << "Data : " <<>getData() << p1 =" reinterpret_cast<"> (tempTail->getNext());<br /> long p2 = reinterpret_cast<> (tempXOR);<br /> tempTail = reinterpret_cast<node><type> *>(p1^p2);<br /> tempXOR = tempTail1;<br /> tempTail1 = tempTail;<br /> }<br />}<br /><br />template<typename><br />void LIST<type>::traverseForward() {<br /> NODE<type> *tempHead = head;<br /> NODE<type> *tempHead1 = head;<br /> NODE<type> *tempXOR = NULL;<br /> while(tempHead) {<br /> cout << "Data : " <<>getData() <<>getNext()) break;<br /> long p1 = reinterpret_cast<> (tempHead->getNext());<br /> long p2 = reinterpret_cast<> (tempXOR);<br /> tempHead = reinterpret_cast<node><type> *>(p1^p2);<br /> tempXOR = tempHead1;<br /> tempHead1 = tempHead;<br /> }<br />}<br /><br />template<typename><br />void LIST<type>::add(TYPE data) {<br /> if(NULL == head) {<br /> tail = head = new NODE<type>(data);<br /> } else {<br /> NODE<type> *temp = new NODE<type>(data);<br /> long p1 = reinterpret_cast<long>(XORdata);<br /> long p2 = reinterpret_cast<long>(temp);<br /> tail->setNext(p1^p2);<br /> XORdata = tail;<br /> tail = temp;<br /> }<br />}<br /><br />int main(int argc, char **argv, char **arge) try {<br /> LIST<int> list;<br /> for(int i = 10; i < 16; ++i )<br /> list.add ( i);<br /> list.traverseForward();<br /> cout << "Now moving backward !!!" << endl;<br /> list.traverseBackward();<br /> return 0;<br />} catch(...) {<br /> cout << "Uncaught exception!" << endl;<br />}<br /><br /></int></long></long></type></type></type></type></typename></type></node></type></type></type></type></typename></type></node></type></type></type></type></typename></type></type></type></typename></node></typename></iostream>Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com3tag:blogger.com,1999:blog-5655479699571221327.post-84815412689537513242007-09-25T15:21:00.000+05:302007-09-25T15:26:08.394+05:30Cricket PuzzleContrary to an Indian, I don't like cricket at all ( at least before twenty 20 ).<br />Though when I came through the below mentioned cricket puzzle and having interest in solving puzzles. I somehow gained interest in knowing the rules. So people who know cricket should have a look.<br />Here it goes:<br />There are last 2 balls to bowl. Both the batsman are on 94 each.<br />The team require 7 runs to win. Both has to score century as well.<br />How will they help their team to win.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com4tag:blogger.com,1999:blog-5655479699571221327.post-5923565054135821582007-09-20T19:35:00.000+05:302007-09-20T19:39:12.022+05:30Atomic Compare and Swap algorithmIs there anyone who knows how to make CSA in C/C++ to make it atomic ?<br />This would help in having producer-consumer lock free.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0tag:blogger.com,1999:blog-5655479699571221327.post-24127211056700624242007-09-20T13:13:00.000+05:302007-09-20T13:15:23.856+05:30Why VTABLE is required for Abstract class in C++I am not sure why VTABLE is required in C++ after all it is just an interface and it always refer to its derived classes only. One can manipulate the pointer to upcast but that has got no meaning ( logical ).<br />Therefore, my main question is why not optimize it and remove the VTABLE from abstract class.<br />I am looking for a satisfying answer.Anonymoushttp://www.blogger.com/profile/04233765409685340029noreply@blogger.com0