I need Books that I can’t Buy, I drink Beer that I can’t Sip

Categories: Lame
Posted on: 24th January 2009 by: kitallis

Probably, the most frustrating thing a programming hobbyist in India could find is the lack of availability of programming books. 

Most of the Universities and Schools here in India prescribe books written by Indian authors. It’s not that I’m against them in anyway, it’s just that there are better books around. 

Computer Science courses in High schools here have C++ as the programming language. The text book prescribed IMHO is absolutely not ideal to start programming. This is a two part book which covers the language and a lot of theory on programming in general (which is amazingly crappy), networking and database management (and SQL) and not to forget the worst implementations of Data Structures ever.

Most of the colleges here have C as the primary programming language in the Introduction to Programming lectures (it’s stupid starting off programming with an incomplete version of C++ and then ‘going back’ to C) and most too prescribe Let Us C by Yashvant Kanetkar. It’s a way better book than the one by Sumita Arora.

But the most appalling thing I find in these books is the fake-ish ideology of programming they present. Someone who’s new to programming would still find things behind the scenes unclear after reading them. Random explanations for memory management, overemphasis on the smaller topics are common. Many here who know C/C++ still don’t know what’s Really going on and why they are doing it.

Only a few all time popular books are available like Introduction to Algorithms, due to the fact that they are prescribed by a considerable number of Universities. You’ll have a hard time searching for something that is not taught in the Computer Science courses.

I have a growing interest in the LISP language and the only book I could find here was LISP  (CLOS, but not ANSI) and that too only a single copy by accident. You won’t even find a trace for any of the other Functional Languages.

It’s a good thing that I can see a few Ruby titles around but I’m pretty sure that you can literally count the copies in the distributor’s warehouse in an hour.
Although there are a lot of good free e-books around, it’s really difficult reading them, I can barely read a whole chapter (Wish I had a Kindle).

I made an Amazon Wish List mostly containing titles not available here. Hope someone grants it!

It’s all messed up here, all the weird laws, systems, you can’t even drink a can of Beer properly after a hard unsuccessful day of searching programming books in the whole city because you are not 25 yet, although finding kids smoking Bhang in corners. It’s perfectly legal.

Superpower India

Categories: Lame
Posted on: 20th January 2009 by: kitallis

This isn’t really it. It’s not just the professors who are inept with basic computer science knowledge.

The  Students who cleared exams for entering into the top Computer Science courses, they are actually the ones to laugh about.

Here’s a list of things I’ve heard from supposedly Intelligent kids :

  • … Hey! You know what? You can type your C code in notepad and then save it as .C and then run it in C++. (By C++ he meant the Borland C++ compiler)
  • From what Institute can I learn Hacking? I need to hack a website.
  • A : There’s an examination next week on C programming, have you prepared?
  • B : Bah! I know the whole C, I’ve executed all the code the professor gave us.
  • (me asking B) Why did you take up Software Engg. ?
  • (his reply) IT has a wide scope in India. 
  • (asking me for a copy of the Borland IDE) Do you have TC? (I don’t know why they think that the blue screen in that cranky old Borland editor is THE programming language)
  • (while writing HTML in notepad) How do you insert the anchor tag for hyperlinks?
  • (reply) Look it up in the notepad Help Topics. 

Thankfully, my professors are a little better than Uncool’s.  Although a few classics I’ve probably heard more than twice :

  • … Oracle and SQL are the same things (before repeatedly pronouncing SQL as ‘Sequel’)
  • In the practical world, Linux is not used anymore.
  • It took me 5 years to understand the difference between Multitasking and Multiprogramming

It’s not that I’m in the worst college, it’s just that people around me don’t seem to care about the stuff they learn in college, not even the things that are directly related to the course, their main objective is to score marks in exams and get jobs with lots of money.

Invariably, there are always talks on India being an IT superpower. An IT Superpower whose university’s conduct the so called ‘IT Quizzes’ filled in with questions from Database management (Well, TCS is an exception) and those random kids giving me weird looks when I read Ruby books in the library or talk about Dynamic Programing and LISP.

Implementing a Chat Server in Ruby

5
Categories: Howto, Programming
Posted on: 13th January 2009 by: kitallis

Me and Uncool participated in a ‘Linux Challenge’ recently in one of the IT Fest of the University of Delhi.
Although we just managed a Third Prize by some Python heroics in the end by Uncool, we were behind the First team only by a single problem of implementing a chat program using Unix Pipes. We had little clue about UNIX Pipes so we thought about implementing it by using standard libraries from either Ruby or Python, as they (event organizers) said they would still consider it. Expectedly, they didn’t have any trace of Ruby on their machines which were running Fedora 9.
Uncool was unsuccessful in implementing it in Python, the documentation was ugly enough.
Reasonably angry, I decided to prove myself why we could have at least won the Second prize without even a drop of sweat.

TCPSocket and TCPServer classes in the Ruby Standard Library are braindead-simple to implement.
The Ruby Programming Language shows how (comments are self-explanatory) :

# A Multithreaded Server
 
require 'socket'
 
# This method expects a socket connected to a client.
# It reads lines from the client, reverses them and sends them back.
# Multiple threads may run this method at the same time.
 
def handle_client(c)
 while true
   input = c.gets.chop                 # Read a line of input from the client
   break if !input                     # Exit if no more input
   break if input == "quit"            # or if the client asks to.
   c.puts(input.reverse)               # Otherwise, respond to client.
   c.flush                             # Force our output out
 end
 c.close                               # Close the client socket
end
 
server = TCPServer.open(2000) # Listen on port 2000
 
while true                             # Servers loop forever
 client = server.accept                # Wait for a client to connect
 Thread.start(client) do |c|           # Start a new thread
   handle_client(c)                    # And handle the client on that thread
 end
end

Gserver, one of the better standard libraries in Ruby.

More flexible than the socket library, it can be used to implement application level servers, it has a few useful predefined methods like the number of connections, event logging and handles all threading problems by itself, that means multiple users can connect on a single server at once (Asynchronous Socket programming -  which is, where many clients connect to a single server and send input for processing concurrently, the server then handles all the connected clients asynchronously and process the data as and whenever it is available from any of them.)

This little toy Chat Program reads a single input from the client, shuffles it and sends it back.

CLIENT

require 'socket'                           # Sockets are in standard library
 
sock = TCPSocket.open("localhost",1234)    # Socket to listen on port 1234
 
  l = STDIN.gets                           # Get a single input from console
  sock.puts(l)                             # Send input to the server
  sock.flush                               # Force input
  line = sock.readpartial(4096)            # Read server's response
  puts line                                # Display the response to the user
 
sock.close                                 # Close the socket

SERVER

require 'gserver'
 
# Algorithm to shuffle a string
 
def shuffle(str)
 
lenth = str.length
 
index = (lenth-1)
 
  while(index >= 0) do
 
   random_number = rand(lenth)
 
   str[random_number], str[index] = str[index], str[random_number]
 
   index = index - 1
 
  end
 
str
end
 
class Server < GServer                  # Server class derived from GServer super class
  def initialize(port=1234, *args)      # to use the initialize function
      super(port, *args)
  end
 
  def serve(io)                         # Serve method handles connections
 
      input = io.gets.chop!             # Get input from client console
      io.puts(shuffle(input))           # Return the shuffled input onto the client console
      puts input                        # Print the client message 
 
  end
 
end
 
server = Server.new
 
while (input = gets)                     # Loop server while user gives an input
 
 if input =~ /start/
   server.start                          # Start the server if the user types "init"
 
 end
 
 if input =~ /shutdown/
   server.shutdown                       # Shut the server down if the user types "shutdown"
 
 break
 end
 
end

Thin provides a TCPServer Socket backend which can also be used for similar purposes. Its pretty much the same except that it uses the EventMachine library for the Network I/O.

Shuffling

6
Categories: Algorithms
Posted on: 11th January 2009 by: kitallis

Set_0f_Cards

I was recently going through a set of commonly asked interview questions and I came across a problem requiring to shuffle a deck of 52 cards in random order. Initially, I found The Knuth or The Fisher Yates shuffle the easiest algorithm to implement.

The Knuth Shuffle makes use of a certain set  of random numbers for creating randomness. Implementing it as Code, obviously required me to make use of the rand() function.

Here’s the actual description of the algorithm from The Art of Computer Programming, Volume 2: Seminumerical Algorithms, page:145. Third Edition. D.E. Knuth

Let X1, X2, …, Xt be a set of t numbers to be shuffed.

P1. [Initialize.] Set j ← t.
P2. [Generate U.] Generate a random number U, uniformly distributed between zero and one.
P3. [Exchange.] Set k ← [jU] + 1. (Now k is a random integer, between 1 and j. Exchange Xk and Xj.
P4. [Decrease j.] Decrease j by 1. If j > 1, return to step P2.

I used my favourite language Ruby to write the code and came up with this :

array = (1..52).to_a
 
lenth = array.length
 
index = (lenth-1)
 
while(index >= 0) do
 
  random_number = rand(index+1)
 
  array[random_number], array[index] = array[index], array[random_number]
 
  index = index - 1
 
end
 
puts array

One of the problem I found was the use of the rand() function.
The use of a randomize function in real life situation is not ideal, say, in a game of Poker(online). One can easily sync the time of our clock to that of the server, If the randomize function is seeded with the number of milliseconds from the system clock as was in the case of the ASF Software’s Poker product.

A Modulus operator is used for restricting the numbers in a particular range. Like in the GNU C Library’s (GlibC) strfry() which can be used for randomizing strings. 

From Wikipedia :

Doing a Fisher-Yates shuffle involves picking uniformly distributed random integers from various ranges. Most random number generators, however—whether true or pseudorandom—will only directly provide numbers in some fixed range, such as, say, from 0 to 232−1. A simple and commonly used way to force such numbers into a desired smaller range is to apply the modulo operator; that is, to divide them by the size of the range and take the remainder. However, the need, in a Fisher-Yates shuffle, to generate random numbers in every range from 0–1 to 0–N pretty much guarantees that some of these ranges will not evenly divide the natural range of the random number generator. Thus, the remainders will not always be evenly distributed and, worse yet, the bias will be systematically in favor of small remainders.

Googling around turned out that sorting it by using UUID’s as a source of random numbers was more easier to implement.
Ruby offers a library for generating UUID’s which uses /dev/urandom on *nix types systems to generate random numbers.
A GUID can be created by these two lines.

require 'guid' 
 
g2 = Guid.new  #a unique GUID every time

It’s typically not faster, as sorting would be O(n log n) compared to the O(n) (linear time) for the Knuth Shuffle.

Wolfram MathWorld has a few mathematical shuffling algorithms and randomization techniques for further mathematical reference.