Total Pageviews

Monday, August 7, 2023

BFS IN C

 #include <stdio.h>

 

int n, i, j, visited[10], queue[10], front = -1, rear = -1;

int adj[10][10];

 

void bfs(int v)

{

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

        if (adj[v][i] && !visited[i])

            queue[++rear] = i;

    if (front <= rear)

    {

        visited[queue[front]] = 1;

        bfs(queue[front++]);

    }

}

 

void main()

{

    int v;

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

    scanf("%d", &n);

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

    {

        queue[i] = 0;

        visited[i] = 0;

    }

    printf("Enter graph data in matrix form:    \n");

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

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

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

    printf("Enter the starting vertex: ");

    scanf("%d", &v);

    bfs(v);

    printf("The node which are reachable are:    \n");

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

        if (visited[i])

            printf("%d\t", i);

        else

            printf("BFS is not possible. Not all nodes are reachable");

    

}

KRUSKAL

 #include <conio.h>

#include <stdlib.h>

#include <stdio.h>

    int i, j, k, a, b, u, v, n, ne = 1;

    int min, mincost = 0, cost[9][9], parent[9];

    int find(int);

    int uni(int, int);

    void main() {

      printf("\n\tImplementation of Kruskal's Algorithm\n");

      printf("\nEnter the no. of vertices:");

      scanf("%d",&n);

      printf("\nEnter the cost adjacency matrix:\n");

      for (i = 1; i<= n; i++) {

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

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

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

            cost[i][j] = 999;

        }

      }

      printf("The edges of Minimum Cost Spanning Tree are\n");

      while (ne < n) {

        for (i = 1, min = 999; i <= n; i++) {

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

            if (cost[i][j] <min) {

              min = cost[i][j];

              a = u = i;

              b = v = j;

            }

          }

        }

        u = find(u);

        v = find(v);

        if (uni(u, v)) {

          printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);

          mincost += min;

        }

        cost[a][b] = cost[b][a] = 999;

      }

      printf("\n\tMinimum cost = %d\n", mincost);

      getch();

    }

    int find(int i) {

      while (parent[i])

        i = parent[i];

      return i;

    }

    int uni(int i, int j) {

      if (i != j) {

        parent[j] = i;

        return 1;

      }

      return 0;

    }

prims algorithm

 #include<iostream>


using namespace std;


// Number of vertices in the graph  

const int V=6;


// Function to find the vertex with minimum key value 

int min_Key(int key[], bool visited[])  

    int min = 999, min_index;  // 999 represents an Infinite value


    for (int v = 0; v < V; v++) { 

        if (visited[v] == false && key[v] < min) { 

        // vertex should not be visited

            min = key[v];

min_index = v;  

        }

    }    

    return min_index;  

}  


// Function to print the final MST stored in parent[]  

void print_MST(int parent[], int cost[V][V])  

{  

    int minCost=0;

cout<<"Edge \tWeight\n";  

    for (int i = 1; i< V; i++) {

cout<<parent[i]<<" - "<<i<<" \t"<<cost[i][parent[i]]<<" \n";  

minCost+=cost[i][parent[i]];

    }

cout<<"Total cost is"<<minCost;

}  


// Function to find the MST using adjacency cost matrix representation  

void find_MST(int cost[V][V])  

{  

    int parent[V], key[V];

    bool visited[V];


    // Initialize all the arrays 

    for (int i = 0; i< V; i++) { 

        key[i] = 999;    // 99 represents an Infinite value

        visited[i] = false;

        parent[i]=-1;

    }    


    key[0] = 0;  // Include first vertex in MST by setting its key vaue to 0.  

    parent[0] = -1; // First node is always root of MST  


    // The MST will have maximum V-1 vertices  

    for (int x = 0; x < V - 1; x++) 

    {  

        // Finding the minimum key vertex from the 

        //set of vertices not yet included in MST  

        int u = min_Key(key, visited);  


        visited[u] = true;  // Add the minimum key vertex to the MST  


        // Update key and parent arrays

        for (int v = 0; v < V; v++)  

        {

            // cost[u][v] is non zero only for adjacent vertices of u  

            // visited[v] is false for vertices not yet included in MST  

            // key[] gets updated only if cost[u][v] is smaller than key[v]  

            if (cost[u][v]!=0 && visited[v] == false && cost[u][v] < key[v])

            {  

                parent[v] = u;

                key[v] = cost[u][v];  

            }        

        }

    }


    // print the final MST  

print_MST(parent, cost);  

}  


// main function

int main()  

{  

    int cost[V][V];

cout<<"Enter the vertices for a graph with 6 vetices";

    for (int i=0;i<V;i++)

    {

        for(int j=0;j<V;j++)

        {

cin>>cost[i][j];

        }

    }

find_MST(cost);  


    return 0;  

}  

Tuesday, July 25, 2023

Twin Prime Number in a range

 

import java.io.*; 

import java.util.*;

 

public class Main

{static boolean checkPrimeNumber(int number) 

    { 

        int i; 

        int m = 0; 

        int flag = 0;       

        m = number/2;       

        if(number == 0 || number == 1){   

            return false;       

        }else{   

            for(i = 2; i <= m ;i++){       

                if(number%i == 0){       

                    flag=1;       

                    return false;       

                }       

            }       

            if(flag == 0)   

            {  

                return true; 

            }   

        } 

        return false; 

    }     

    static boolean checkTwinPrimeNumber(int number1, int number2) 

    { 

        if(checkPrimeNumber(number1) && checkPrimeNumber(number2) && Math.abs(number1 - number2) == 2) 

            return true; 

        else 

            return false; 

    } 

  

    public static void main(String[] args) 

    { 

        int startRange, endRange; 

         

        Scanner sc=new Scanner(System.in);          

      

        System.out.println("Enter start value");            

        startRange = sc.nextInt();            

                System.out.println("Enter last value");            

        endRange = sc.nextInt(); 

         

        System.out.println("The pairs of twin primes between" + startRange + " and " + endRange + "are:"); 

         

        for (int i = startRange; i < endRange; i++) { 

            if (checkTwinPrimeNumber(i, (i + 2))){ 

                System.out.printf("(%d, %d)\n", i, i + 2); 

            } 

        } 

    } 

} 

Neon Number

 import java.util.Scanner;  

import java.lang.Math;  

public class Main

{

    

public static void main(String args[])     

{     

int sum = 0, n;      

Scanner sc = new Scanner(System.in);  

System.out.print("Enter the number to check: ");  

n = sc.nextInt();  

int square = n * n; 

while(square != 0)  

{  

 

int digit = square % 10; 

sum = sum + digit;

square = square / 10;  

}  


if(n == sum)  

System.out.println(n + " is a Neon Number.");  

else  

System.out.println(n + " is not a Neon Number.");  

}  

}  



DecimalToBinary

 

import java.util.Scanner; 

import java.lang.Math; 

public class Main

{

    public static int convertDecimalToBinary(int dec) {

   

      int rem,b1=0;

      int rev = 1;

      while (dec > 0) {

         rem = dec % 2;

         dec = dec / 2;

         b1 = b1 + rem * rev;

         rev = rev * 10;

      }

    return b1;

  }

public static void main(String args[])    

{    

 

 

    Scanner in = new Scanner(System.in); 

System.out.print("Enter a number : "); 

 

int num = in.nextInt(); 

 

    int decimal = convertDecimalToBinary(num);

    System.out.println("Binary to Decimal");

    System.out.println(num + " = " + decimal);

  }

 

 

}

Automorphic Number

 

import java.util.Scanner; 

import java.lang.Math; 

public class Main

{

public static void main(String args[])    

{    

Scanner in = new Scanner(System.in); 

System.out.print("Enter a number to check: "); 

 

int num = in.nextInt(); 

int count=0;

int square = num*num;

int temp = num;

while(temp>0) 

{ 

count++;

temp=temp/10; 

}  

int lastDigit = (int) (square%(Math.pow(10, count)));  

if(num == lastDigit) 

System.out.println(num+ " is an automorphic number."); 

else 

System.out.println(num+ " is not an automorphic number."); 

} 

} 

Armstrong Number

 

import java.util.Scanner; 

import java.lang.Math; 

public class Main

{

     static boolean isArmstrong(int n)  

{  

int temp, digits=0, last=0, sum=0;  

 

temp=n;  

 

while(temp>0)   

{  

temp = temp/10;  

digits++;  

}  

temp = n;  

while(temp>0)  

{

last = temp % 10;  

sum +=  (Math.pow(last, digits));

temp = temp/10;  

} 

 

if(n==sum)

return true;

else return false;  

}  

   

   

 

public static void main(String args[])    

{    

int num;  

Scanner sc= new Scanner(System.in); 

System.out.print("Enter the limit: ");

num=sc.nextInt(); 

if(isArmstrong(num)) 

System.out.print(num+ " is armstrong Number "); 

}  

} 

Fibonacci series

 

import java.util.*;

 

public class Main

{

                public static void main(String[] args) {

                        Scanner sc = new Scanner(System.in); 

                                 System.out.println( " enter a value");

 

                     int n1=0,n2=1,n3,i,count;

                     count = sc.nextInt();   

 

   

 for(i=1;i<=count;++i)//loop starts from 2 because 0 and 1 are already printed   

 {   

  n3=n1+n2;   

  System.out.print(" "+n1);   

  n1=n2;   

  n2=n3;   

 }   

 

}} 

 

Java happy Number

 

import java.util.*;

public class Main

{public static int isHappyNumber(int num){ 

        int rem = 0, sum = 0; 

         

        while(num > 0){ 

            rem = num%10; 

            sum = sum + (rem*rem); 

            num = num/10; 

        } 

        return sum; 

    } 

                public static void main(String[] args) {

                    Scanner sc = new Scanner(System.in); 

                                 System.out.println( " enter a value");

                                 int num = sc.nextInt();   

        int result = num; 

         

        while(result != 1 && result != 4){ 

            result = isHappyNumber(result); 

        } 

         

      

        if(result == 1) 

            System.out.println(num + " is a happy number"); 

        else if(result == 4) 

            System.out.println(num + " is not a happy number");    

    } 

} 

Java Magic Number

 

import java.util.Scanner; 

public class Main

{

                public static void main(String[] args) {

                                int n, remainder = 1, number, sum = 0; 

Scanner sc = new Scanner(System.in); 

System.out.print("Enter a number you want to check: "); 

n = sc.nextInt(); 

number = n; 

while (number > 9)               

{ 

while (number > 0) 

{ 

remainder = number % 10;  

sum = sum + remainder; 

number = number / 10;    

} 

number = sum; 

sum = 0; 

} 

if (number == 1) 

{ 

System.out.println("The given number is a magic number."); 

} 

else 

{ 

System.out.println("The given number is not a magic number."); 

} 

} 

} 

Monday, July 24, 2023

Write a program to accept a word from the user . Print the converted word where the consonants are upgraded by nearest vowel and vowels are upgraded to nearest consonant.

 import java.util.Scanner;

import java.util.Random;

public class Main

{

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a word: ");

String word = scanner.nextLine();

scanner.close();

String convertedWord = convertWord(word);

System.out.println("Converted word: " + convertedWord);

}

private static String convertWord(String word)

{

StringBuilder converted = new StringBuilder();

for (int i = 0; i < word.length(); i++)

{char convertedChar;

    

char c = word.charAt(i);

if (c!=' '){

 convertedChar = convertCharacter(c);}else{convertedChar =' ';}


converted.append(convertedChar);

}

return converted.toString();



private static char convertCharacter(char c)

{

if (isVowel(c))

{

return findNearestConsonant(c);

}

else

{

return findNearestVowel(c);

}

}



private static boolean isVowel(char c)

{

c = Character.toLowerCase(c);

return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';

}


private static char findNearestConsonant(char c)

{

while (true)

{

c--;

if (!isVowel(c))

{

return c;

}

}

private static char findNearestVowel(char c)

{

while (true)

{

c++;

if (isVowel(c))

{

return c;

}

}

}

}


Write a program to accept a string from user and display the words that are having repeating characters.

 import java.util.Scanner;

import java.util.Random;

public class Main

{

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String inputString = scanner.nextLine();

String[] words = inputString.split(" ");

System.out.println("Words with repeating characters:");

for (String word : words)

{

    if (hasRepeatingCharacters(word))

    {

        System.out.println(word);

    }

}

scanner.close();

}

private static boolean hasRepeatingCharacters(String word)

{

    for (int I = 0; I < word.length() - 1; I++)

    {

        char currentChar = word.charAt(I);

        for (int j = I + 1; j < word.length(); j++)

        {

            if (currentChar == word.charAt(j))

            {

                return true;

            }

        }

    }

        return false;

}

   

}



Enter a string: bbn bnb vbn xcdxx

Words with repeating characters:

bbn

bnb

xcdxx



Write a program to form a square Matrix of characters and display the row and column having the max valued characters .

 Write a program to form a square Matrix of characters and display the row and column having the max valued characters .


import java.util.Scanner;

import java.util.Random;

public class Main

{

public static void main(String[] args) {

int size = 5;

char[][] matrix = generateRandomMatrix(size);

System.out.println("Matrix:");

displayMatrix(matrix);

int[] maxIndices = findMaxValueIndices(matrix);

int maxRow = maxIndices[0];

int maxCol = maxIndices[1];

System.out.println("\nRow and column with maximum valued character:");

System.out.println("Row: " + maxRow);

System.out.println("Column: " + maxCol);

}

public static char[][] generateRandomMatrix(int size)

{

char[][] matrix = new char[size][size];

Random random = new Random();

for (int i = 0; i < size; i++)

{

for (int j = 0; j < size; j++)

{

matrix[i][j] = (char) (random.nextInt(26) + 'A');

}

}

return matrix;

}

public static void displayMatrix(char[][] matrix)

{

int size = matrix.length;

for (int i = 0; i < size; i++)

{

for (int j = 0; j < size; j++)

{

System.out.print(matrix[i][j] + " " );

}

System.out.println();

}

}

public static int[] findMaxValueIndices(char[][] matrix)

{

int size = matrix.length;

int maxRow = 0;

int maxCol = 0;

int maxValue = matrix[maxRow][maxCol];

for (int i = 0; i < size; i++)

{

for (int j = 0; j < size; j++)

{

if (matrix[i][j] > maxValue) 

{

maxRow = i;

maxCol = j;

maxValue = matrix[i][j];

}

}

}

return new int[] { maxRow, maxCol };

}

}



Matrix:

L T B G E 

R I K G Q 

W R L O D 

S X V O B 

B Y U O G 


Row and column with maximum valued character:

Row: 4

Column: 1


Fascinating Number

 import java.util.Scanner;


public class Main

{

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

scanner.close();

if (isFascinatingNumber(number))

{

System.out.println(number + " is a fascinating number.");

}

else

{

System.out.println(number + " is not a fascinating number.");

}

}

private static boolean isFascinatingNumber(int number)

{

String concatenatedNumber = String.valueOf(number) + String.valueOf(number * 2) + String.valueOf(number * 3);

int digitCount = countDigits(concatenatedNumber);

int[] frequency = new int[10];

for (int i = 0; i < digitCount; i++)

{

char digitChar = concatenatedNumber.charAt(i);

if (!Character.isDigit(digitChar) || frequency[digitChar - '0'] > 0) 

{

return false;

}

frequency[digitChar - '0']++;

}

return true;

}

private static int countDigits(String number)

{

return number.length();

}

}

KaprekarNumbers

 KaprekarNumbers


import java.util.Scanner;


public class Main

{

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the value of p: ");

        int p = scanner.nextInt();

        System.out.print("Enter the value of q (where p < q): ");

        int q = scanner.nextInt();

        scanner.close();

        if (p >= q)

        {

            System.out.println("Invalid input. Please make sure p < q.");

            return;

        }

        int count = countKaprekarNumbers(p, q);

        System.out.println("Number of Kaprekar numbers between " + p + " and " + q + ": " + count);

        }

        private static int countKaprekarNumbers(int p, int q) 

        {

            int count = 0;

            for (int num = p; num <= q; num++)

            {

                if (isKaprekarNumber(num))

                {

                    System.out.println(num+" ");

                    count++;

                }

            }

            return count;

        }

        private static boolean isKaprekarNumber(int num)

        {

            long square = (long) num * num;

            String squareStr = String.valueOf(square);

            for (int i = 1; i < squareStr.length(); i++)

            {

                String leftStr = squareStr.substring(0, i);

                String rightStr = squareStr.substring(i);

                int left = (leftStr.isEmpty()) ? 0 : Integer.parseInt(leftStr);

                int right = (rightStr.isEmpty()) ? 0 : Integer.parseInt(rightStr);

                if (left + right == num && left > 0 && right > 0)

                {

                    

                    return true;

                }

            }

        return false;

        }

}

Enter the value of p: 1
Enter the value of q (where p < q): 100
45 
55 
99 
Number of Kaprekar numbers between 1 and 100: 4



 4

 3

 2

 1