[algogeeks] Re: A theoritical question

2011-12-07 Thread Gene
You can't if you are trying to print a binary representation. This extends to any integer base. The binary representation of an irrational square root never repeats or terminates. That's why it's called irrational!. So there can exist no machine the prints it exactly. You can however: 1)

[algogeeks] Re: Permutation Problem with repeating characters

2011-12-07 Thread Gene
Here is the algorithm for printing all permutations ignoring repeats: char buf[MAX_LEN]; void swap(int i, int j) { char t = buf[i]; buf[i] = buf[j]; buf[j] = t; } void recur(int start, int len) { if (len == 0) printf(%s, buf); else { for (int i = 0; i len; ++i) { swap(start, i);

[algogeeks] Re: Reverse a XOR linked list in O(1) time ?

2011-12-01 Thread Gene
Nodes of these XOR lists look like typedef struct { PTRS_AS_INT next_xor_prev; DATA data; } NODE; You need 2 pointers to adjacent nodes to traverse. If p and q are these pointers, then to advance to the next node, tmp = p; p = q ^ p-next_xor_prev; // not correct C; add casts to make it

[algogeeks] Re: What is the difference between Reentrant and Thread Safe code ,please explain with example funcitons..

2011-11-29 Thread Gene
They're apples and oranges: both fruit but not directly related. Reentrant is a very old and general term that predates the term thread. Code is reentrant when it's safe to interleave executions: suspend one execution at any time and start or continue another one, with all executions producing

[algogeeks] Re: Finding the repeated element

2011-11-26 Thread Gene
that's included in a list an odd number of times rather than an even number of times. On Nov 24, 3:56 pm, Ankur Garg ankurga...@gmail.com wrote: ^^+1..how matrix formed ?? But as Gene said we can use a set to store all the unique elements Now we xor all the set elements and then xor them

[algogeeks] Re: Threaded binary tree

2011-11-25 Thread Gene
Perhaps the simplest way is to do a normal inorder traversal and, as you visit nodes, keep track of the last one visited in an external (global or class) variable. When you visit a new node and the last node has a NULL right child pointer, you can update it with the new node. If the new node has

[algogeeks] Re: Finding the repeated element

2011-11-24 Thread Gene
Finding duplicates in a multiset is a pretty standard problem. I've only ever heard of two solutions, and it's unlikely there are others. One is to sort, which will place duplicates adjacent to each other, so you can find them by comparing a[i] with a[i+i] for all I. This algorithm is O(sorting

[algogeeks] Re: Xor Linked lists

2011-11-24 Thread Gene
This is very language-dependent. In assembly it's no problem at all! In C you must coerce to an integer type where xor is possible. The portable way to make this work including 64-bit systems is to use type uintptr_t from stdint.h. Not all compilers have this. Perhaps the next best hing to try

[algogeeks] Re: finding closest points

2011-11-23 Thread Gene
Exactly. But I think you can get O(n) by using the linear time K- median selection algorithm (see for example http://en.wikipedia.org/wiki/Selection_algorithm) on the distances to the target point. These kinds of questions where you process all n points every time are seldom of practical

[algogeeks] Re: An Array Problem

2011-11-23 Thread Gene
It's a nice problem, and this solution is almost right. Process the input in _reverse_ order, which means we'll also generate output in reverse order. The invariant is that the stack is a sorted list - highest value on top - of the strictly descending subsequence of elements seen so far in

[algogeeks] Re: Recurrence relation

2011-11-23 Thread Gene
Solving recurrences is an art form. There are many techniques. One of the simplest is to assume you know the form of the result with some unknown coefficients. Then plug the form into the recurrence and try to solve for the coefficients. If you succeed, you're done. If not, look for another

[algogeeks] Re: An Array Problem

2011-11-23 Thread Gene
by tech coder is fine and is working .. I coded it and its working perfectly using stack On Wed, Nov 23, 2011 at 2:50 PM, Gene gene.ress...@gmail.com wrote: It's a nice problem, and this solution is almost right. Process the input in _reverse_ order, which means we'll also generate output

[algogeeks] Re: An Array Problem

2011-11-23 Thread Gene
Sorry I forgot to initialize p. It's fixed below. On Nov 23, 6:59 am, Gene gene.ress...@gmail.com wrote: Thanks. Maybe I'm not reading correctly, but tech coder's algorithm doesn't mention anything about pairs, which are necessary to obtain O(n).  This is what I meant by almost. In reverse

[algogeeks] Re: Recurrence relation

2011-11-23 Thread Gene
, but there is a rich theory of generating functions that is widely regarded as a powerful tool for solving recurrences. The guess and confirm method that I described is covered in more detail in http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/2009/notes/99-recurrences.pdf Gene On Nov 23, 12:58 pm

[algogeeks] Re: Time Complexity

2011-11-22 Thread Gene
. Gene On Nov 21, 11:13 pm, atul anand atul.87fri...@gmail.com wrote: @Gene : i guess you are considering balanced tree. what if the tree is left skewed or right skewed . then height of thee will ne H=No. of node. so we will get :- 1+2+3+4H so recurrence will be T(n) = T(n-1) + O(n

[algogeeks] Re: Time Complexity

2011-11-20 Thread Gene
My advice is don't guess. Do the math. To print level L of a perfectly balanced tree, you will traverse 2^L -1 nodes. The outer loop that prints levels 1 .. H will therefore traverse sum_{L=1..H} (2^L - 1) = 1 + 3 + 7 + ... 2^H - 1 Let N = 2^H - 1 be the number of nodes in the tree. Then

[algogeeks] Re: Find all possible paths(Amazon)

2011-11-20 Thread Gene
This is a pretty silly question unless the graph is quite simple or small (because the output size is generally exponential wrt the input) and acyclic (when there are infinitely many paths). If I were interviewing someone, I'd like to have them tell me this before starting to describe an

[algogeeks] Re: deep vs shallow copy

2011-11-17 Thread Gene
The most extreme shallow copy is just copying a pointer to a large data structure like a graph or tree. Deep copy is copying the entire data structure and returning a new pointer. Here is a more common example: typedef struct list { struct list *next; void *data; } LIST_NODE; In practice

[algogeeks] Re: kth smallest element

2011-11-16 Thread Gene
This is a beautiful way to express the algorithm. The magic that Don has omitted is that just as in normal binary search, you can hypthesize that A[i] is the k'th element meaning that A[1..i-1] = k, which forces you to conclude the other k-i elements must be in the prefix of B, which is

[algogeeks] Re: Median of 2D matrix

2011-11-13 Thread Gene
(N^2) *because there are N^2 elements. On Tue, Nov 8, 2011 at 6:58 AM, vikas vikas.rastogi2...@gmail.com wrote: Gene, we are not creating heap here but using the sorted matrix as heap itself. so use same logic of removing items from heap , in this case you have either right/bottom

[algogeeks] Re: Median of 2D matrix

2011-11-13 Thread Gene
and couldn't find a good source for the K-Median Theorem. So, could you provide a good link? On Tue, Nov 8, 2011 at 2:55 PM, sagar sindwani sindwani.sa...@gmail.comwrote: Use K-Median theorem with k=N On Mon, Nov 7, 2011 at 11:33 PM, Gene gene.ress...@gmail.com wrote: Can you explain how

[algogeeks] Re: free() function

2011-11-13 Thread Gene
Not meaning any disrespect, this argument is about as wrong as it gets in computer science. Predicting when memory will be free in a running program at compile time is called an _undecidable problem_. This means it's totally impossible to write a C / C++ compiler that will produce an executable

[algogeeks] Re: heap memory

2011-11-07 Thread Gene
, 12:17 pm, himanshu kansal himanshukansal...@gmail.com wrote: @Gene: since the article itself says that if the memory is allocated through malloc, it will make some (less) sbrk calls to the system to increase the allocated memory to the program. then how can a wrapper function will do

[algogeeks] Re: Median of 2D matrix

2011-11-07 Thread Gene
algorithm to find the median of any array by sorting rows and columns in O(2 sqrt N * sqrt N * log sqrt N) = O(N log N) then apply the solution recursively on sqrt N elements. It is no better though than the unstable O(N) method of qsort 1 branch. On Nov 5, 2011, at 23:32, Gene gene.ress

[algogeeks] Re: Median of 2D matrix

2011-11-07 Thread Gene
. Dave On Nov 6, 3:11 am, mohit verma mohit89m...@gmail.com wrote: @Gene As i said in my earlier post right to left diagonal partitions the martix into 2 equal number of elements. So now the median must be in this diagonal. Now our focus is on finding median of this diagonal only

[algogeeks] Re: heap memory

2011-11-05 Thread Gene
In C you can get close by wrapping malloc() and free() and maintaining your own total. This will not capture the header within each malloc()'ed block. You can also use a tool like valgrind . The behavior of sbrk() is totally OS dependent, and sbrk() doesn't exist on e.g. Windows. This method

[algogeeks] Re: Median of 2D matrix

2011-11-05 Thread Gene
, 1:29 am, Gene gene.ress...@gmail.com wrote: Here's an idea.  Say we pick any element P in the 2D array A and use it to fill in an N element array X as follows. j = N; for i = 1 to N do   while A(i, j) P do      j = j - 1;   end;   X(i) = j; end; This algorithm needs O(N

[algogeeks] Re: Median of 2D matrix

2011-11-04 Thread Gene
Here's an idea. Say we pick any element P in the 2D array A and use it to fill in an N element array X as follows. j = N; for i = 1 to N do while A(i, j) P do j = j - 1; end; X(i) = j; end; This algorithm needs O(N) time. The elements of X split each row with respect to P. That is,

[algogeeks] Re: Median of 2D matrix

2011-11-03 Thread Gene
Try 1 2 3 2 4 5 3 4 6 1 2 2 3 3 4 4 5 6 Median 3, median of medians is 4. On Nov 2, 11:33 am, Anup Ghatage ghat...@gmail.com wrote: Median of Medians? On Tue, Nov 1, 2011 at 10:44 PM, Ankuj Gupta ankuj2...@gmail.com wrote: We have a N X N matrix whose rows and columns are in sorted order.

[algogeeks] Re: Designing Data Structure

2011-11-03 Thread Gene
Often you can get optimal performance with unusual combinations of operations by combining data structures. Here you can get O(1) for all operations by combining a hash table and a bag of pointers in an array. The hash table references bag elements by index, and the bag elements point back at hash

[algogeeks] Re: Dp solution for this problem?

2011-10-30 Thread Gene
You can convert this into a regular SP problem on a graph and use a classical SP algorithm. In this graph, the nodes are labeled with pairs (i,j). If M[A,B] is your matrix, then the graph's adjacency matrix C[A,B] is just C[ (iA, jA), (iB, jB) ] = { M[ iB, jB ] if abs(iA-iB) = 1 abs(jA-jB) =

[algogeeks] Re: Reconstruct BST from preorder traversal

2011-10-18 Thread Gene
It turns out preorder is enough if you know it was generated from a BST. Inorder is needed if it was an arbitrary tree. One way to code the algorithm is with a stack to hold nodes that already have a left child and might still need a right one. // assume: unique keys // root is the tree we're

[algogeeks] Re: Sorting a array which is already sorted but has some disorder

2011-10-18 Thread Gene
As others have said this is not stated precisely. There are lots of sorting algorithms that have O(n) behavior on nearly sorted data.Quicksort and mergesort can both be implemented to get this behavior. However if you are very confident that elements are not very far from their correct sorted

[algogeeks] Re: Reconstruct BST from preorder traversal

2011-10-18 Thread Gene
) { print_tree(read_tree()); return 0; } On Oct 18, 10:09 am, Gene gene.ress...@gmail.com wrote: It turns out preorder is enough if you know it was generated from a BST.  Inorder is needed if it was an arbitrary tree. One way to code the algorithm is with a stack to hold nodes that already

[algogeeks] Re: Code it...

2011-10-18 Thread Gene
Not really. Most executable formats have a way to include extra data that's not used by the loader. You could store a count in such data and have the program modify the executable every time it runs. Not recommended, though. A separate file is a much better idea. You could also play games by

[algogeeks] Re: How to Solve This

2011-10-13 Thread Gene
number ) An unverified one because my machine ran out of memory while multiplying (but which took about .05 seconds to find) is: 1,638,726 1's = 9,876,543 times (a 1,638,719 digit number ) On Oct 12, 4:35 pm, Gene gene.ress...@gmail.com wrote: First note: 0 * 3 = 0 7 * 3 = 21 4 * 3 = 12 1

[algogeeks] Re: Find the later version

2011-10-12 Thread Gene
As others have said, you have not completely specified the problem. If you always have exactly 4 base 10 numbers separated by dots, and you are working in C or C++ then you can use sscanf to get the numbers and compare them: // Return: // positive if version s1 is an earlier version than s2, //

[algogeeks] Re: How to Solve This

2011-10-12 Thread Gene
First note: 0 * 3 = 0 7 * 3 = 21 4 * 3 = 12 1 * 3 = 3 8 * 3 = 24 5 * 3 = 15 2 * 3 = 6 9 * 3 = 27 6 * 3 = 18 3 * 3 = 9 Important is that the final digits of each line count 0 to 9. Now you can build an answer right to left. Example: 123. Check the table to get the rightmost 1. 7 * 123 = 861

[algogeeks] Re: Memorization

2011-10-12 Thread Gene
; i++) {   f = p + q;   p = q;   q = f; } But as gene mentioned, in complex programs involving dynamic programming we might need to access more than 1 or 2 previously obtained values. To reduce the burden of recalculating old values, we preserve them in a hash/table/array, as the case

[algogeeks] Re: Memorization

2011-10-11 Thread Gene
Memoization just adds a persistent map for the memoized function. It stores mappings from tuples of function arguments to the corresponding return value. Each time the function is called, its memoized version first checks the map to see if a result has already been computed. If so, it just

[algogeeks] Re: recursion

2011-10-04 Thread Gene
For a local value with an array type, yes, a fresh array is allocated for each recursive call. In C, C++, and languages with reference semantics like Java and Lisp, array parameters are passed as pointers or references, so no fresh array is allocated. In Pascal, call-by-value parameter arrays

[algogeeks] Re: MS question

2011-09-27 Thread Gene
asked in MS by me.. I suggested O(m*n) but they were looking for a solution in nlogn ( n*n Sparse Matrix ) ..Any idea ... This post was discussed earlier but every1 came with O(m*n) solution so instead of cluttering it ..opened a new One ... On Tue, Sep 27, 2011 at 3:06 AM, Gene gene.ress

[algogeeks] Re: MS Question - Median of a BST without using extra space and in O(n)

2011-09-27 Thread Gene
And you have to use the pointer-reversing trick to traverse the tree because you don't have space for a stack. On Sep 27, 4:52 am, anshu mishra anshumishra6...@gmail.com wrote: do the inorder traversal as soon as reached at n/2th element that will be median. -- You received this message

[algogeeks] Re: MS Question - Median of a BST without using extra space and in O(n)

2011-09-27 Thread Gene
This requires O(n) extra space. On Sep 27, 7:43 am, anshu mishra anshumishra6...@gmail.com wrote: int bstMedian(node *root, int n, int x) {     if (node-left) return bstMedian(root-left, n, x);     x++;     if (x == n/2) return node-val;     if (node-right) return bstMedian(root-right, n,

[algogeeks] Re: Modified binary search

2011-09-27 Thread Gene
Indeed you must be given that all the array elements are unique or at least that there are no more than floor(n/2) repeats). Otherwise this is impossible. The simplest way to think about it is first to search for i such that a[i] a[i+1]. At that point you know there are two sorted ranges

[algogeeks] Re: BST in file

2011-09-26 Thread Gene
Here is a little program to show how it works. It's a nice little problem. There is also a coding with recursion. #include stdio.h #include stdlib.h typedef struct node_s { int data; struct node_s *left, *right; } NODE; void print_tree(NODE *tree) { if (tree == NULL) return;

[algogeeks] Re: google os ques on pipelining

2011-09-26 Thread Gene
You guys have the right idea except that since it's multiple choice you can do this with no math. With 1000 data items and only 4 stages, the bottleneck has to be the slowest pipeline stage with its register delay. So you can answer b in 10 seconds and move on to the next question! On Sep 26,

[algogeeks] Re: MS question

2011-09-26 Thread Gene
I assume we don't want to use extra storage. So one way is this: Go over the matrix and mark the first row with a 1 and the first column with a 1 for each 1 you find. Because row and column 1 are used for temporary storage in this manner, you must first remember whether they contained a 1, then

[algogeeks] Re: sqrt function...

2011-09-25 Thread Gene
Binary search isn't the right term. Rather you want bisection. But for each iteration it adds only one bit to the precision of the answer. You should also look at Newton's method. It doubles the number of bits of precision in each iteration. Algorithm: float sqrt(float x) root = intial guess

[algogeeks] Re: which is better?

2011-09-22 Thread Gene
No modern compiler will see these as different. Use the one you find prettiest. On Sep 22, 8:54 am, Sahil Garg garg.sahi...@gmail.com wrote: n=n+1 n++ ++n which of the three is better ?? Sahil Garg Computer Engg. DCE -- You received this message because you are subscribed to the

[algogeeks] Re: tree to list

2011-09-21 Thread Gene
#include stdio.h typedef struct node_s { int data; struct node_s *left, *right; } NODE; // Convert BST to a sorted list connected by -right pointers. NODE *to_list(NODE *tree, NODE *tail) { if (tree == NULL) return tail; tree-right = to_list(tree-right, tail); return to_list(tree-left,

[algogeeks] Re: C Puzzle

2011-09-17 Thread Gene
This is not a C puzzle. It depends on operating system. On Sep 17, 3:46 pm, teja bala pawanjalsa.t...@gmail.com wrote:  you have to print the list of all the files in a directory and all its sub directories? -- You received this message because you are subscribed to the Google Groups

[algogeeks] Re: Question -- plz answer

2011-09-16 Thread Gene
. Any anybody see it? Gene On Sep 10, 2:42 pm, Dave dave_and_da...@juno.com wrote: @Ishan: Here is the algorithm: If L = C, then     cup1 = L     cup2 = cup3 = cup4 = cup5 = cup6 = overflow = 0 else if L 3*C, then     cup1 = C     cup2 = cup3 = (L-C)/2     cup4 = cup5 = cup6 = overflow = 0

[algogeeks] Re: Question -- plz answer

2011-09-16 Thread Gene
My guess is that the and so on... means we should be able to solve this assuming the pyramid is as high as it needs to be in order not to overflow. With this the problem gets more interesting. I worked it out a bit farther: L/C --- Filled cups 1 --- 1 3 --- 2,3 5 --- 5 7 --- 4-6 8 1/3 --- 8,9

[algogeeks] Re: Question -- plz answer

2011-09-16 Thread Gene
Sorry. Small mistake. First test should have been W(n,k) = (k 1 || k n) ? 0 : This is fixed below. On Sep 16, 4:48 am, Gene gene.ress...@gmail.com wrote: My guess is that the and so on... means we should be able to solve this assuming the pyramid is as high as it needs to be in order

[algogeeks] Re: Easy Dp problem

2011-09-16 Thread Gene
I'll do the 5th example. A proper bracket expression of size n has n ['s and n ]'s and every prefix has no more ]'s than ['s. Test case 5 is n = 4 k = 2, so the possible bracket expressions are [][][][] * [][][[]] [][[]][] [][[][]] [][[[]]] [[]][][] * [[]][[]] [[][]][] [[][][]] [[][[]]]

[algogeeks] Re: Easy Dp problem

2011-09-16 Thread Gene
is going out of stack.Could someone please help me code this grammar? On Fri, Sep 16, 2011 at 7:11 PM, mc2 . qlearn...@gmail.com wrote: thanks a lot gene. :) On Fri, Sep 16, 2011 at 7:00 PM, Gene gene.ress...@gmail.com wrote: I'll do the 5th example.  A proper bracket expression of size n has

[algogeeks] Re: algorithm problem

2011-09-16 Thread Gene
All possible subsets of 10 elements is B(100,10), which is over 17 trillion. Not a great algorithm. You can do this by constructing sets S_0, S_1, S_2, ... S_10, S_11 of stations accessible from the start in 0,1,2,...10, 11 hops. The 11th is from the final station to the destination. It's simple

[algogeeks] Re: Exchanging bit values in a number

2011-09-14 Thread Gene
My solution just tests bit i and either sets or clears bit j based on the result. Then it does the same testing bit j and setting or clearing bit i. There are many other possibilities. It would be slick if C shift operators accepted negative shift values. But they don't. Instead you could

[algogeeks] Re: Exchanging bit values in a number

2011-09-14 Thread Gene
On Sep 14, 10:27 pm, Gene gene.ress...@gmail.com wrote: My solution just tests bit i and either sets or clears bit j based on the result.  Then it does the same testing bit j and setting or clearing bit i. There are many other possibilities.  It would be slick if C shift operators accepted

[algogeeks] Re: unique no. problem

2011-09-13 Thread Gene
Here's a way: The base 2 xor operator has an obvious extension to base 3 such that for all integers N, N ^ N ^ N = 0, just like the normal xor has N ^ N = 0. This base 3 operator a^b just adds corresponding digit pairs of a and b mod 3 to get the digits of the result. So the algorithm is to

[algogeeks] Re: Exchanging bit values in a number

2011-09-13 Thread Gene
// One of several ways in C: unsigned swap_bits(unsigned x, int i, int j) { r = x; if (x (1u i)) r |= (1u j); else r = ~(1u j); if (x (1u j)) r |= (1u i); else r = ~(1u i); return r; } On Sep 13, 2:50 pm, kumar raja rajkumar.cs...@gmail.com wrote: Suppose a number 'n' is given  

[algogeeks] Re: informatica interview question

2011-09-09 Thread Gene
1. True and True, though the second depends somewhat on features supported by the language you are using. Languages like ML (or OCAML) and Scheme are designed to support this. 2. You need somewhere to store state (lambda parameters at the lowest level). The stack is one mechanism. There are

[algogeeks] Re: Element in Array Repeated Even Number of Times

2011-09-09 Thread Gene
It can also be done in O(n) time and space with this. The XOR solution of bittusrk is interesting, too. The only advantage of this one is that it will work for any kind of object, not just numbers. Let S be the empty set for all elements E if E is in S, remove it else add it end; for all

[algogeeks] Re: activation record

2011-09-04 Thread Gene
and garbage-collected only after the last reference to them disappears, which may be not until the program terminates. Languages where this is true include -- lisp, ML, F#, javascript, perl, ruby, and quite a few others. Gene On Sep 2, 11:36 pm, bharatkumar bagana bagana.bharatku...@gmail.com wrote

[algogeeks] Re: Static variable memory location

2011-09-02 Thread Gene
The first sentence is incorrect for any compiler I've ever seen, and that's a bunch. As has been said, the C standard doesnt' say where _any_ variables live. So you can only ask the question with respect to certain compiler. On Sep 2, 1:57 am, aditya kumar aditya.kumar130...@gmail.com wrote:

[algogeeks] Re: Hexadecimal to Decimal

2011-09-01 Thread Gene
The language does give it tyou in sscanf, but sscanf is a pretty big function and in some environments, like small embedded ones, you don't get the luxury of using a big block of code to do a small thing. unsigned hex_to_unsigned(char *p) { unsigned val = 0; while (*p != '\0') { char c =

[algogeeks] Re: graph

2011-08-31 Thread Gene
for the cycles to be disjoint (2 separate SCCs), you are sharing 2 vertices and 1 edge, so the totals are 8 and 9. Gene On Aug 31, 11:16 am, MAC macatad...@gmail.com wrote: Q  The question asked in interview of a startup : suppose you have a graph as shown bellow : please see the attachment . The red

[algogeeks] Re: microsoft interview

2011-08-31 Thread Gene
You can use the first row and column as a scratchpad to keep track of which rows and columns need to be 1. Make one pass over the matrix to put 1's in the scratchpad locations. Then make a second pass checking the scratchpad to see of the square needs to be flipped to a 1. To make this

[algogeeks] Re: finding duplicates

2011-08-31 Thread Gene
Sorting is fine but destroys the input, which often hurts, especially in version 2. Unless you use fancy probing techniques, number of comparisons is O(n). If you're not sorting, then you need a set data structure of some form. If the numbers are small integers, an array of bits is good. Set

[algogeeks] Re: compiler

2011-08-05 Thread Gene
the current activation of the current procedure is popped. The only compilers I've ever seen allocate temporaries on a heap are for functional languages that use no stack at all. Appel's ML compiler is one I can remember off hand. Gene On Aug 5, 1:36 am, krishna meena krishna.meena...@gmail.com

[algogeeks] Re: To reverse a linked list

2011-08-05 Thread Gene
It's easy if you think in terms of pop and push operations. Pop the first k elements off the head of the list and push them onto a new list. They're now in reverse order. All that's left is to connect the two lists. You can do this efficiently if you keep a pointer to the tail element. NODE

[algogeeks] Re: MS [Written Question]

2011-08-03 Thread Gene
Your solution to 1 works fine. I hope you get the job. But it needs O(N) additional storage for the stack. You can also do with constant additional storage. #include stdio.h int main(void) { #define N (sizeof a / sizeof a[0]) int a[] = {7, 9, 4, 8, 2}; int result[N], i, product; for (i = 0,

[algogeeks] Re: Reversing the order of words in String

2011-07-13 Thread Gene
..why don't just read it word by word ? . what's the problem in it ? btw...nice soln... On Wed, Jul 13, 2011 at 7:32 AM, Gene gene.ress...@gmail.com wrote: You can recognize a word W, recur to print the rest of the words in reverse, then print W: #include stdio.h #include string.h

[algogeeks] Re: Reversing the order of words in String

2011-07-13 Thread Gene
Perl to reverse words in stdin: print join(' ', reverse(split(/\s+/, ))) On Jul 7, 5:18 am, Vishal Thanki vishaltha...@gmail.com wrote: Off Topic: Sorry for the diversion, but I was just wondering how easy it has become to code in languages other than c. Here is the code i wrote for the

[algogeeks] Re: Reversing the order of words in String

2011-07-12 Thread Gene
You can recognize a word W, recur to print the rest of the words in reverse, then print W: #include stdio.h #include string.h void print_words_in_reverse(char *s) { char *e; while (isspace(*s)) s++; if (*s == '\0') return; e = s + 1; while (*e !isspace(*e)) e++;

[algogeeks] Re: Flatten a BST to produce inorder traversal

2011-07-04 Thread Gene
This is a problem of attribute evaluation. Pick the right attributes, and it's not hard. Note this code is not tested, but it ought to work fine. // return value is the last node visited in reverse order. // prev is the previous node in reverse order NODE *inorder_set(NODE *node, NODE *prev) {

[algogeeks] Re: array size problem

2011-07-03 Thread Gene
Why do bicycles have 2 wheels and tricycles 3? The designers made them that way. So you're probably asking why they were designed that way. C++ came after C. In general C++ seeks to de-emphasize use of the pre- processor because macro substitution is generally considered to make maintenance

[algogeeks] Re: 2 D array(dynamic allocation)

2011-07-02 Thread Gene
Unfortunately this invokes undefined behavior, so it may not work for all architectures and compilers. It relies on pointers to int having the same alignment as int. By far the best way to do this is use C99 features: double (*a)[n_cols] = calloc(n_rows, sizeof *a); If you don't have C99 and

[algogeeks] Re: Sort - Consecutive Array in O(n)

2011-07-02 Thread Gene
You can use a count sort, but you need an array to store the counts. The oppilas algorithm needs only constant extra storage. On Jun 30, 7:23 am, hary rathor harry.rat...@gmail.com wrote: can we not use count sort because of O(n) .? -- You received this message because you are subscribed to

[algogeeks] Re: Amazon Telephonic Interview Questions

2011-06-30 Thread Gene
For 1. you need an in-order traversal. During the visit check to see that each successive key is non-decreasing. For 2. you need a post order traversal. During the visit swap the left and right child pointers. Now you can look up the standard algorithms for these traversals. On Jun 30, 3:34 

[algogeeks] Re: Sort - Consecutive Array in O(n)

2011-06-29 Thread Gene
Your algorithm is good, but the first part doesn't help you because duplicates are allowed. Here is code that does what you say: #include stdio.h int main(void) { int a[] = { 6, 2, 4, 8, 7, 3, 5 }; int n = sizeof a / sizeof a[0]; int i, t, min, max, tmp; min = max = a[0]; for (i = 1;

[algogeeks] Re: Sort - Consecutive Array in O(n)

2011-06-29 Thread Gene
: Please read it again. Hashing would also help in the case of duplicates. On Wed, Jun 29, 2011 at 9:16 AM, Gene gene.ress...@gmail.com wrote: Your algorithm is good, but the first part doesn't help you because duplicates are allowed. Here is code that does what you say: #include stdio.h

[algogeeks] Re: Sort - Consecutive Array in O(n)

2011-06-24 Thread Gene
Nice idea, but unfortunately doesn't work. The XOR only contains parity information. So just pick two values in the range and a low order bit where they're different. Then swap the bits. 2 xor 3 xor 4 xor 5 = 0 Pick 3 and 4 and swap the lsb, which gives 2 and 5. So we have 2 xor 2 xor 5 xor 5

[algogeeks] Re: BST

2011-06-19 Thread Gene
If you are allowed an extra integer per node, then you can maintain in each node a count of the number of nodes in the subtree rooted at that node. This can be maintained at no additional asymptotic cost in the insert, delete, and balance operations (if you're balancing). With these counts in

[algogeeks] Re: Reverse the bits.

2011-06-19 Thread Gene
To do it in O(1) for N bits, you need a table lookup. But for 32 bits, the table is 16 Gb. A compromise is to build a table of 256 entries to reverse the bits in a byte (it's easy to write a program to do this). Then the result is something like unsigned reverse_bits(unsigned x) { static

[algogeeks] Re: How to use asm in spoj

2011-06-17 Thread Gene
Spoj uses -O2 -fomit-frame-pointer when it compiles. Could that be it? Maybe the %1 and %2 don't work with this option. Just a guess... -- You received this message because you are subscribed to the Google Groups Algorithm Geeks group. To view this discussion on the web visit

[algogeeks] Re: Mathematical Induction

2011-06-12 Thread Gene
Suppose you want to prove that you can climb all the way to the top of a ladder. One way to do this is in two parts: First prove you can stand on the bottom step. Call this step 1 and number the rest of the steps 2,3,..N upward to the top of the ladder. The second part is to prove that if

[algogeeks] Re: GOOGLE Q

2011-05-17 Thread Gene
Sort the characters in the string. Go through the dictionary sorting the characters in each word in turn. Print the words whose sorted versions match the sorted string. You can quickly print all equivalence classes of anagrams in the dictionary by hashing with the sorted strings as keys. It

[algogeeks] Re: suggest data structure

2011-03-25 Thread Gene
A knight can move 8 possible ways, so you need 3 bits to encode a movement. To convert these 3 bits into relative motion on a board, define integer board coordinates, then use a lookup table of (delta x, delta y) pairs to store the coordinate change of each possible move. All the elements of

[algogeeks] Re: virtual memory

2011-03-24 Thread Gene
As rahul rai said, you can ensure that two processes run independently; one can't affect the other's memory. Similarly you can ensure the running process can't access memory outside its allocated space. You can arrange for two or more processes to share pages. You can map memory space to

[algogeeks] Re: random number generator

2011-03-19 Thread Gene
On Saturday, March 19, 2011 6:07:44 AM UTC-4, cegprakash wrote: @gene: can u give the function for unfair_coin_toss so that i can understand what u are doing in fair_coin_toss On Mar 19, 9:54 am, Gene gene.r...@gmail.com wrote: On Friday, March 18, 2011 1:47:45 PM UTC-4, Gene wrote

[algogeeks] Re: random number generator

2011-03-18 Thread Gene
On Mar 17, 10:24 am, saurabh agrawal saurabh...@gmail.com wrote: Given a  function which returns true 60% time and false 40% time. Using this function you have to write a function which returns true 50% of the time. If we call the function N times, then the probability that we'll have K true

[algogeeks] Re: random number generator

2011-03-18 Thread Gene
On Friday, March 18, 2011 1:47:45 PM UTC-4, Gene wrote: On Mar 17, 10:24 am, saurabh agrawal saura...@gmail.com wrote: Given a function which returns true 60% time and false 40% time. Using this function you have to write a function which returns true 50% of the time. If we

[algogeeks] Re: Link list Problem

2011-03-16 Thread Gene
I think Wirth mentions this idea in Algorithms + Data Structures = Programs, which dates from the 70's. Of course this technique is useless if other pointers to the deleted note can exist. -- You received this message because you are subscribed to the Google Groups Algorithm Geeks

Re: [algogeeks] Application of Binomial Heaps

2011-03-06 Thread Gene
Prim's algorithm for minimum spanning trees. -- You received this message because you are subscribed to the Google Groups Algorithm Geeks group. To post to this group, send email to algogeeks@googlegroups.com. To unsubscribe from this group, send email to

[algogeeks] Re: Antipodal points

2011-02-24 Thread Gene
Dave's solution is best if numerical error is possible. If the points are precise, you can also do it in linear time. Just hash the points on abs(y/x). -- You received this message because you are subscribed to the Google Groups Algorithm Geeks group. To post to this group, send email to

Re: [algogeeks] extendible hashing

2011-02-13 Thread Gene
Two or three versions ago at least the documents had very nice examples, and there were examples in the source distribution. I have a hard time believing they've been removed. -- You received this message because you are subscribed to the Google Groups Algorithm Geeks group. To post to this

Re: [algogeeks] extendible hashing

2011-02-11 Thread Gene
This is a very lame question. Type Berkeley DB into Google. The 3rd listing is Berkeley DB downloads at Oracle: http://www.oracle.com/technetwork/database/berkeleydb/downloads/index.html Wouldn't it have been easier to do this than to write back to the group? It certainly would have been

Re: [algogeeks] extendible hashing

2011-02-10 Thread Gene
If I remember correctly Berkeley DB uses an extensible hashing system or did at one time. This is not part of the OS API, but rather a library that runs in user space. I've used the B-tree parts of Berkeley DB, though never the hash table. Performance and reliability have been extremely

<    1   2   3   4   5   >