Sunday, December 27, 2009

Equations Solver

This program finds the inverse of the input coefficient matrix and multiplies it with the constant matrix to find the solution.

 


// Matrix Inverse.cpp : Defines the entry point for the console application.


//


 


#include "stdafx.h"


 


 


int _tmain(int argc, _TCHAR* argv[])


{


      int m,i,j,k,r,c,a,row,col,tru=0;


      float B[100][100],A[100][100],D[100][100],E[100][100],F[100][10];


      printf("Enter the number of rows or columns in the coefficient matrix: ");


      scanf("%d",&m);


      printf("Enter the coefficients in row-major order:\n");


      //Taking the input coefficient matrix into the array A.


      //Copying the array A into D for elementary tranformations.


      //Copying the array A into E for verification.


      //Initializing the elements of array B to make it an identity matrix.


      for(i=0;i<m;i++)


      {


            for(j=0;j<m;j++)


            {


                  scanf("%f",&A[i][j]);


                  D[i][j]=A[i][j];


                  E[i][j]=A[i][j];


                  if(i==j)


                  {


                        B[i][j]=1;


                  }


                  else


                  {


                        B[i][j]=0;


                  }


            }


      }


      //Taking the constant terms into the array F.


      printf("Enter the matrix of constant terms:\n");


      for(j=0;j<1;j++)


      {


            for(i=0;i<m;i++)


            {


                  scanf("%f",&F[i][j]);


            }


      }


      //Printing the original matrix.


      printf("The original matrix is:\n");


      for(i=0;i<m;i++)


      {


            for(j=0;j<m;j++)


            {


                  printf("%6.2f",A[i][j]);


            }


            printf("\n");


      }


      i=0;j=0;


      //Logic for elementary transformations.


      while(i!=m)


      {


            for(a=0;a<m;a++)


            {


                  if(D[i][j]==0)


                  {


                        tru=1;


                        break;


                  }


                  B[i][a]=B[i][a]/D[i][j];//Applying the operation below on the identity matrix B.


                  A[i][a]=A[i][a]/D[i][j];//Converting the diagonal elements of A into 1.


            }


            if(tru==1)


                  break;


            for(row=0;row<m;row++)


            {


                  for(col=0;col<m;col++)


                  {


                        D[row][col]=A[row][col];//Copying the present state of A into D.


                  }


            }


            for(c=0;c<m;c++)


            {


                  for(r=0;r<m;r++)


                  {


                        if(r!=i)


                        {


                              A[r][c]=A[r][c]-(D[r][j]*A[i][c]);//Converting the non-diagonal elements of same column of A to 0.


                              B[r][c]=B[r][c]-(D[r][j]*B[i][c]);//Applying the same operations to B.


                        }


                  }


            }


            for(row=0;row<m;row++)


            {


                  for(col=0;col<m;col++)


                  {


                        D[row][col]=A[row][col];//Copying the present state of A into D.


                  }


            }


            i++;j++;


      }


      printf("\nThe original matrix after transformation:\n");


      for(i=0;i<m;i++)


      {


            for(j=0;j<m;j++)


            {


                  printf("%6.2f",A[i][j]);


            }


            printf("\n");


      }


      printf("\nThe inverse of the matrix is:\n");


      for(i=0;i<m;i++)


      {


            for(j=0;j<m;j++)


            {


                  printf("%6.2f",B[i][j]);


            }


            printf("\n");


      }


      printf("\nVerification\n");


      //Multiplying the obtained inverse matrix with a copy of the original matrix.


      for(i=0;i<m;i++)


      {


            for(j=0;j<m;j++)


            {


                  k=0;


                  A[i][j]=0;


                  D[i][j]=0;


                  while(k!=m)


                  {


                        A[i][j]=A[i][j]+E[i][k]*B[k][j];


                        k++;


                  }


            }


      }


      //Printing the identity matrix obtained.


      for(i=0;i<m;i++)


      {


            for(j=0;j<m;j++)


            {


                  printf("%6.2f",A[i][j]);


            }


            printf("\n");


      }


      printf("\nThe answer matrix is:\n");


      //Obtaining the answers by multiplying the inverse with the constant matrix.


      for(i=0;i<1;i++)


      {


            for(j=0;j<m;j++)


            {


                  k=0;


                  D[j][i]=0;


                  while(k!=m)


                  {


                        D[j][i]=D[j][i]+(B[j][k]*F[k][i]);


                        k++;


                  }


                  printf("%6.2f",D[j][i]);


            }


            printf("\n");


      }


      printf("\n");


      if(tru==1)


      {


            printf("\nThe system of equations does not have a unique solution.\n");


      }


      return 0;


}


 


Enter the number of rows or columns in the coefficient matrix: 3
Enter the coefficients in row-major order:
4 3 -2
1 1 0
3 0 1
Enter the matrix of constant terms:
7 5 14
The original matrix is:
  4.00  3.00 -2.00
  1.00  1.00  0.00
  3.00  0.00  1.00


The original matrix after transformation:
  1.00  0.00  0.00
  0.00  1.00  0.00
  0.00  0.00  1.00


The inverse of the matrix is:
  0.14 -0.43  0.29
 -0.14  1.43 -0.29
 -0.43  1.29  0.14


Verification
  1.00  0.00  0.00
  0.00  1.00  0.00
 -0.00 -0.00  1.00


The answer matrix is:
  2.86  2.14  5.43


Press any key to continue . . .

Sudoku Solver


// Sudoku.cpp : Defines the entry point for the console application.


//


 


#include "stdafx.h"


 


 


int _tmain(int argc, _TCHAR* argv[])


{


      int A[100][100],r,c,inr,inc,used[10],count,trav,i,j,num=0,a,b;


      printf("Enter the values of the elements already present:\n");


      printf("Enter 0 for empty positions:\n");


      //Taking the input question.


      for(i=0;i<9;i++)


      {


            for(j=0;j<9;j++)


            {


                  scanf("%d",&A[i][j]);


                  if(A[i][j]!=0)


                        num++;


            }


      }


      //Printing the input matrix.


      printf("\nThe input matrix is:\n");


      for(i=0;i<9;i++)


      {


            for(j=0;j<9;j++)


            {


                  printf("%3d",A[i][j]);


            }


            printf("\n");


      }


      //Logic for finding the answer matrix.


      while(num<81)


      {


            for(i=0;i<9;i++)//Determining the row of the empty position.


            {


                  for(j=0;j<9;j++)//Determining the column of the empty position.


                  {


                        if(A[i][j]==0)//Condition checking whether the position is empty.


                        {


                              for(count=0;count<9;count++)


                                    used[count]=0;//Array to determine which number is already present.


                              count=9;


                              //Row check.


                              a=i;


                              for(b=0;b<9;b++)


                              {


                                    if(b!=j && A[a][b]!=0)


                                    {


                                          used[A[a][b]-1]=1;


                                    }


                              }


                              //Column check.


                              a=j;


                              for(b=0;b<9;b++)


                              {


                                    if(b!=i && A[b][a]!=0)


                                    {


                                          used[A[b][a]-1]=1;


                                    }


                              }


                              //Sub-square check.


                              if(i<=2)


                              {r=3;inr=0;}


                              else if(i<=5)


                              {r=6;inr=3;}


                              else if(i<=8)


                              {r=9;inr=6;}


                              if(j<=2)


                              {c=3;inc=0;}


                              else if(j<=5)


                              {c=6;inc=3;}


                              else if(j<=8)


                              {c=9;inc=6;}


                              //Checking in the sub-square determined by the above conditions.


                              for(a=inr;a<r;a++)


                              {


                                    for(b=inc;b<c;b++)


                                    {


                                          if(a!=i || b!=j || A[a][b]!=0)


                                          {


                                                used[A[a][b]-1]=1;


                                          }


                                    }


                              }


                              //Counting the number of elements permitted to come at the empty position.


                              for(trav=0;trav<9;trav++)


                              {


                                    if(used[trav]==1)


                                    {count--;}


                              }


                              if(count==1)


                              {


                                    for(trav=0;trav<9;trav++)


                                    {


                                          if(used[trav]==0)


                                                break;


                                    }


                                    A[i][j]=trav+1;//Element to be put=(Index of the zero element)+1.


                                    num++;


                              }


                        }


                  }


            }


      }


      //Printing the answer matrix.


      printf("\nThe answer is:\n");


      for(i=0;i<9;i++)


      {


            for(j=0;j<9;j++)


            {


                  printf("%3d",A[i][j]);


            }


            printf("\n");


      }


      return 0;


}


 


Enter the values of the elements already present:
Enter 0 for empty positions:
0 0 6 5 0 0 0 0 0
8 0 9 1 0 4 0 7 0
0 0 3 0 0 0 2 4 0
0 8 7 0 0 3 0 6 5
0 9 0 7 0 0 0 1 0
4 0 1 0 0 9 7 8 0
0 6 0 0 8 0 1 0 7
9 7 2 3 0 1 6 0 0
0 1 8 0 6 0 4 3 0


 


The input matrix is:
  0  0  6  5  0  0  0  0  0
  8  0  9  1  0  4  0  7  0
  0  0  3  0  0  0  2  4  0
  0  8  7  0  0  3  0  6  5
  0  9  0  7  0  0  0  1  0
  4  0  1  0  0  9  7  8  0
  0  6  0  0  8  0  1  0  7
  9  7  2  3  0  1  6  0  0
  0  1  8  0  6  0  4  3  0


 


The answer is:
  1  4  6  5  7  2  8  9  3
  8  2  9  1  3  4  5  7  6
  7  5  3  8  9  6  2  4  1
  2  8  7  4  1  3  9  6  5
  6  9  5  7  2  8  3  1  4
  4  3  1  6  5  9  7  8  2
  3  6  4  9  8  5  1  2  7
  9  7  2  3  4  1  6  5  8
  5  1  8  2  6  7  4  3  9


Press any key to continue . . .


 

Friday, December 25, 2009

Train Swapping


Key Concept: Bubble sorting gives the least number of swaps of two adjacent objects necessary to sort the array.


The Problem


At an old railway station, you may still encounter one of the last remaining ``train swappers''. A train swapper is an employee of the railroad, whose sole job it is to rearrange the carriages of trains.


Once the carriages are arranged in the optimal order, all the train driver has to do, is drop the carriages off, one by one, at the stations for which the load is meant.


 


The title ``train swapper'' stems from the first person who performed this task, at a station close to a railway bridge. Instead of opening up vertically, the bridge rotated around a pillar in the center of the river. After rotating the bridge 90 degrees, boats could pass left or right.


The first train swapper had discovered that the bridge could be operated with at most two carriages on it. By rotating the bridge 180 degrees, the carriages switched place, allowing him to rearrange the carriages (as a side effect, the carriages then faced the opposite direction, but train carriages can move either way, so who cares).


 


Now that almost all train swappers have died out, the railway company would like to automate their operation. Part of the program to be developed, is a routine which decides for a given train the least number of swaps of two adjacent carriages necessary to order the train. Your assignment is to create that routine.


 


Input Specification


The input contains on the first line the number of test cases (N). Each test case consists of two input lines. The first line of a test case contains an integer L, determining the length of the train ( ). The second line of a test case contains a permutation of the numbers 1 through L, indicating the current order of the carriages. The carriages should be ordered such that carriage 1 comes first, then 2, etc. with carriage L coming last.


 


Output Specification


For each test case output the sentence: 'Optimal train swapping takes S swaps.' where S is an integer.


 


Example Input


3


3


1 3 2


4


4 3 2 1


2


2 1


 


Example Output


Optimal train swapping takes 1 swaps.


Optimal train swapping takes 6 swaps.


Optimal train swapping takes 1 swaps.


 


// Train Swapping.cpp : Defines the entry point for the console application.


//


 


#include "stdafx.h"


 


 


int _tmain(int argc, _TCHAR* argv[])


{


      int count,A[100],swap,i,j,b,num,test=0,ans[100];


      scanf("%d",&num);//Takes the number of test-cases.


      while(test<num)


      {


            scanf("%d",&count);//Takes the length of the train in terms of number of coaches.


            b=0;


            for(i=0;i<count;i++)


            {


                  scanf("%d",&A[i]);//Takes the current order of the coaches.


            }


            //Bubble sorting the array.


            for(i=0;i<count;i++)


            {


                  for(j=0;j<=count-i;j++)


                  {


                        if(A[j]>A[j+1] && (j+1)<count)


                        {


                              swap=A[j];


                              A[j]=A[j+1];


                              A[j+1]=swap;


                              b++;


                        }


                  }


            }


            //Storing the number of minimal swaps in the ans array.


            ans[test]=b;


            test++;


      }


      //Printing the output.


      for(i=0;i<test;i++)


      {


            printf("Optimal train swapping takes %d swaps.\n",ans[i]);


      }


      return 0;


}


 

3
3
1 3 2
4
4 3 2 1
2
2 1
Optimal train swapping takes 1 swaps.
Optimal train swapping takes 6 swaps.
Optimal train swapping takes 1 swaps.
Press any key to continue . . .

Maximum Sum


The Problem


Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest sum. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. A sub-rectangle is any contiguous sub-array of size or greater located within the whole array. As an example, the maximal sub-rectangle of the array:



is in the lower-left-hand corner:



and has the sum of 15.


Input and Output


The input consists of an array of integers. The input begins with a single positive integer N on a line by itself indicating the size of the square two dimensional array. This is followed by integers separated by white-space (newlines and spaces). These integers make up the array in row-major order (i.e., all numbers on the first row, left-to-right, then all numbers on the second row, left-to-right, etc.). N may be as large as 100. The numbers in the array will be in the range [-127, 127].


The output is the sum of the maximal sub-rectangle.


Sample Input


4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2


Sample Output


15

// Maximum Sum.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

 

int A[100][100],m,n,maxsum,count=0,x,y,row,col;

int _tmain(int argc, _TCHAR* argv[])

{

      int i,j,r,c;

      void mat(int i,int j);

      printf("Enter the number of rows: ");

      scanf("%d",&m);

      printf("Enter the number of columns: ");

      scanf("%d",&n);

      //Taking the elements of the input matrix.

      for(i=0;i<m;i++)

      {

            for(j=0;j<n;j++)

            {

                  scanf("%d",&A[i][j]);

            }

      }

      //Printing the input matrix.

      printf("The matrix is:\n");

      for(i=0;i<m;i++)

      {

            for(j=0;j<n;j++)

            {

                  printf("%3d",A[i][j]);

            }

            printf("\n");

      }

//Forming possible row-column pairs or window sizes smaller than or equal to the dimensions of the original matrix.

      for(i=1;i<m+1;i++)

      {

            for(j=1;j<n+1;j++)

            {

                  mat(i,j);//Function for calculating the sum of the sub-matrices.

            }

      }

      //Printing the maximum sum sub-matrix and the maximum sum.

      printf("The maximum sum sub-matrix is:\n");

      for(m=x;m<row;m++)

      {

            for(n=y;n<col;n++)

            {

                  printf("%3d",A[m][n]);

            }

            printf("\n");

      }

      printf("The maximum sum is %d\n",maxsum);

      return 0;

}

void mat(int i,int j)

{

      int r,c,a,b,thissum=0;

for(r=0;r<=m-i;r++)//Defines the row position of the starting element of the sub-matrix.

      {

for(c=0;c<=n-j;c++)//Defines the column position of the starting element of the sub-matrix.

            {

                  thissum=0;

for(a=r;a<r+i;a++)//Defines the rows of elements to be included in the sub-matrix according to the window-size.

                  {

for(b=c;b<c+j;b++)//Defines the rows of elements to be included in the sub-matrix according to the window-size.

                        {

thissum=thissum+A[a][b];//Calculating the sub-sum.

                        }

                  }

                  count++;

                  if(count==1)

                  {

                        maxsum=thissum;

                        x=r;y=c;row=r+i;col=c+j;

                  }

                  else

                  {

                        if(thissum>maxsum)

                        {

                              maxsum=thissum;

x=r;y=c;row=r+i;col=c+j;//Storing the values the rows,columns,row and column of the starting element.

                        }

                  }

            }

      }

}

 

Enter the number of rows: 4
Enter the number of columns: 4

Enter the elements in the row-major order:
0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2


The matrix is:
  0 -2 -7  0
  9  2 -6  2
 -4  1 -4  1
 -1  8  0 -2


The maximum sum sub-matrix is:
  9  2
 -4  1
 -1  8


The maximum sum is 15
Press any key to continue . . .

 

Wednesday, December 23, 2009

Prime factorization of a given integer


// Prime factorization.cpp : Defines the entry point for the console application.


//


 


#include "stdafx.h"


 


 


int _tmain(int argc, _TCHAR* argv[])


{


      int num,k=0,i=1,pri[100],j,count=0,tru=0,fac[100],ans[100],m,n;


      printf("Enter the number: ");


      scanf("%d",&num);


      //Generating the first 100 prime numbers and storing them in the pri[] array.


      while(count<100)


      {


            tru=0;


            i++;


            for(j=2;j<=i/2;j++)


            {


                  if(i%j==0)


                  {


                        tru=1;


                        break;


                  }


            }


            if(tru!=1)


            {


                  pri[count]=i;


                  count++;


            }


      }


      /*printf("The prime numbers are:\n");


      for(i=0;i<count;i++)


      {


            printf("%d,",pri[i]);


      }*/


      i=0;tru=0;


      //Doing the prime factorization.


      while(num>1)


      {


            j=0;tru=0;


            while(num%pri[i]==0)


            {


                  tru=1;


                  num=num/pri[i];


                  j++;


            }


            if(tru==1)


            {


                  fac[k]=j;


                  ans[k]=pri[i];


                  k++;


            }


            i++;


      }


      printf("The prime factorization is:\n");


      //Printing the prime factorization in the correct format.


      for(m=0;m<k;m++)


      {


            for(n=0;n<fac[m];n++)


            {


                  if(m!=0 && n==0)


                        printf("*");


                  printf("%d",ans[m]);


                  if(n!=fac[m]-1)


                        printf("*");


            }


      }


      printf("\n");


      return 0;


}


 


Enter the number: 36
The prime factorization is:
2*2*3*3
Press any key to continue . . .