Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

May 16, 2011

Full Question:
What is the C-language command for opening a connection with a foreign host over the internet?

Intuitively, there's no such direct command built into the programming language. Sockets need to be used but they are platform dependent.

Actually, there's no single C command or function to open a connection to a foreign host.

To do this, first, you need a socket that is provided by the socket() function. Then, you need to call connect() to establish the connection with the host. However, that requires that all host names have been resolved, so you may have had to call gethostbyname() or similar, to turn a hostname into an IP address.

Simple Example codes here. It is a TCP client implementation.
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main(){
        int sock, bytes_recieved;  
        char send_data[1024],recv_data[1024];
        struct hostent *host;
        struct sockaddr_in server_addr;  

        host = gethostbyname("127.0.0.1");

        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            printf("Socket Error");
            exit(1);
        }

        server_addr.sin_family = AF_INET;     
        server_addr.sin_port = htons(5000);   
        server_addr.sin_addr = *((struct in_addr *)host->h_addr);
        bzero(&(server_addr.sin_zero),8); 

        if (connect(sock, (struct sockaddr *)&server_addr,
                    sizeof(struct sockaddr)) == -1) {
            perror("Connect");
            exit(1);
        }

        while(1) {
          bytes_recieved=recv(sock,recv_data,1024,0);
          recv_data[bytes_recieved] = '\0';
 
          if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0){
             close(sock);
             break;
          }
          else
             printf("\nRecieved data = %s " , recv_data);
           
          printf("\nSEND (q or Q to quit) : ");
          gets(send_data);
           
          if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0)
           send(sock,send_data,strlen(send_data), 0); 
          else {
           send(sock,send_data,strlen(send_data), 0);   
           close(sock);
           break;
          }
        }   
        return 0;
}

April 29, 2011

Full Question:
Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5. The distribution between each of the numbers must be uniform.

The given function, let's call rand(5), generates a random number between 1 to 5 in uniform manner. So, we can generate a random number from 1 to 5n in also uniform manner. For example, 25*(rand(5)-1) + rand(5) generates a random number between 1 to 125, and 5*(rand(5)-1)+rand(5) generates a random number between 1 to 25 uniformly. From this derivation, we can get a random number between 1 to 7 under uniform distribution.

public static void main(String args[]) {
Random g = new Random(1929304);
int N = 100000000;
int num[] = {0, 0, 0, 0, 0, 0, 0};

for(int i=0; i<N; i++ ) {
int j;
do {
j = 5*g.nextInt(5) + (g.nextInt(5)+1); // uniform between 1 and 25
} while(j>21); // uniform between 1 and 21
num[(j%7)]++; // uniform between 1 and 7 (0 and 6)
}

for(int i=0; i< 7; i++ )
System.out.println(i+1 + ": " + num[i]);
}

Following box shows results after a hundred million times try.
1: 14289981
2: 14288932
3: 14286841
4: 14284775
5: 14283995
6: 14285958
7: 14279518

April 28, 2011

Full Question:
There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. Solve it without division operator and in O(n).

Simply, it can be solved in O(n2) time, by using double loop. For example,
int[] multiplicationExceptMe() {
int ret[N] = {1,};
for (int i=0; i < N; i++)
 for (int j=0; j < N; j++) {
  if(i != j)
     ret[i] *= A[j]
 }
return ret;
}

But, we have to solve in in O(n). The idea is to do multiply in both side (i.e. from start to end and from end to start) in each loop.

public static void main(String args[]) {
int input[] = {1, 2, 3, 4, 5};
int ret[] = {1,1,1,1,1};
int n = input.length, left=1, right=1;

for(int i=0; i <n; i++) {
ret[i] = ret[i]*left;  
ret[n-1-i] = ret[n-1-i]*right;
//after multiplication, set new left and right value
left *= input[i];
right *= input[n-i-1];
}

for (int i =0; i<n; i++)
System.out.print(ret[i] +"\t");
}

Obviously, it's O(n) time complexity.

April 25, 2011

Find All Permutations of the Letters in a Particular String

Permutations of string 'ABC' are:
ABC, ACB, BAC, BCA, CAB, CBA.

Taking the backtracking strategy, here is a solution. The program prints all permutation of the given string .It's assumed that NO same character in the string. So, the given string has same character, some redundant results are shown. You can avoid it by maintaining array to save permutations.

public static void main(String args[]) {
char[] input = {'A', 'B', 'C'};
permute(input, 0, input.length-1);
}

public static void swap(char[] str, int i, int j) {
char temp;

temp = str[j];
str[j] = str[i];
str[i] = temp;
}

public static void permute(char[] str, int start, int end) {
if (start == end)
System.out.println(str);
else {
for (int i=start; i<=end; i++) {
swap(str, start, i);
permute(str, start+1, end);
swap(str, start, i);
}
}
}
Question:
  • There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. Solve it without division operator and in O(n).
It is from Google and Microsoft interview Question List. If you want to be hired, see the code. If we use divide operator (/), it's easy to solve in O(n). Multiply of all elements once, and divide into the value of A[i]. And we can implement division function without divide operator, but it may be not way to go. 

Here is a solution. Just define two variable, left and right to store multiplication results of left of A[i] and right of A[i]. We need just one loop of n and hence it's in O(n).


public static void main(String args[]) {
int input[] = {1, 2, 3, 4, 5};
int ret[] = {1,1,1,1,1};
int n = input.length, left=1, right=1;

for(int i=0; i <n; i++) {
ret[i] = ret[i]*left;
ret[n-1-i] = ret[n-1-i]*right;
left *= input[i];
right *= input[n-i-1];
}

for (int i =0; i<n; i++)
System.out.print(ret[i] +"\t");
}

April 24, 2011

Implementing Division without Divide Operator

Implementing dividing operation is a popular interview question in programmer and software engineering job. When you're asked, of course you must not use divide (/) operator obviously.

Since Multiplication (Devision) is derived from Addition (Subtraction) mathematically, the dividing operation can be implemented using subtraction.

Following function implement the dividing operation. there're two way- using multiplication and subtraction. However, you should use subtraction because multiplication has same property of division. You know devision can be converted to multiplication, and vise versa.



public int divide(int numerator, int denominator) {
int result = 0;

if (numerator == 0)
return numerator;
else if (denominator == 0) {
System.out.println("Error: Divided by 0");
return ERROR;// define constant for ERROR Message
else {
int sign = numerator*denominator > 0? 1:-1;
if(numerator < 0)
numerator *= -1;
if(denominator < 0)
denominator *= -1;
/* using multiplication
while(true) {
result++;
if(result*denominator > numerator) {
result--;
break;
}
}
*/
//using subtraction
while (true) {
numerator = numerator - denominator;
if(numerator>=0)
result++;
else
break;
}

return (sign*result);
}
}

Reverse String Funcion in C/Java Code

To Reverse String is not difficult, but it's one of the most popular question for interviewing in programmer job. Simple is the best, but in this case recursive function can be a better answer and efficient solution.

First method, swap first and last character repeatedly. Almost same in C and Java programming.
public String reverseString(char[] str) {
char temp;
int i, j;
for(i=0, j=str.length-1; i<=j; i++, j--){
temp = str[i];
str[i] = str[j];
str[j] = temp;
}

return new String(str);
}


Second, a recursive function can be defined. call the function within the function with Substring of input string. In Java:

public String reverseStringByRecursion(String str) {
if(str.length() == 1)
return str;
return reverseStringByRecursion(str.substring(1))
+ str.substring(0,1);
}

For C(++):
(just print character or you need global variable.)

     void StrReverse4(char *str)
     {
         if(*str)
         {
             StrReverse4(str+1);
             putchar(*str);
         } 
     }