Thursday, May 20, 2010

Oracle Trouble shooting

 When I am trying to sign in to Oracle 11g  in windows xp , I am getting the error  'ORA-12560: TNS:protocol adapter error'

Solution:
Try1:
set local=databasename
For example, if name of database is orcl, command will be
C:\ set local = ORCL

Then log in to sqlplus 
C:\ sqlplus / as sysdba
___________________________________________________________________________________
Try 2

If try1 does not work,

In command prompt do the following:
C:\ set ORACLE_SID =  databasename
 Important:  The database name has to be in uppercase letters. 

For example, if name of database is orcl, command will be
C:\ set ORACLE_SID = ORCL

Then log in to sqlplus 
C:\ sqlplus / as sysdba

SQL*Plus: Release 11.1.0.6.0 - Production on Sun Jun 20 00:06:58 2010


Copyright (c) 1982, 2007, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

Now you are connected to the database.
____________________________________________________________________________________

Friday, April 16, 2010

Turing Machine ( True or False )

1. A Universal Turing Machine can compute anything that any other Turing Machine could possibly compute.
True

2.The Turing Test is a test of whether a problem can be solved by a Turing Machine.
True

3. Every acceptable language is also decidable.
False

4. Decidability is a special case of decidability
True

5. Regular languages are decidable
True

6. Context free languages are not decidable
False

Saturday, March 13, 2010

Interesting Algorithms

1. Let A be a list of n elements in non-decreasing order where some elements are replicated.
The problem is to find the element that appear most frequently. Give an O(k log n) time
algorithm to solve the problem where k denotes the number of distinct elements in A.


2. You are given a list A = [a1; a2; - - - ; an] of n distinct numbers in an arbitrary order.
You are supposed to find two numbers i and j from A such that (i) i < j, (ii) j > i, and
(iii) satisfying (i) and (ii), aj - ai is minimum over all possible such pairs. Give an O(n) time
algorithm.


3. A carpenter has a piece of wood of a certain length that must be cut at positions a1, a2 ..., an where ai is the distance from the left end of the original piece of wood. Notice that after making the first cut, the carpenter now has two pieces of wood; after making the second cut, the carpenter has three pieces of wood, etc. Assume that the cost of making a cut in a piece of wood of length l is equal to l, and is the same no matter which position in that piece of wood is being cut. Let L be the length of the original piece of wood.
Derive the recurrence relation which could be used to design a recursive algorithm to find the minimum total cost for making all the cuts.


4. Describe a Θ(n lg n)-time algorithm, that given a set of n integers and another
integer x, determines whether or not there exist two elements in S whose sum is exactly x. Write
pseudocode.
Hint: Sort using mergesort and iterate once after sorting. Θ(n lg n+n) = Θ(n lg n)


5. Suppose you are given an array A containing n sorted elements followed by lgn unsorted elements. Thus, entire array contains N = n+lgn elements. Can the entire array sorted in O(n) time.

6.  You are given an array of n numbers. Write an algorithm with O(n)=nlogn  that returns the number of distinct numbers in the array.   

Friday, March 12, 2010

Minimum Spanning Tree - True or False

1. In an undirected graph, the shortest path between two nodes lies on some minimum spanning
tree.
A: False.

2. If the edges in a graph have different weights, then the minimum spanning tree is unique.
A: True.

3. If the edge with maximum weight belongs to a cycle, then there exists some MST that
does not contain this edge.
A: True

4. Adding a constant to every edge weight does not change the minimum spanning tree.
A: True

5. There can be more than one minimum spanning trees if the weight of the edges are all distinct
A.False

6. If all weights are the same, every spanning tree is minimum.
A. True

7. Greedy algorithm runs in exponential time
A. False

8. A minimum spanning tree should contain all edges of the graph
A. False

9. A minimum spanning tree should contain all vertices of the graph
A.True

10.Adding an edge to a spanning tree of a graph G always creates a cycle.
A.False

11. Adding an edge to a spanning tree connecting two existing vertices of a graph G always creates a cycle.
A. True

12. For any cycle in a graph, the cheapest edge in the cycle is in a minimum spanning tree.
A. False

Big O, Big Omega, Big Theta

For each of the following pairs of functions f(n) and g(n), state whether f(n) =
O(g(n)), f(n) = ­Ω(g(n)), or f(n) = Θ(g(n)), or none of the above:


(a) f(n) = n2 + 3n + 4, g(n) = 6n + 7
Sol: f(n) = ­Ω(g(n).


(b) f(n) = n √n , g(n) = n2 - n
Sol: f(n) = O(g(n)).


(c) f(n) = 2**n - n**2, g(n) = n**4 + n**2
Sol: f(n) = ­­Ω(g(n).


(d) Assume you have five algorithms with the running times
listed below (these are the exact running times). How much slower do each of these
algorithms get when you double the input size
i) n2
Sol: 4T(n)

ii) n3
Sol: 8T(n)

iii) 100n2
Sol: 4T(n)

iv) nlgn
Sol: 2n(lg2n) = 2n(1+lgn) ~ 2n lgn
T(n) = 2T(n)

v) 2n
Sol:  [T(n)]


(e)  Write a big-O expression for 1+2+3+...+n?
Sol:  O(n2)


True or false:
(f) An algorithm with worst case time behavior of 3n takes at least 30 operations for every input of size n=10.
Sol : False


(g)  n! = O(nn)
Sol: True


(h) nO(1) = O(n2)
Sol: False.  O(1) can be any large constant .


(i) All of the following are true.
  • f(n) = O(f(n))
  • c * O(f(n)) = O(f(n)), if c is constant
  • O(f(n)) + O(f(n)) = O(f(n))
  • O(O(f(n))) = O(f(n))
  • O(f(n)) * O(g(n)) = O(f(n)g(n))
  • O(f(n)g(n)) = f(n) * O(g(n))

Wednesday, February 17, 2010

merge sort code in c++ to count number of comparisons

#include < iostream >
#include < stdio.h >

using namespace std;

int count = 0; //count of comparisons
int n = 0;
const int MAX_ITEMS = 100;
void merge(int values[], int leftFirst, int leftLast, int rightFirst, int rightLast);
void printarray( int a[], int n);
void mergesort(int a[], int start, int end){  //no significant comparisons are done during splitting
   
    if(start < end){
        int mid = (start+end)/2;   
        mergesort(a,start, mid);
        mergesort(a,mid+1,end);
        merge(a, start,mid, mid+1, end);
    }
}
void merge(int values[], int leftFirst, int leftLast, int rightFirst, int rightLast){
        int temparray[MAX_ITEMS];
        int index = leftFirst;
        int saveFirst = leftFirst;

        while((leftFirst <= leftLast)  && ( rightFirst <= rightLast)){//compare and select smallest from two subarrays

            if(values[leftFirst] < values[rightFirst]){
                temparray[index]  = values[leftFirst]; //smallest assigned to temp
                leftFirst++;
            }
            else
            {
                temparray[index]  = values[rightFirst];
                rightFirst++;
            }
            index++;
            count++;  //count of comaparisons done during merge. One comparison is done per iteration of while loop. 
        }
       
        while(leftFirst <= leftLast){ 

            temparray[index] = values[leftFirst];
            leftFirst++;
            index++;
           
        }
        while(rightFirst <= rightLast){
            temparray[index] = values[rightFirst];
            rightFirst++;
            index++;
           
        }
       
        for(index = saveFirst; index <= rightLast; index++)//copies from temp array to values array
            values[index] = temparray[index];
        printarray(values,n);
        cout << endl;

    }

void printarray( int a[], int n){
    for (int i=0; i < n; i++)
        cout << a[i] << "  ";
}

int main(){
   
    cout << "Enter number of  elements to be sorted : ";
    cin >>n;

    int a[MAX_ITEMS];
   
for (int i=0; i < n; i++){
        if(i==0)
            cout << "Enter the first element: ";
        else
            cout << "Enter the next element: ";
        cin >>     a[i];
    }
   
    int start = 0;
    int end = n-1;
      mergesort(a, start, end);
    printarray(a, n);

    cout << endl;
    cout  << "Number of comparisons : "<< count << endl;
}

Friday, February 12, 2010

systems programming (UNIX, C)

How to toggle lettercases.

struct termios info;
    int   rv = tcgetattr(0, &info);
    if(info.c_oflag & OLCUC)
            info.c_oflag &=  ~OLCUC;
    else
        info.c_oflag |= OLCUC;
    tcsetattr(0, TCSANOW, &info);

______________________________________________________________

How can we measure CPU time ( user + kernel) of a program in UNIX.

1. Use clock() system call to measure CPU time.
      The clock() function returns the  amount  of  CPU  time  (in
     microseconds)  used  since  the first call to clock() in the
     calling process.
      example
          time_t time = clock();
          int i=0;
          while(i<10000){
              printf("%d\n", i);
              i++;
          }
         time = clock();
         printf( "\nCPU time : %ld\n" , time);// prints CPU time  taken  to print numbers from 0 to 999


2.  Use time command
     example
     bash$     time gcc file.c
3.  Use getitimer and setitimer with ITIMER_REALPROF

Friday, February 5, 2010

IMac

How can I access(SSH) a remote machine from my iMac.

Access the terminal from application -> Utilities -> Terminal
On prompt type ssh -l uername host 
On prompt for password ,  type pasword

How can I switch between two terminal windows in iMac
command- ~

Wednesday, February 3, 2010

c programmin errors, warnings and solutions

Warnings:
  1.  warning: incompatible implicit declaration of built-in function 'malloc'
    solution - add #include < stdlib.h> 
  2.  warning: incompatible implicit declaration of built-in function 'strlen'
    solution-   add #include < string.h>

Friday, January 8, 2010

C programming

Code to deep copy a string in C

char*  deepcopy(char* str1){
        char *copy  = malloc (strlen(str1));
        sprintf(copy, str1);
        return copy;
}




1. When I compile, I am getting the error: 'EOF' undeclared (first use in this function)

Solution: #include < stdio.h >

2. In visual studio output window just flashes and disappears. What can I do to make it stay.

Run the program using Ctrl F5 instead of just F5


3. When I compile a simple program I am getting the error "Cannot open include file: 'iostream.h': No such file or directory". How can I fix this.

Check if iostream is stored in C:\Program Files\Microsoft Visual Studio 8\VC\include folder. Sometimes it is stored just as iostream instead of iostream.h . If that is the case add #include < iostream> omitting .h

4.LINK : fatal error LNK1104: cannot open file 'C:\Documents and Settings/...............

Usual reason is that the same program is running and a terminal window is waiting for input.







Saturday, December 5, 2009

Comer (XINU) Algorithm Examples

1. Consider disk arm scheduling algorithms. Assume that the disk has 200 cylinders numbered 0...199. The request queue is 10, 15, 9, 20, 40, 2. How will the queue look like after adding 23 and 45.

Try to find two requests R1 and R2 such that the head will pass the new request on its way from R1 to R2. If there exists two requests like that squeeze the new request in between. If there exists no such requests add new request to the end of the queue

23 can be squeezed in between 20 and 40.
Queue is 10,15, 9, 20, 23, 40, 2

45 cannot be squeezed in since there is no Request(i) such that 45 is in between Request(i)and Request(i-1). So add 45 to the end of the queue.

Queue is updated to 10,15, 9, 20, 23, 40, 2, 45

2. Disk requests arrive in the order 26, 79, 96, 27, 8 . In what order will XINU algorithms service the requests above.

26
26,79 - added to the end
26,79,96 - added to the end
26, 27, 79, 96 - 27 is squeezed in.
26, 27, 79, 96, 8 - 8 is added in the end.

3. Disk requests arrive in the order 50, 100, 75, 25, 125 . In what order will XINU algorithms service the requests above.

50
50,100 - added to the end
50, 75, 100 - 75 is squeezed in
50, 75, 100, 25 -25 is added to the end, but this will force redirection
50, 75, 100, 25, 125 - added to the end

4. When is XINU better than LOOK.
Consider block numbers 50, 60,40,100

XINU : head movement = 10+ 20+60 = 90
LOOK : order of processing is 50, 60, 100, 40
head movement = 10+ 40+ 60 = 110
Here XINU is better than LOOK
Since XINU will force redirection after processing 60 to process 40 overall head movement is less than LOOK.

Sunday, November 29, 2009

shortest seek time first (SSTF) java source code

import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Math;



public class Main {


public static void main(String[] args) {


ArrayList list = new ArrayList();


BufferedReader dataIn = new BufferedReader(new
InputStreamReader( System.in) );


//read current head position
String w = "";
System.out.println("Position of head currently :");
try{
w = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
int head = Integer.parseInt(w);
int initialhead = head;


// Read service requests
while(true){
try{
System.out.println("Enter next service request.Enter z to end the requests.");
w = dataIn.readLine();

if(w.equals("z"))
break;
int temp = Integer.parseInt(w);
list.add(temp);
}catch( IOException e ){
System.out.println("Error!");
}

}


ArrayList service_order = new ArrayList();//adds requests in order of the service

int number_of_orders = list.size();
for(int i=0; i &ltnumber_of_orders;i++){
Iterator it = list.iterator();
int min = 0;
int temp=0;
int min_distance=200;

while(it.hasNext()){
temp = (Integer)it.next();
int distance = Math.abs(head-temp);
System.out.println(head +" "+ temp+" " + distance );

if(distance < min_distance){
min = temp;
min_distance = distance;
}

}

list.remove((Integer)min);
head = min;
System.out.println(" Next request "+ min);
service_order.add(min);


}

Iterator min_it = service_order.iterator();

System.out.print("Service Order: ");

while(min_it.hasNext()){
System.out.print(min_it.next()+" ");
}
int total_head_movement=0;
min_it = service_order.iterator();
total_head_movement = Math.abs(initialhead - (Integer)service_order.get(0));
for(int i =1;i < service_order.size();i++){
total_head_movement += Math.abs((Integer)service_order.get(i) - (Integer)service_order.get(i-1));
}
System.out.println();

System.out.println("Total head movement: "+ total_head_movement);
}

}




Deepcopy of a string in c

Tuesday, November 3, 2009

Process Synchronization Examples

The following Java code samples describe two Lock classes with two methods
each: acquire() and release(). You can assume that the application calls lock.acquire()
before entering a critical section and lock.release() after exiting the critical section. For the
implementations that require a tid (i.e., thread id), you can assume that the tid of each thread is
either 0 or 1.

class LockA {
private int turn = 0;
public void acquire(int tid) {
while (turn == (1 - tid));
}
public void release(int tid) {
turn = (1 - tid);
}
}
class LockB {
public void acquire() {
disableInterrupts();
}
public void release() {
enableInterrupts();
}
}

For each lock, answer the following three questions. Be sure that your answers clearly indicate
whether you are referring to LockA or LockB.
(a) Does the code guarantee mutual exclusion? (Simply answer yes or no)
(b) Does the code guarantee progress? (Simply answer yes or no)
(c) List all other limitations that exist for each implementation. Issues you might consider
include (but are not limited to) the following: generality, efficiency, and fairness. (Note: You
can skip this part of the quetion when the implementation fails to provide mutual exclusion
or progress.)

Answer
LockA (a) Yes, guarantees mutual exclusion; only the thread with tid matching turn is able to
acquire the lock. (b) No, does not guarantee progress; if thread 0 never tries to acquire the lock
(it is executing other code), thread 1 will not be able to acquire the lock. (c) Limitations (Not
required): Only works with two processes, uses busy waiting.
LockB (a) Guarantees mutual exclusion on a uniprocessor, but not on a multiprocessor. On a
uniprocessor, once the timer interrupt is disabled, the scheduler won’t be able to switch to another
process (assuming the scheduled process doesn’t voluntarily relinquish the CPU). However, on
a multiprocessor, it is possible for the other CPU to be running a process that also acquires the
lock. (b) Yes, guarantees progress; once a process is scheduled, it is able to acquire the lock without
incident. (c) Limitations: Only works on uniprocessors; allows user processes to disable interrupts
for an arbitrary long period; cannot service other important interrupts during critical section (e.g.,
I/O); cannot schedule any other processes when lock is held, even those not contending for the
lock.
Also answer the following general question: Locks are often implemented by maintaining a list of processes (or threads) that are waiting to acquire the lock. What are all of the advantages of this approach (compared to a correct implementation of a lock that does not use a list)?
fairness and efficiency. Fairness comes from the fact that the queue can provide the lock to the
processes in the order they request it. Efficiency comes from the elimination of the spin lock, and
reliance on a notification mechanism to wake-up a process.

_______________________________________________________________

Suppose two processes compete for access to a critical section using simple spin locks. Prior to entering the critical section, the process executes the following:
while (TAS(t)); and after exiting the critical section it executes t=1.
(a) Suppose a priority scheduler where high priority processes always execute before any
lower priority processes. Can the described scheme lead to deadlock? If no, why not. If yes,
describe a case.
Yes, deadlock is possible. If a low priority process acquires the lock. Then a high priority
process starts, gets the processor and requests the lock. The high priority process will keep
the processor, spinning on the lock that the low priority process is holding. Because the low
priority process cannot get the processor, it cannot release the lock, and we have a deadlock
scenario.
(b) Suppose a round robin scheduler. Can the described scheme lead to deadlock? If no, why not. If yes, describe a case.
No, deadlock is not possible. A round robin, preemptive scheduler will alternate among
processes, so every process will have a chance to execute, and eventually the holding process
will release the lock.
_______________________________________________________________
Fix the following code to avoid the possible deadlock:
acquire(L1)
acquire(L2)
release(L2)
release(L1)
acquire(L2)
acquire(L1)
release(L1)
release(L2)
Answer
You could have changed this many ways. One possibility is to remove circular wait and
make both processes acquire the resources in the same order. Another possibility is to remove
hold-and-wait and have the processes release the first resource before they acquire another.
Although this changes the semantics of the program, I accepted it as a solution.
----------------------------------------------------------------------------------------------------------
Suppose a program has three threads Thread1, Thread2, and Thread3, and a
shared counter, count, as shown below:
int count = 10;
Semaphore Lock = 1; // initial value is 1
Thread1(...)
{
// do something
Lock.Wait();
count++;
Lock.Signal();
}
Thread2(...)
{
// do something
Lock.Wait();
count−−;
Lock.Signal();
}
Thread3(...)
{
// do something
Lock.Wait();
printf(‘‘$d’’, count);
Lock.Signal();
}
(a) What are the possible outputs of this program?

9, 10, 11
_______________________________________________________________________________________________

Consider a system with two preemptively scheduled threads. One thread executes the WriteA function
shown below. The other executes the WriteB function, also shown below. Both functions use kprintf
to produce console output. The random function called by WriteA returns a randomly-generated nonnegative
integer. WriteA and WriteB are synchronized using two semaphores, Sa and Sb. The intial
value of both semaphores is zero. Assume that the individual calls to kprintf are atomic.
WriteA() {
unsigned int n,i;
while(1) {
n = random();
for(i=0;i<n;i++){
kprintf(‘‘A’’);
}
for(i=0;i<n;i++) {
V(Sb);
}
for(i=0;i<n;i++) {
P(Sa);
}
}
WriteB() {
while(1) {
P(Sb);
kprintf(‘‘B’’);
V(Sa);
}
}

a.
Consider the following 10-character console output prefixes. (Each prefix shows the first 10 characters
printed to the console.) Which of these prefixes could possibly be generated by the two
threads running in this system? Write “YES” next to the output prefix if it could be generated,
otherwise write “NO”.
• ABABABABAB YES
• BABABABABA NO
• AAAAAAAAAA YES
• AAABABABAB NO
• AAABBBBAAB NO
• AAAAAABBBB YES
• AAABBBAABB YES
• BBBBBAAAAB NO
b.
Suppose that the initial value of semaphore Sb is 1, rather than 0. Show a 10-character console
output prefix that could be generated in that case, and that could not be generated if the initial
value of Sb were 0.
Some examples:
• BABABABABA
• ABABBABABAB
• AAABBBABABB
__________________________________________________________________

Below is an attempted solution for producer- consumer problem. What problems can arise using this solution?
Buffer size = N
int count = 0;
consumer:
while(true){
if(count==0)
sleep( );
//remove from buffer
count--;
if(count ==N-1)
wakeup(producer);
consume(item)
}

producer:
while(true){
produce(item);
if(count==N)
sleep( );
//produce into buffer
count++;
if(count ==1)
wakeup(consumer);
consume(item)
}

Answer:
  • Consumer checks count==0
  • before going to sleep consumer is preempted
  • Producer increments count to 1
  • producer wakes up consumer.
  • since consumer is not sleeping yet, wakeup call is lost.
  • Producer fills the buffers until count == N and goes to sleep
  • Both processes are deadlocked.


___________________________________________________________________________________

Consider three concurrently executing threads in the same process using two semaphores
s1 and s2. Assume s1 has been initialized to 1, while s2 has been initialized to 0.
What are the possible values of the global variable x, initialized to 0, after all three threads have terminated?


/* thread A */
P(&s2);
P(&s1);
x = x*2;
V(&s1);

/* thread B */
P(&s1);
x = x*x;
V(&s1);

/* thread C */
P(&s1);
x = x+3;
V(&s2);
V(&s1);

The possible sequences are B,C,A (x = 6) or C,A,B (x = 36) or C,B,A (x = 18).
________________________________________________________________
We explore the so-called barbershop problem. A barbershop consists of a n waiting chairs
and the barber chair. If there are no customers, the barber waits. If a customer enters,
and all the waiting chairs are occupied, then the customer leaves the shop. If the barber
is busy, but waiting chairs are available, then the customer sits in one of the free chairs.
Here is the skeleton of the code, without synchronization.
extern int N; /* initialized elsewhere to value > 0 */
int customers = 0;
void* customer() {
if (customers > N) {
return NULL;
}
customers += 1;
getHairCut();
customers -= 1;
return NULL;
}
void* barber() {
while(1) {
cutHair();
}
}
13
For the solution, we use three binary semaphores:
• mutex to control access to the global variable customers.
• customer to signal a customer is in the shop.
• barber to signal the barber is busy.
1. (5 points) Indicate the initial values for the three semaphores.
• mutex
• customer
• barber
2. (15 points) Complete the code above filling in as many copies of the following commands
as you need, but no other code.
P(&mutex);
V(&mutex);
P(&customer);
V(&customer);
P(&barber);
V(&barber);

Solution: Initial values are mutex = 1 (variable customers may
be accessed), customer = 0 (no customers) and barber = 0 (barber is not busy).
void* customer() {
P(&mutex);
if (customers > N) {
V(&mutex);
return NULL;
}
customers += 1;
V(&mutex);
V(&customer);
P(&barber);
getHairCut();
P(&mutex);
customers -= 1;
V(&mutex);
return NULL;
}
void* barber() {
while(1) {
P(&customer);
V(&barber);
cutHair();
}
}
________________________________________________________________


Tasks T1 and T2 share the integer variables X, Y initially set to
0.
Task T1 executes:      | and T2 executes:
|
X := 0;        | Y := 0;
if X > 0 then  |        while Y < 2 do
X := X + 1; |    X := X - 1;
Y := 2;        | Y := 1;

What are the possible values of X and Y when these tasks
terminate?


T1:1 X=0
T2:1 y=0
T2:2 x=-1
T1:3 Y=2
T2:2 Y=1 


X =-1; Y=1  -----CONSIDER ALL POSSIBILITIES LIKE THESE EXAMPLES


______________________________________________________________________________


Process P executes:
A1: X := 1;
A2: Y := 1;
A3: Z := 2;
and process Q executes:
B1: X := 2;
B2: Y := 2;
What are the possible resulting values for X, Y, and Z?
For example, after the execution sequence A1 A2 A3 B1 B2
we obtain [x=2,y=2,z=2].
B1 A1 B2 A2 A3[x=1, y=1,Z=2]
try all combinations


In the same conditions as above, what should you do if you want
to guaranty that X, Y, Z finish with value, respectively, 1,
2, and 2?
You can change the order of A1, A2, A3; or the order of B1, B2;
or use semaphores; or use spinlocks.
Answer:
semaphore sem =0;
P1:                P2
wait(sem)          x=2
x=1                signal(sem)
y=1                wait(sem)
signal(sem)        y=2
Z=2

In the same conditions as above, what should you do if you want
that X and Y have both value 1 or both value 2?


For both x=1 and y=1


semaphore sem =0;
P1:                P2:
wait(sem)                
x=1                x=2
y=1                y=2
Z=2               signal(sem)


______________________________________________________________________________
 
 
http://pages.cs.wisc.edu/~bart/537/quizzes/quiz1.html
 
______________________________________________________________________________ 

Monday, November 2, 2009

Pumping Lemma Examples

Steps to solve Pumping Lemma problems:
1. If the language is finite, it is regular , otherwise it might be non-regular.
2. Consider the given language to be regular
3. State pumping lemma
4. Choose a string w from language, choose smartly .
5. Partition it according to constraints of pumping lemma in a generic way
6. Choose a pumping factor k such that the new ‘pumped’ string is not part of the language
given.
7. State the contradiction and end the proof.

How to remember what pumping Lemma says:

Pumping Lemma alternates between “for all” and “there is at least one” or “for every” or
“there exists”. Notice:
For every regular language L
There exists a constant n
For every string w in L such that |w| >= n,
There exists a way to break up w into three strings w = xyz such that |y| > 0 , |xy| <= n and For every k>=0 , the string xykz is also in L.

courtesey: http://suraj.lums.edu.pk/~cs311w05/pumping_lemma_writeup.pdf
1. Show that L2 = {0m1m | x ∈ {0, 1}*} is not regular.
We show that the pumping lemma does not hold for L1. Consider any pumping number p; p≥ 1. Choose w = 0p1p.
Consider any pumping decomposition w = xyz;
|y| > 0 and |xy| ≤ p. It follows that x = 0a and y = 0b and z = 0p-a-b1p, for b ≥ 1. Choose i = 2. We need to show that xy2z = 0p+b1p is not in L1.

b ≥ 1.
So p+b > p
Hence 0p+b1p is not in L.

2. L2 = {xx | x ∈ {0, 1}*} is not regular.
We show that the pumping lemma does not hold for L2. Consider any pumping number
p ≥ 1. Choose w = 10p10p. Consider any pumping decomposition w = xyz; all we know about xyz is that
|y| > 0 and |xy| ≤ p. There are two possibilities:

(a) x = 10aand y = 0b and z = 0p-a-b10p, for b ≥ 1.
(a) x = " and y = 10b and z = 0p-b10p1.
Choose i = 2. We need to show that xy2z is not in L2.
In case (a), xy2z = 10p+b10p, which is not in L2 because b ≥ 1.
In case (b), xy2z = 10b10p10p, which is not in L2 because it contains three 1’s.

3. We prove that L3 = {1n2 | n ≥ 0} is not regular.

We show that the pumping lemma does not hold for L3. Consider any pumping number p ≥ 1.
Choose w = 1p2.
Consider any pumping decomposition w = xyz such that |y| > 0 and |xy| ≤ p. It follows
that x = 1a and y = 1b and z = 1p2
−a−b, for b ≥ 1 and a + b ≤ p. Choose i = 2. We need to show that
xy2z = 1n2+b is not in L3; that is, we need to show that p2 + b is not a square. Since b ≥ 1, we have
p2 + b > p2. Since a + b ≤ p, we have p2 + b ≤ p2 + p < (p + 1)2 4.Prove that Language L = {0n: n is a perfect square} is irregular.

Solution: L is infinite. Suppose L is also regular. Then according to pumping lemma there exists an integer n such that for every string w in where |w| >= n, we can break w into three strings w = xyz such that:
|y| > 0 , |xy| <= n and for all k>=0 , the string xykz is also in L.
Choose w to be w = 0s where s = n2 that is it is a perfect square.
Let w= 00000000000000000………00000 = xyz . (The length of w = s = n2 in this case.)
Let |xy| <= n and |y| = k. That is w = 0000 0k 000… X y z So, |xyz| = |xz| + |y| = (n2- k ) + (k) From pumping lemma, I can pump y any number of times and the new string should also belong to the language. Suppose I pump y twice then, the new string should belong to the language that is it should have length that is a perfect square but, |xy2z| = |xz| + 2|y| = (n2- k ) + 2k = n2 + k where n2 + k < 1 =" (n+1)(n+1)"> n2 (As k > 0)
=> n2 <>2 + k < (n+1)2 => n2 + k is not a perfect square
=> xy2z is not in L
=> This is a contradiction to the pumping lemma
So, our initial assumption must have been wrong that is L is not regular.

DFA Minimization Examples

  1. Example 1
  2. Example2

Monday, October 26, 2009

Regular Expressions

Describe the language denoted by the following regular expressions:

a) a(a|b)*a

The expression denotes the set of all strings of length two or more that start and end with an ‘a’.

b) ((e|a)b*)*

The expression denotes the set of all strings over the alphabet {a,b}.

c) (a|b)*a(a|b)(a|b)

The expression denotes the set of all strings of length 3 or more with an ‘a’ in the third position from the right. Ie of form yaxz where y is an arbitrary string , and x and z are single characters.

d) a*ba*ba*ba*

The expression denotes the set of all strings that contain precisely 3 b’s.

e) (aa|bb)*((ab|ba)(aa|bb)*(ab|ba)(aa|bb)*)*

The expression denotes the set of all strings of even length.

Wednesday, October 21, 2009

automata quiz ( True or False)

True or False
  1. In a finite language no string is pumpable. True
  2. A DFA has infinite number of states. False
  3. A DFA can have more than one accepting state. True
  4. In DFA all states have same number of transitions. True
  5. Every subset of a regular language is regular. False
  6. Let L4 = L1L2L3. If L1 and L2 are regular and L3 is not regular, it is possible that L4 is regular. True
  7. In a finite language no string is pumpable. True
  8. If A is a nonregular language, then A must be infinite. True
  9. Every context-free language has a context-free grammarin Chomsky normal form. True
  10. If A is a context-free language, then A must be nonregular. False
  11. The class of regular languages is closed under intersection. True
  12. If a language A is regular, then it A must be finite. False
  13. Every language is Turing-recognizable. False
  14. If a language is context-free, then it must be Turing-decidable. True
  15. The problem of determining if a context-free grammar generates
    the empty language is undecidable. False
  16. The problem of determining if a Turing machine recognizes the
    empty language is undecidable. True
  17. The set of all languages over an alphabet is countable.False
  18. There are some languages recognized by a 5-tape, nondetermin-
    istic Turing machine that cannot be recognized by a 1-tape,
    deterministic Turing machine.False
  19. The language { 0n1n | 0 ≤ n ≤ 1000 } is regular. True
  20. Nonregular languages are recognized by NFAs. False
  21. The class of context-free languages is closed under intersection. False
  22. A language has a regular expression if and only if it
    has an NFA. True
  23. The regular expression (01*0 ∪ 1)*0 generates the language
    consisting of all strings over {0, 1} having
    an odd number of 0’s. False
  24. If a language A has a PDA, then A is generated by a
    context-free grammar in Chomsky normal form. True
  25. If A is a context-free language and B is a language such that B is a subset of A, then B must be a context-free language. False
  26. If a language A has an NFA, then A is nonregular. False
  27. The regular expressions (a ∪ b)* and (b*a*)* generate the same language. True
  28. If a language A has a regular expression, then it also has a context-free grammar. True

Recommended Books








Monday, October 19, 2009

Operating systems Exam Questions

What are two types of low-level operations that higher-level synchronization operations(e.g., semaphores and monitors) can be built upon?
test-and-set. compare-and-swap. atomic reads and writes. Other atomic operations. enabling
and disabling interrupts.
_______________________________________________________________
What is the difference between a process and a thread?
Every process has its own address space, but multiple threads inside a process share part of
the memory with their parent process. There is less context switching overhead to switch
among threads when compared to switching among threads.
_______________________________________________________________
What is the difference between deadlock and starvation?
In a deadlock situation, none of the involved processes can possibly make progress. In a
starvation situation, a process is ready to execute, but it is not being allowed to execute.
_______________________________________________________________
Suppose our computer system is running five processes (P1,P2,P3,--,P5 ) and has four
separate types of resources (A,B,C,D). We want to see if the system is in a safe state
using the Banker's algorithm. Using the following information about the state of the
system, determine if the state is safe: (11 points)
Total
AB C D
4 5 4 3

Available
AB C D
0 1 0 0

Maximum
A B C D
P1 1 3 3 0
P2 2 2 1 3
P3 1 1 0 1
P4 1 4 1 0
P5 3 1 2 1

Used
A B C D
P1 0 1 2 0
P2 2 0 1 1
P3 1 0 0 1
P4 0 3 1 0
P5 1 0 0 1

A B C D
Total 4 5 4 3

A B C D
Available 0 1 0 0

Total gives the number of instances of each resource in the system; Available gives the
number of unallocated instances of each resource; Maximum refers to the maximum
number of instances of each resource required by each process; Used refers to how many instances of each resource each process currently holds.

Answer:
The Need matrix is as follows:
Need
A B C D
P1 1 2 1 0
P2 0 2 0 2
P3 0 1 0 0
P4 1 1 0 0
P5 2 1 2 0

The state of the system is unsafe. Executing the Banker's algorithm terminates with P2
and P5 unable to complete. We give a possible sequence of execution with "Work" P3 runs (1, 1, 0, 1), P4 runs (1, 4, 1, 1),P1 runs (1, 5, 3, 1). Now neither P2
nor P5 can release its resources because each holds resources the other needs.
------------------------------------------------------------------------------------------------
2. A computer system has m resources of the same type and n processes share these
resources. Prove or disprove the following statement for the system:
This system is deadlock free if sum of all maximum needs of processes is less than m+n.

3. There are four processes which are going to share nine tape drives. Their current and
maximum number of allocation numbers are as follows :
process current maximum
p1 3 6
p2 1 2
p3 4 9
p4 0 2
a. Is the system in a safe state? Why or why not?
b. Is the system deadlocked? Why or why not?