Saturday, October 20, 2012

Longest Palindromic Subsequence or Maximum Length of Palindrome

Definition:
              A sequence is called "Palindrome" if it is read same left to right and right to left. The sequence remains same as before after reversing it. The sequence "MADAM" is a Palindrome.
More about Palindrome.

A sequence which is a Palindrome is called a Palindromic Sequence. In this problem, given any sequence (not necessarily palindromic sequence), and we have to determine the Longest Palindromic Sub-sequence of Maximum Length of Palindrome of it.
A dynamic approach is not mandatory for this problem, because there is no overlapping sub-problems and so no optimal sub-structure available for Longest Palindromic Sub-sequence.
But if we go recursively, it can be easily determined. How? Obviously there is no overlapping sub-problems but we can divide it into sub-problems (that how we do it :p).
Here is a C++ solution for LPS.


#include <iostream>
#include <string>

using namespace std;

template<class T>inline T MAX( T a, T b ){ return a>b ? a:b; } // Note: returns maximum of a and b

string A;

int LPS( int i, int j ) {
    if( i == j ) return 1; // A[i] & A[j] are same, cost is 1
    if( i > j ) return 0;
    if( A[i] == A[j] )
        return 2 + LPS( i+1, j-1 ); // A[i] & A[j] are different, cost is 2, 1 for each.
    else
        return MAX( LPS(i+1, j), LPS(i, j-1) );
}

int main( ){
    while( cin >> A ){
        int len = A.length( );
        int res = LPS(0, len);
        cout << "Longest Palindromic Subsequence is: " << res << endl;
    }
    return 0;
}

Obviously, a memoization make the procedure lot more faster. Here is a memoized faster version.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

template<class T>inline T MAX( T a, T b ){ return a>b ? a:b; } // Note: returns maximum of a and b
const int SIZ = 105;

#define mset2d(x,n) memset(x,n,sizeof(int [SIZ][SIZ]))

string A;
int memo[SIZ][SIZ];

int LPS( int i, int j ) {
    if( i == j ) return 1; // A[i] & A[j] are same, cost is 1
    if( i > j ) return 0;
    if( memo[i][j] != -1 ) return memo[i][j];
    if( A[i] == A[j] )
        memo[i][j] = 2 + LPS( i+1, j-1 ); // A[i] & A[j] are different, cost is 2, 1 for each.
    else
        memo[i][j] = MAX( LPS(i+1, j), LPS(i, j-1) );
    return memo[i][j];
}

int main( ){
    while( cin >> A ){
        mset2d( memo, -1 );
        int len = A.length( );
        int res = LPS(0, len);
        cout << "Longest Palindromic Subsequence is: " << res << endl;
    }
    return 0;
}

Monday, October 15, 2012

Addition, Subtraction & Multiplication in .ASM

Addition, Subtraction & Multiplication of two numbers submitted, until the program terminates by user. The termination process is actually maintained by 0 and 1, 0 terminates the program and 1 continues.
Limitations of the code is the initial two numbers and the resultant numbers must be between 0 to 9. "emu8086" compiler was used. This is my 5th code in assembly language I have done in my lab.
; Date: October 10, 2012
; Author: Md. Nabid Imteaj
; Tag: Add, Substract, Multiplication as user want

TITLE ANOTHER_DAY_IN_CLASS  
.model small
.stack 100h
.code

.data
msg1 db 'ENTER Hex Value: $'
msg2 db 'Equivalent Decimal: $' 
msg3 db 'INVALID :($'
msg10 db '0 to exit, 1 to continue?: $'
msg11 db 'THANK YOU :D$' 

main proc
    
    mov ax, @data
    mov ds, ax 
    
    mov cx, 3

AGAIN_PAIN: 
; new line
    mov ah, 2
    mov dl, 0dh
    int 21h
    mov dl, 0ah
    int 21h 

cmp cl, 0
je TERMINATE
dec cx

; message print

    lea dx, msg1
    mov ah, 9
    int 21h
    
; enter character
    mov ah, 1
    int 21h 
    mov bl, al
    
    ; new line
    mov ah, 2
    mov dl, 0dh
    int 21h
    mov dl, 0ah
    int 21h
    
; cmpareing
    cmp bl, 'A'
    je print_A
    cmp bl, 'B'
    je print_B 
    cmp bl, 'C'
    je print_C
    cmp bl, 'D'
    je print_D
    cmp bl, 'E'
    je print_E
    cmp bl, 'F'
    je print_F 
    
    cmp bl, 30
    jge over_0
    
over_0:
    cmp bl, 39
    jle less_9 
    jmp print_invalid

less_9:
    mov ah, 2
    mov dl, bl
    int 21h 
    jmp EXIT_ 
    
print_A:  
lea dx, msg2
mov ah, 9
int 21h
   
    mov ah, 2
    mov dl, '1'
    int 21h
    mov ah, 2
    mov dl, '0'
    int 21h 
    jmp EXIT_ 
    
print_B:
lea dx, msg2
mov ah, 9
int 21h 
    mov ah, 2
    mov dl, '1'
    int 21h
    mov ah, 2
    mov dl, '1'
    int 21h 
    jmp EXIT_
    
print_C:
lea dx, msg2
mov ah, 9
int 21h 
    mov ah, 2
    mov dl, '1'
    int 21h 
    mov ah, 2
    mov dl, '2'
    int 21h 
    jmp EXIT_
    
print_D:
lea dx, msg2
mov ah, 9
int 21h 
    mov ah, 2
    mov dl, '1'
    int 21h 
    mov ah, 2
    mov dl, '3'
    int 21h 
    jmp EXIT_
    
print_E:
lea dx, msg2
mov ah, 9
int 21h 
    mov ah, 2
    mov dl, '1'
    int 21h
    mov ah, 2
    mov dl, '4'
    int 21h  
    jmp EXIT_     
    
print_F:
lea dx, msg2
mov ah, 9
int 21h 
    mov ah, 2
    mov dl, '1'
    int 21h
    mov ah, 2
    mov dl, '5'
    int 21h  
    jmp EXIT_ 
           
print_invalid:
    lea dx, msg3
    mov ah, 9
    int 21h
    jmp EXIT_
               
  
EXIT_: 

; new line
    mov ah, 2
    mov dl, 0dh
    int 21h
    mov dl, 0ah
    int 21h    
    
; operation message
    lea dx, msg10
    mov ah, 9
    int 21h 
    
; gets character
    mov bl, '1'
    mov ah, 1
    int 21h
    
    cmp al, bl
    je AGAIN_PAIN
    
    ; new line
    mov ah, 2
    mov dl, 0dh
    int 21h
    mov dl, 0ah
    int 21h 
    
TERMINATE:   
     ; operation message
    lea dx, msg11
    mov ah, 9
    int 21h 

mov ah, 4ch
int 21h
main endp
end main

Sunday, September 23, 2012

Maximum Interval Sum


Given a array of natural numbers, we have to find the maximum interval sum.
5    5   -1    5    5
Now we have these intervals (5 + 5), ( 5 + 5 + (-1)), (5 + 5 + (-1) + 5), (5 + 5 + (-1) + 5 + 5). 
Which interval has maximum sum?
(5 + 5) = 10
( 5 + 5 + (-1)) = 9
(5 + 5 + (-1) + 5) = 14
(5 + 5 + (-1) + 5 + 5) = 19
So, the last interval has maximum sum. These type of problems are called Maximum Interval Sum.
C++ implementation:

#include <iostream>
using namespace std;
const int INF = (-(1<<30));  // negative infinity
int MIS( ) {
    sum = 0; // initially sum is 0
    Max = -INF; // Maximum is less than 0
    for( i=0; i<N; i++ ) {
       sum += A[i]; // "A[]" array of intejars
        if( sum > Max ) Max = sum;
        if( sum < 0 ) sum = 0;  // sum below 0 is not useful, right?
    }
    return Max;
}

Wednesday, September 19, 2012

Message Print in Assembly Language

TITLE PRINTING HABIJABI

.MODEL SMALL    

.STACK 100H   

.DATA
MSG  DB 'Take Input: $'
MSG1 DB 'First Value: $'
MSG2 DB 'Second Value: $'
A    DB 5
B    DB ?

MAIN PROC
; initializing data segment  
    MOV AX, @DATA
    MOV DS, AX  ; initialized :D 
    
; display message
    LEA DX, MSG
    MOV AH, 9  ; message print function
    INT 21h  
    
; input 
    MOV AH, 1
    INT 21h
    MOV B, AL
    
; new line
    MOV AH, 2
    MOV DL, 0DH
    INT 21H
    MOV DL, 0AH
    INT 21H   
    
; display message1
    LEA DX, MSG1
    MOV AH, 9  ; message print function
    INT 21h
    
; display A
    MOV AH, 2
    MOV DL, A
    INT 21h
    
; new line
    MOV AH, 2
    MOV DL, 0DH
    INT 21H
    MOV DL, 0AH
    INT 21H   
    
; display message2
    LEA DX, MSG2
    MOV AH, 9  ; message print function
    INT 21h
    
; display B 
    MOV AH, 2
    MOV DL, B
    INT 21h
    
; return to DOS

    MOV AH, 4CH
    INT 21h
    
MAIN ENDP
    END MAIN

Maximum Sum Sub Matrix


Problem:

        Given m*n matrix. We have to find a sub-matrix which have maximum sum. Values of the matrix can be both positive and negative.

Idea:

      Lets start with an example then we will generate our idea. Suppose we have 4*4 matrix as below:
    [ initial matrix ] 
-1      2     3      10          
 5      9    -7       6
 0    -1     -3     -5
 7     5   -18       2
Now we add first column with second column. So, the matrix became like this:
-1      1     3      10
 5     14    -7       6
 0    -1     -3     -5
 7    12   -18       2
Now add second column with third column and the third column with last column. Then, the matrix will look like:
-1      1     4      14
 5     14     7      13
 0    -1     -4      -9
 7    12    -6      -4

Now the row addition part. Add first row with second, then add second with third, then third with last. Finally, the matrix will be:
-1      1      4      14
 5     15    11     27
 0     14     7      18
 7     26     1      14

Our matrix is ready to manipulate.

-1
1
4
14
4
15
11
27
4
14
7
18
11
26
1
14
Definitely, we can say form this matrix that value of every cell is the sum of (0,0) to that cell. Say, (1,1) is 15 is the sum of (0,0), (0,1), (1,0) and (1,1) cells that is 15 i.e. ( -1+2+5+9 ) = 15. This property makes our idea easier. 
       In this matrix, the maximum sum is the middle sub-matrix. ( 15 + 11 + 14 + 7 ) = 37.
-1
1
4
14
4
15
11
27
4
14
7
18
11
26
1
14
We are very closer to our solution. Now, see carefully. Cell (2,2) has cumulative sum form cell (0,0) to (2,2).  
-1
1
4
14
4
15
11
27
4
14
7
18
11
26
1
14
We can subtract the sum of cell (0,0) to (0,2) from this result. 
-1
1
4
14
4
15
11
27
4
14
7
18
11
26
1
14
Again, we subtract sum of cell (0,0) to (2, 0) from the last result.
-1
1
4
14
4
15
11
27
4
14
7
18
11
26
1
14
Have we finished ? No. Look at the matrix above carefully. We have subtract cell (0,0) from the actual result  twice. It should be once. Finally, add the (0,0) cell to actual result and we get our maximum sum sub-matrix.

Wednesday, June 27, 2012

Line Feed & Input Problem

Hello there, its been a long time for a new post. This time I am here with the Line Feed (ASCII value 10) and input problem in C/C++ compilers. I faced this problem tonight and could not find where was the bug!
Really I was feeling guilty, Oh! I cannot taking input a string...
Okay, now the problem is sometimes we need to take input an intejar followed a string(can be a string / empty line / only contains space). For this type of problem "scanf" followed "getsdosent works.
Why?
Now there is a ascii character (usually called "new line") "Line Feed" ('\n') ascii value 10, which caused the problem.
How to solve?
Take input the intejar followed by a False or Dummy input such as
scanf("%d%c", &Tc, &Fake); // Tc is intejar type and Fake is char type
Done.
More about ASCII.
Note:
* "scanf" takes input without leading and trailing spaces.
* "gets" takes the whole line until new line entered.
* "getline" does the same.
* "gets", previously used "scanf" dosent works. Better take a dummy or fake character input with "scanf" to    get rid of Line Feed. (Discussed above)
* "gets" only takes character array.
* While taking input a single character with "scanf", its better to use a space before "%c"
like scanf(" %c ", &ch); // ch is character type.

Thanks a lot. Please comment bellow if you want to add something or make correction.
Enjoy Safe Computing.

Sunday, January 29, 2012

Adding Timer in C code

Hello everyone! Hope you are passing great time with coding!!
Today I am here with how to add or insert a timer in your C code to show the time how much your code taking time to execute. Sometimes it becomes important to see time your code taking. Okay let’s do it…
We will discuss with a very simple problem. User input two integers and a code to add them !!!
-----------------------------------------------------------------------------------------------------------------
Inserting timer:

#include <stdio.h>
#include <time.h>  //inserting time.h library function.

int main ( )
{
    int a, b, add;  //a & b two integers and add is their addition.
scanf ( “ %d %d ”, &a, &b ); // taking input.

clock_t start=clock(); // clock starting.
add = a + b; //adding a & b.

printf(“\nAddition of %d & %d is =  %d, a, b, add );
                      //printing result.
printf("\nTime = %.2f secondes\n",(double)(clock()-start)/CLOCKS_PER_SEC); // printing time.
    return 0 ;
-----------------------------------------------------------------------------------------------------------------
Inserting current time:
#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t timer = time(NULL);
    printf("current time is %s", ctime(&timer));
    return 0;
}
-----------------------------------------------------------------------------------------------------------------
Reference:  

Sunday, January 22, 2012

Active AIUB Student Mail


There is a rumor among AIUBians as well as outsiders, that AIUB provide student mail only for AIUBians with 10GB (+25GB by Live) free space.
But it’s not rumor… it’s 200% true. Now problem is that how can someone active this student mail? I asked some seniors about this in my first semester but most of them said they only know about it, don’t  know how to activate. No probs. I am going to write about it.

Follow these steps:
Step 1:
Go to IT department in Level 5, Campus 4. Contact the duty stuff and collect a form. Write your name, ID, reason (for this mark on 'e-mail')and a valid e-mail address. The next day collect your password.
Step 2:
this PDF file & follow the next procedure to active student mail.
FINISH !!!

Hope this will beneficial for AIUBians.
Enjoy your stay on this blog.
ENJOY SAFE COMPUTING.
Thank you.

Tuesday, January 17, 2012

Beginners C Programming : Variables & Data Types


The Journey Begins
I always thought to do something for the beginners, to make those lessons easier which gave me lots of pain. (:P) So, the journey begins from here. Actually, today I attended my first class of C++. The discussions will be on C++. But before that I would like to review some chapters for the beginners so that those terms became easy for them as well as for them also who are practicing C.

Why do we have to learn a programming language??
Simply, we came to learn about the computer because we love computer, that what I realized and also told by my favorite course teacher. And a programming language is a language to communicate with the computer. (hmm… In a simple line.)

What is C or Why C?
The C is called the mother of programming language, the root or base level language, developed by Dennis Ritchie (September 9, 1941 to October 12, 2011). For detail, take a tour to the Wikipedia.
C is one of the most widely used computer language. It is a procedural or step by step procedure language.

Please Note: Don’t panic. I don’t want to make it lengthy. Search the web if you want. I like to make it short as possible but more useful.

Okay, it’s time now! Let’s get into C!!
Before that, we must to be familiar with some definitions which are so much important.

Variable & Data Type:
This is the first thought of a programming language.

Variable:
We have used some variables in Math. We imagined some ‘x’ or ‘y’ to prove a problem. Finally the ‘x’ or ‘y’ had a value. Our variable is also like that. A variable is that, which can store a value. Finish!!!
Tips: Your variable should be any alphabet (uppercase or lowercase), any word (like ‘sum’), and any combination of alphabets (like ‘aa’). Do not use ‘space’ in your variable.

Data Type:
Now read attentively.
How many students are there in your section? Look carefully at them and you will find them their characteristics will not match with each other, even yours. Everyone have different personality. Isn’t it?
If the students are your variables then their personality or characteristics are their Data Type. Clear? I think No. Data Type of a variable is that which represents the type of the variable like ‘x’ is a integer number or real number or a character. This is important that your variable must contain a valid Data Type.

Some of the Data Types used in C are:
int (stands for integer numbers i.e like 3)
float (stands for real numbers i.e like 3.1416)
char (stands for character i.e like ‘a’)


Hope that it was easy for you to understand. You can mail me from my profile that is below Blog Archive.
Enjoy your stay on this blog.
ENJOY SAFE COMPUTING.
Thank you.
Thanks - Jajabor, 2014