Monday, January 14, 2013

Reverse a string by words

Wow! Accidentally created a nice code to reverse a string by words. Reversing a string is easy, but the problem arises when we have to reverse the word positions.

Target: This is a good string => string good a is This
Strategy: Simply reverse the whole string and then reverse each word
Code:
    char str1[] = "This is a good string";
    size_t j = strlen(str1)-1;
    //Step to reverse the whole string
    for (size_t i=0; i
        swap(str1[i],str1[j]);
    }

    //Step to reverse each word, word by word
    stack stk;
    for (size_t i=0; i<=strlen(str1); ++i){
        if ( (str1[i] != ' ') && (str1[i] != '\0')  )
            stk.push(str1[i]);
        else {
            while(!stk.empty()){
                cout<
                stk.pop();
            }
            cout<<" ";
        }
    }

Sunday, November 7, 2010

Since morning I’m feeling pissed off. Now, don’t bother to ask why. Even if you do you won’t get anything other than a blank look from me.

I’m feeling sleepy and groggy too. I have to reach home early today, so I came to work early. My PoW (place of work) expects we to do so. If that’s not torture then what is?

The bus to PoW is supposed to drop me at a bus stand 1 kilometer away but it dropped me 1 and half kilometer away. I can do without this forced morning workout. I didn’t like it at all; the walk I mean. Anything out of normal worries me.

I am a sissy at heart. To hide that, I force myself to stare at a lizard or a grasshopper, especially when some nubile nymphet is hovering around. Meanwhile I pray they don’t jump on me, either the bug or the nymph; that would have catastrophic consequences to one and all.

My stomach is upset. When is it not? When the food is good it revolts, when not so good it revolts. I guess my stomach is yet to get used to food even after sub-30 years of conscientious effort on my part to feed it.

That speaks a lot about me. At times I feel I’m so bereft of ambition. That’s scary, isn’t it? But I don’t feel scared about it. For me that’s scary.

Something else is scary too. I am a closeted violent person. Today I saw an ugly guy with a beautiful girl, again. I felt like killing the ugly guy, again. I did not do anything, again.

I think I’m writing junk. I’m sure you agree too.

The CWG games are going on smoothly, at least by the yardstick of the ruckus it created before the games started. That’s adding to my frustration. An event in India is no event unless there’s some foreign hand showing up once in a while. But till now the hand has been conspicuous by its absence. I don’t like that. Since morning I have scourged through 3 national, 1 international and 1 irrational (Dawn Pakistan) papers but none of them have anything bad to say about CWG.

Yesterday men’s Hockey team lost to Australia big time. Well, when it does not? Most of the channels did not care to carry the news. Well when do they?

Road to my PoW is all dug up. I don’t like coming to office jumping about. I can do without this forced morning workout. Oh, I think I’m repeating my words. Ignore this one or the last one; whichever is convenient for you.

Talking about jumping, someone from India won bronze in gymnastics yesterday. The kid was jumping around like a 4 year old but without his shoes on. Yet he got the medal. I don’t know if gymnasts are not allowed to wear shoes or the poor boy could not afford one. Or maybe the security personnel did not allow him in with his shoes on. The kid won a medal. Ahh! repeating again. But he could have done better with some slippers on.

By the way I want to meet the performer who came last. Maybe that poor fellow was also having a bad day.

So there’s somebody who also had a bad day. That makes me feel better already.

Thursday, November 5, 2009

Perl

Perl (for me)

1. How chomp can be screwed up

########################

#! /usr/bin/perl -w

$/="something";

chomp ($name = );

#chomp $name;

print "$name\n";

########################



Now what happens is chomp won't remove the newline. It will remove
'something'!!!

This is because $/ by default is set to "\n" and we have set it to
'something'.

Good thing to remember.


2. Something about Lists

########################

#! /usr/bin/perl -w

@abc= ("a","b","c","d");

print @abc,"\n";

print "@abc\n";

########################

OUTPUT

abcd

a b c d


3. Printing arrays in so many ways (Look at ***5***)

#######################

#! /usr/bin/perl -w

@abc= ("a","b","c","d");



print "\n***1***\n";

for ($x=0;$x<=$#abc;$x++) { print "$abc[$x]"; } print "\n***2***\n"; for $x (0..$#abc){ print "$abc[$x]"; } print "\n***3***\n"; foreach $alphabet (@abc){ print "$alphabet"; } print "\n***4***\n"; foreach (@abc){ print "$_"; } print "\n***5***\n"; foreach (@abc){ print ; }


print "\n***6***\n";

print @abc[0..$#abc],"\n";


4. Using 'Last'


#######################


#! /usr/bin/perl -w

@alphabets = ('a','b','c','d','e','f','g','h','i');

foreach $letter (@alphabets) {

print "$letter\n";

last if $letter=~/e/;

}

#######################


5. Splice
#######################
#! /usr/bin/perl



@vowels = ('a','e','i','o');

@alphabets = ('a','b','c','d');

&display;

splice (@vowels,0,0, @alphabets);

&display;


sub display{

print "Vowels: @vowels\n";

print "Alphabets: @alphabets\n";

}
#######################


6. HASH

########################

foreach $x (sort hash_val_descending (keys(%hash_val))) {
print OUTFILE "$x \, $hash_val{$x} \n";
}
print "\nOUTPUT FILE: merged.csv\n";

close OUTFILE;
close INFILE;
}

sub hash_val_descending {
$hash_val{$b} <=> $hash_val{$a};



Monday, April 20, 2009

IF

If you can keep your head when all about you
Are losing theirs and blaming it on you,
If you can trust yourself when all men doubt you
But make allowance for their doubting too,
If you can wait and not be tired by waiting,
Or being lied about, don't deal in lies,
Or being hated, don't give way to hating,
And yet don't look too good, nor talk too wise:

If you can dream--and not make dreams your master,
If you can think--and not make thoughts your aim;
If you can meet with Triumph and Disaster
And treat those two impostors just the same;
If you can bear to hear the truth you've spoken
Twisted by knaves to make a trap for fools,
Or watch the things you gave your life to, broken,
And stoop and build 'em up with worn-out tools:

If you can make one heap of all your winnings
And risk it all on one turn of pitch-and-toss,
And lose, and start again at your beginnings
And never breath a word about your loss;
If you can force your heart and nerve and sinew
To serve your turn long after they are gone,
And so hold on when there is nothing in you
Except the Will which says to them: "Hold on!"

If you can talk with crowds and keep your virtue,
Or walk with kings--nor lose the common touch,
If neither foes nor loving friends can hurt you;
If all men count with you, but none too much,
If you can fill the unforgiving minute
With sixty seconds' worth of distance run,
Yours is the Earth and everything that's in it,
And--which is more--you'll be a Man, my son!

--Rudyard Kipling

Wednesday, January 21, 2009

Technical

Makefile
cp a b . ; \
cp c . ;

The \ indicates that both the cp are to be done on the same shell, that is they will be inclusive. But if I remove the '\' the cp commands will be exclusive. They will be executed with a break in continuity.

BASH
Searching and changing permission of files and folders

FILE
find . -name "*" -type f -exec chmod 444 {} \; -print

DIR
find . -name "*" -type d -exec chmod 555 {} \; -print

SCP
All of us have faced this problem one time or the other. We do a scp, and midway through the process scp feels knotty(naughty). The solution is rsync. To resume a partially scp-ed file we use rsync.

THE PROBLEM
$> scp anjan@server1:/a/b/xyz
95% complete
Connection timed out :-(

THE SOLUTION
$> rsync --partial --progress anjan@server1:/a/b/xyz

VIM Tip

1. There are lots of other neat things you can do with block selects. Here is a way of adding a string to the end of each line, like so:

i. Press Ctrl+V and then j to extend the selection to all the lines you want.

ii. Press $. This will create a 'ragged edge' selection that extends to the right end of each line in your selection.

iii. Press A. I inserts text at the beginning of a block selection, A appends text at the end of a block selection.

iiii. Type your text and press Esc.

2. To search for ':' and remove everything in the line after that
:%s/:.*$//gc

3. All words are jumbled in one line. The must be put in separate lines...
:%s/\ /\r/g (search blanks and replace with return; globally)

4. map = j$?\/d$

PERL
To chk if the process whose pid is known is alive or dead

#! /usr/bin/perl
$exists = kill 0, $PID ;
if ($exists) {print "YES\n";} else {print "NO\n";}

Friday, January 2, 2009

Lets plan a trip and skip the meet

To travel hopefully is a better thing than to arrive.
-R.L. Stevenson

So aptly said but not so widely appreciated. A new year has dawned upon us. Old and new calenders have changed places. Till yesterday what decked our desks has now been relegated to the bin. Give the new a chance is what seems to be the mantra. These were the thoughts when I woke up in the morning. I immediately left my bed and went to the living room. Subhro was already up and he was already looking at the new calender. In many things our frequencies match.

Turn turn sift sift...yes here is the holidays list. "Wow, so many 4 day weeks this year". I said, "look 26th Jan is a Monday".
"Why not plan something?"

"Plan what", came the instant retort from Subhro.


"Plan anything you fool."


"So be it if you insist. Let's wake up early", quipped Subhro in all seriousness, "and catch the live telecast from
Rajpath from the very beginning. I never seen it from the beginning. Ages ago when I was 5-6 my mom once pulled me out of the bed early; I was all groggy and very annoyed and..."

"Ah cut the crap. Someone please do something with this fellow. Well what can I say, other than curse my luck to be talking to you".


"What do you mean? You yourself asked me to plan something and I did. God! if I do I am damned, if I do not then also I am damned" said Subhro in a mocking anger. He knows very well how to annoy me.


"It was not your fault, planning, thinking, contemplating, I should not associate these words with you".


This is our general lingo. Nobody takes offense. But the other person always waits for the chance to give back in the same coin as soon as possible.


"I was thinking of a trip." I said.


"Great. As a matter of fact I was also thinking about it. I have shortlisted on either Goa or Pondicherry". "Both places are very similar yet very distinct too".

That's the fun part with Subhro my room mate and in many ways my alter-ego. We can think alike.


"Exactly my thought". I have already thought of these two places with a bit of a tilt towards Pondicherry. I told this to Subhro and it seemed he also agreed to it.


I am not the bag packer type tourist who just has to pick the sack and start the journey. I love to plan and plan hard. More than the tour it's the planning which fills me with joy and excitement. Many don't agree though.


"So how are we going". "Car or bus or train may be. If we are going to Goa then car is not a very good option. so we need to fix on the place".


"The weekend is Friday 23rd, Sat 24th, Sun 25th and finally 26th Monday. Pondi takes 8hrs, we start
earliest morning at around 4:00. We can take Bangalore-Krishnagiri-Chennai-Pondicherry route or the Chennai route but that will add some extra Kms. I heard that Chennai route is good so many people take it. We need to find someone who has been there rcently". Subhro continued, "10hrs is my estimate. So ideally we should be there by 2:00pm unless we plan to stop at Gingee Fort. So anyway we can be there by 6pm". "We can make a booking in the Aurobindo Ashram"

"We can not take accomodation in the Ashram, remember. No late nights no
Khamba".

Suddenly Subhro jumped off the chair. It's already 8 and today is not a holiday.


"Do some more reserach. We have to chalk out the trip ASAP. Oh yeah today you have your client call so don't be late on first day..." and saying this Subhro marched into the bathroom.


He had his revenge.





Saturday, November 22, 2008

Rain and you

After so long a pleasant Saturday evening all to myself, but I want to share it with you.

The raindrops, the tinkling of your bangles, the smile, a golden streak of sun ray peeking from behind the clouds. Has anyone seen the color of longing? I think I have, the crimson color of pain mixed with the blue color of excitement. Add to it some silver and golden hues of the overcast sky, it had rained the whole day. I wish you were here. I know it will be too much to ask for, I know you don't care. But still deep inside an ache, a pain...the pain of longing or of yearning.

The window still is shut tight, but the heart...a fool looks back again and again and again some more... if only once by mistake it opens and the breeze carries the wisp of your scent....

Yes I am mad, but for you.