Twin Primes

A Math oriented question asked at a recent Amazon interview.

Q : Given any twin prime pair, prove that the number between the twin primes is always divisible by 6.

Twin Prime (from Wiipedia) :

A twin prime is a prime number that differs from another prime number by two. Except for the pair (2, 3), this is the smallest possible difference between two primes. Some examples of twin prime pairs are (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), ... (821, 823), etc. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin.

Panlindrome Dates

Asked at a recent Amazon interview : 2001-01-02 is a palindrome date.
Find the previous closest palindore date?

Reverse words in a sentence

Given an array of characters, reverse the words in the sentence.
For example, if the sentence is "Reverse these words", then the output should be "words these reverse".

Source : this interview q

Find duplicates in an array

Given an array of size 'n', containing elements from 1 to 'n', find out if there are any duplicates in the array. Solve this, if
  • a single duplicate number exists
  • multiple duplicate numbers exist
 Source : CLRS & this blog question (that I did not get)

Find subarray with maximum sum

Given an array of size n, containing positive and negative integers, find the longest sub-array such that the sum of the elements in the sub-array is the maximum.

For example,
Given array :
10, 8, -5, 1, -27, 5, 7, -5, 11
the sub array should be : 10, 8

Source : CLRS & this sample interview question

Callbacks in Java

Recently I interviewed a couple of folks. One of the guys was a C++ guy and I thought of delving into the tricky and interesting land of function pointers with him. This is when the question in the title occurred to me : How would you implement callbacks in Java?

Its nothing new, its nothing great, but I was just curious how the candidate would apply his language feature proficiency to implement a real world problem. I asked that question to that candidate and two more, after which I thought I should write this post. None of the three candidates knew how to do it. Worse one of them was completely bewildered and was like "what are you trying to say???". Damn it!!! :(.

Well here is my take on implementing Callbacks in Java. Hope you find it useful.

What are callbacks?
A callback is a paradigm by which a general purpose library can delegate (generally domain specific) parts of its execution to an external, more appropriate owner. This fits well with the "separation of concerns"process - your code will do just the work it understands.

A classic example is the sort functionality - references are available in C++, Java and other languages. The sort method, typically, would accept the list of objects to be sorted, along with an optional callback for object comparison. The sort method (the general purpose library) knows how to sort lists very well, but does not need to know the algorithm to decide the ordering of two given data objects (comparison of data objects). Since comparison of the data object (your domain specific decision) is an important part of the sorting algorithm, the sort method will allow you to specify a function that it can call when it needs to compare two of your data objects. This function is the callback.

Why the fuss?
Callbacks are great! They are means available for developers to write layers of generic code that is reusable across domains with a minimal overhead. We most certainly use callback in our day-to-day code, probably without realizing them (hence those 3 candidates). Callbacks are the backbone for various implementations - lifecycle listeners (in containers), Spring (HibernateTemplate, JdbcTemplate and more), Collections.sort(), .... the list goes on.

Nice. How are they implemented in Java?
Lets just think about it - what is the callback specifying? Its allowing the caller to specify the method to be called from the method to-be-called. This could mean, at least, two things - either the method to-be-called is given the exact callback method (within an instance / global context) OR the method to-be-called declares that it would call a specific method name with specific parameters (on the callback being passed) and its the responsibility of the caller to ensure that such a method exists in the callback object's context.

While the first approach is possible in languages like C++, the second approach fits the Java world. Another read of the second approach tells us that what we taking about is a contract - a binding that the caller must confirm to, which the method to-be-called can rely on.

In Java, how are contracts specified?? Well - by using interfaces. If the method to-be-called accepts an instance of an interface, as its callback parameter, then  it will enforce the caller to implement an object that implements the methods from that interface. The method to-be-called should, however, declare beforehand which methods from the interface it would calls from within its code at what time (the contact of the methods).

Hope this brief article was helpful. For further detailed reading (specially the Command pattern usage) please refer to these links :
http://www.javaworld.com/javaworld/javatips/jw-javatip10.html
http://www.javaworld.com/javaworld/javatips/jw-javatip68.html
http://stackoverflow.com/questions/1476170/how-to-implement-callbacks-in-java

BASIC Macro To Get Stock Quotes for OpenOffice Calc

I've been trying to figure out to keep track of various tips, suggestions and recommendations that various financial experts throw all the time on all the major stock market information websites. While I definitely like moneycontrol.com (for India markets), I really hate the fact that it does not allow me to track my watch list conveniently. For example, I add stock to a watch list, I enter some notes, but then those notes are not visible to me while viewing the watch list :(

Also, since what I am maintaining is a watch list, I would like to record recommended target / buy prices ad trigger alerts on those. So I came up with this small spreadsheet template that will record all this information and give a snapshot of the watch list.

The biggest blocker in this task was how to populate the "current" stock price. So, I wrote this simple BASIC Macro that,  given a stock symbol, will fetch the current price of the stock. Salient points about the script :
  1. The script was written for OpenOffice Calc, but should work in Excel as well.
  2. The script pulls its data from in.finance.yahoo.com, but this can be replaced with the country's specific address and everything should just work fine. For example, for US market replacing http://in.finance.yahoo.com with http://download.finance.yahoo.com will work as-is.
  3. You can also replace the source http://in.finance.yahoo.com, with something completely different (for example http://www.nseindia.com/marketinfo/equities/ajaxGetQuote.jsp), but then the parsing of the returned data will have to change.
  4. To start using the script for your spreadsheet, do ensure that the sheetNocr and destCol variables at the start of the script point to correct locations in your file.
Here is the Macro :

Sub FillStockQuotes
Dim c as Integer, r as Integer, destCol as Integer, sheetNo as Integer
Dim Sheet, Cell, DestCell
Dim symbol as String

REM Which sheet contais the above rows and columns. This is a zero based index (First sheet is sheet no 0)
sheetNo=0
REM Which column has the styock symbol. This is a zero based index (1st column is column no 0)
c=1
REM Which row has the styock symbol. This is a zero based index (3rd row is row no 2)
r=2
REM Which column do you want to store the quote in. This is a zero based index
destCol=6

Sheet = thisComponent.Sheets(sheetNo)
do while true
Cell = Sheet.getCellByPosition(c, r)
symbol = Cell.String
if symbol = "END OF SYMBOLS" then
Print "Processing Complete"
exit do
end if
Dim stockQuote as Currency
stockQuote = GetSymbolQuote(symbol, Sheet)
REM Print " " & symbol & " : " & stockQuote
if stockQuote <> "" then
DestCell = Sheet.getCellByPosition(destCol, r)
DestCell.Value = stockQuote
end if
r=r+1
loop
End Sub

Function GetSymbolQuote(symbol as String, aSheet as Object) As Currency

if symbol = "" then
GetSymbolQuote = ""
Exit Function
end if

Dim sUrl As String, sFilter As String
Dim sOptions As String
Dim stockSymbol As String
Dim fValue As Double
Dim oSheet as Object, oSheets as Object

sUrl = "http://in.finance.yahoo.com/d/quotes.csv?s=" & symbol & "&f=sl1"
sFilter = "Text - txt - csv (StarCalc)"
sOptions = "44,34,SYSTEM,1,1/10/2/10/3/10/4/10/5/10/6/10/7/10/8/10/9/10"

oSheet = createSheet(thisComponent.Sheets)
oSheet.LinkMode = com.sun.star.sheet.SheetLinkMode.NONE
oSheet.link(sUrl, "", sFilter, sOptions, 1 )

stockSymbol = oSheet.getCellByPosition(0,0).String
fValue = oSheet.getCellByPosition(1,0).Value

GetSymbolQuote = fValue
End Function

Function createSheet(oSheets as Object)
Dim oSheet as Object

If oSheets.hasByName("Link") Then
oSheet = oSheets.getByName("Link")
Else
oSheet = oDocument.createInstance("com.sun.star.sheet.Spreadsheet")
oSheets.insertByName("Link", oSheet)
oSheet.IsVisible = False
End If

createSheet = oSheet
End Function



 
Moviehole-madhurtanwani © 2010 | Designed by Chica Blogger | Back to top